

# 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>

Guard は、ローカルに実行、自動構築で実行、または Git コミット前に実行できます。CloudFormation 言語サーバーは、テンプレートの編集中に Guard ルールパックを実行することもできます。セットアップについては、「[CloudFormation 言語サーバー](ide-extension.md)」を参照してください。

CloudFormation および Cloud Control の API オペレーション中にルールを適用するには、Guard Hook を使用します。詳細については、「[Guard Hook](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)」を参照してください。ソースコードとリリース情報は、[GitHub の AWS CloudFormation Guard リポジトリ](https://github.com/aws-cloudformation/cloudformation-guard)で入手できます。