

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Guard 驗證範本
<a name="cloudformation-guard"></a>

AWS CloudFormation Guard (`cfn-guard`) 是一種policy-as-code工具。您可以撰寫描述必要或禁止組態的規則，然後根據這些規則檢查 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` ，以檢查多個檔案。

在自動化工作流程中使用規則之前，請使用內建單元測試支援進行測試。如需說明，請參閱[測試 AWS CloudFormation Guard 規則](https://docs.aws.amazon.com/cfn-guard/latest/ug/testing-rules.html)。

## 將 Guard 新增至您的工作流程
<a name="cloudformation-guard-integrate"></a>

您可以在本機、自動化建置或在 Git 遞交之前執行 Guard。CloudFormation Language Server 也可以在您編輯範本時執行 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)。[AWS CloudFormation Guard GitHub 上的儲存庫](https://github.com/aws-cloudformation/cloudformation-guard)提供原始碼和版本資訊。