

# 使用 Guard 验证模板
<a name="cloudformation-guard"></a>

AWS CloudFormation Guard（`cfn-guard`）是一种策略即代码工具。您可以编写描述必需或禁止配置的规则，然后根据这些规则检查 JSON 或 YAML 数据。例如，您可以要求模板中的每个 Amazon S3 存储桶都使用加密。

有关本地验证的限制以及部署前需采取的步骤，请参阅[了解验证范围](template-guide.md#template-validation-scope)。

**Topics**
+ [安装 Guard](#cloudformation-guard-install)
+ [编写规则](#cloudformation-guard-write-rule)
+ [验证模板](#cloudformation-guard-validate)
+ [向您的工作流添加 Guard](#cloudformation-guard-integrate)
+ [了解更多](#cloudformation-guard-learn-more)

## 安装 Guard
<a name="cloudformation-guard-install"></a>

在 macOS 上，使用 Homebrew 安装 Guard：

```
brew install cloudformation-guard
```

有关 Linux、Windows、其他 macOS 安装方法和版本验证，请参阅[设置 AWS CloudFormation Guard](https://docs.aws.amazon.com/cfn-guard/latest/ug/setting-up.html)。

## 编写规则
<a name="cloudformation-guard-write-rule"></a>

将规则保存为扩展名为 `.guard` 的文件。以下示例要求模板中的每个 Amazon S3 存储桶都指定存储桶加密：

```
let s3_buckets = Resources.*[ Type == 'AWS::S3::Bucket' ]

rule S3_BUCKET_ENCRYPTED when %s3_buckets !empty {
  %s3_buckets {
    Properties.BucketEncryption exists
  }
}
```

有关规则语法和更多示例，请参阅[编写 AWS CloudFormation Guard 规则](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html)。

## 验证模板
<a name="cloudformation-guard-validate"></a>

将规则文件传递给 `--rules`，将模板传递给 `--data`：

```
cfn-guard validate --rules rules.guard --data template.yaml
```

模板通过后，该命令将返回退出状态 `0`。如果规则失败，则输出会识别失败的规则。您还可以将目录传递给 `--rules` 和 `--data` 以检查多个文件。

在自动工作流中使用规则之前，请使用内置的单元测试支持对其进行测试。有关说明，请参阅 [Testing AWS CloudFormation Guard rules](https://docs.aws.amazon.com/cfn-guard/latest/ug/testing-rules.html)。

## 向您的工作流添加 Guard
<a name="cloudformation-guard-integrate"></a>

您可以在本地、自动构建中或 Git 提交之前运行 Guard。CloudFormation 语言服务器也可以在您编辑模板时运行 Guard 规则包。有关设置，请参阅[CloudFormation 语言服务器](ide-extension.md)。

要在 CloudFormation 和 Cloud Control API 操作期间强制执行规则，请使用 Guard Hooks。有关更多信息，请参阅 [Guard Hooks](https://docs.aws.amazon.com/cloudformation-cli/latest/hooks-userguide/guard-hooks.html)。

## 了解更多
<a name="cloudformation-guard-learn-more"></a>

有关完整的语言和命令参考，请参阅《AWS CloudFormation Guard 用户指南》[https://docs.aws.amazon.com/cfn-guard/latest/ug/what-is-guard.html](https://docs.aws.amazon.com/cfn-guard/latest/ug/what-is-guard.html)。源代码和发布信息可在 [GitHub 上的 AWS CloudFormation Guard 存储库](https://github.com/aws-cloudformation/cloudformation-guard)中找到。