View a markdown version of this page

使用 Guard 验证模板 - Amazon CloudFormation
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)。

使用 Guard 验证模板

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

有关本地验证的限制以及部署前需采取的步骤,请参阅了解验证范围。

安装 Guard

在 macOS 上,使用 Homebrew 安装 Guard:

brew install cloudformation-guard

有关 Linux、Windows、其他 macOS 安装方法和版本验证,请参阅设置 Amazon CloudFormation Guard。

编写规则

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

let s3_buckets = Resources.*[ Type == 'AWS::S3::Bucket' ] rule S3_BUCKET_ENCRYPTED when %s3_buckets !empty { %s3_buckets { Properties.BucketEncryption exists } }

有关规则语法和更多示例,请参阅编写 Amazon CloudFormation Guard 规则。

验证模板

将规则文件传递给 --rules,将模板传递给 --data:

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

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

在自动工作流中使用规则之前,请使用内置的单元测试支持对其进行测试。有关说明,请参阅 Testing Amazon CloudFormation Guard rules。

向您的工作流添加 Guard

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

要在 CloudFormation 和 Cloud Control API 操作期间强制执行规则,请使用 Guard Hooks。有关更多信息,请参阅 Guard Hooks。

了解更多

有关完整的语言和命令参考,请参阅《Amazon CloudFormation Guard 用户指南》https://docs.amazonaws.cn/cfn-guard/latest/ug/what-is-guard.html。源代码和发布信息可在 GitHub 上的 Amazon CloudFormation Guard 存储库中找到。