CloudFormation
AWS のインフラをテンプレート (YAML/JSON) で宣言的に定義・管理する IaC サービス
AWSIaC
CloudFormation とは
AWS CloudFormation は、AWS のインフラをテンプレート (YAML/JSON) で宣言的に定義し、スタックとして作成・更新・削除する IaC サービスである。SAM は CloudFormation の拡張、CDK は CloudFormation のコード生成ツール。
テンプレートの構造
AWSTemplateFormatVersion: '2010-09-09'
Description: My Stack
Parameters:
Environment:
Type: String
Default: dev
Resources:
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub users-${Environment}
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- { AttributeName: id, AttributeType: S }
KeySchema:
- { AttributeName: id, KeyType: HASH }
Outputs:
TableName:
Value: !Ref UsersTable
SAM / CDK との関係
CDK (TypeScript) → CloudFormation テンプレート → AWS リソース
SAM (YAML) → CloudFormation テンプレート → AWS リソース
CloudFormation → AWS リソース
| ツール | 入力 | 出力 |
|---|---|---|
| CloudFormation | YAML/JSON テンプレート | AWS リソース |
| SAM | サーバーレス拡張 YAML | CloudFormation テンプレート |
| CDK | TypeScript/Python | CloudFormation テンプレート |
組み込み関数
| 関数 | 用途 | 例 |
|---|---|---|
!Ref |
リソースの参照 | !Ref UsersTable |
!Sub |
文字列の置換 | !Sub users-${Environment} |
!GetAtt |
属性の取得 | !GetAtt UsersTable.Arn |
!Join |
文字列の結合 | !Join ['-', [my, stack]] |
!If |
条件分岐 | !If [IsProd, 5, 1] |
スタックの操作
# スタックの作成
aws cloudformation create-stack --stack-name my-stack --template-body file://template.yaml
# スタックの更新
aws cloudformation update-stack --stack-name my-stack --template-body file://template.yaml
# 変更セットの作成 (プレビュー)
aws cloudformation create-change-set --stack-name my-stack --template-body file://template.yaml
# スタックの削除
aws cloudformation delete-stack --stack-name my-stack
ドリフト検出
aws cloudformation detect-stack-drift --stack-name my-stack
手動変更 (コンソール操作) によるテンプレートと実態の乖離を検出する。
ロールバック
デプロイ失敗時に自動的に前の状態にロールバックする。--on-failure ROLLBACK がデフォルト。
CloudFormation を扱う関連書籍も多い。