mcpField
C
cloudformation

cloudformation

github.com/itsmostafaクラウド・DevOps1.2k131 回インストール4 日前に更新
リポジトリ

cloudformation について

開発者やインフラチーム向けの AWS CloudFormation リファレンススキルです。テンプレートによるプロビジョニング、スタック操作、変更確認、複数アカウント・リージョンへのデプロイ、障害対応を扱います。

主な機能

  1. 01JSON または YAML テンプレートでリソースを定義
  2. 02スタックの作成と管理
  3. 03変更セットによる更新内容の確認
  4. 04複数アカウント・リージョンへのスタック展開
  5. 05テンプレートの検証と障害診断

活用シーン

  1. 01環境間で一貫したインフラ構築
  2. 02スタック更新前の変更内容の確認
  3. 03ネストされたスタックによる複雑な構成の整理
  4. 04デプロイ失敗やリソースのドリフトの調査

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/itsmostafa/aws-agent-skills --skill cloudformation

インストール後、Claude Code で/cloudformationを入力して読み込まれたか確認します。

同梱ファイルtemplate-patterns.md

詳細

AWS CloudFormation

AWS CloudFormation は、テンプレートを使用して AWS リソースをプロビジョニングおよび管理します。インフラストラクチャをコードとして定義し、バージョン管理して、環境間で一貫性のあるデプロイを実現できます。

目次

主な概念

テンプレート

AWS リソースを定義する JSON または YAML ファイルです。主なセクションは次のとおりです。

  • Parameters:入力値
  • Mappings:静的なルックアップテーブル
  • Conditions:条件付きリソース作成
  • Resources:AWS リソース(必須)
  • Outputs:戻り値
スタック

単一の単位として管理されるリソースの集合です。テンプレートから作成されます。

変更セット

更新を実行する前に、変更内容をプレビューします。

スタックセット

複数のアカウントやリージョンにスタックをデプロイします。

一般的なパターン

基本的なテンプレート構造
AWSTemplateFormatVersion: '2010-09-09'
Description: My infrastructure template

Parameters:
  Environment:
    Type: String
    AllowedValues: [dev, staging, prod]
    Default: dev

Mappings:
  EnvironmentConfig:
    dev:
      InstanceType: t3.micro
    prod:
      InstanceType: t3.large

Conditions:
  IsProd: !Equals [!Ref Environment, prod]

Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub 'my-app-${Environment}-${AWS::AccountId}'
      VersioningConfiguration:
        Status: !If [IsProd, Enabled, Suspended]

Outputs:
  BucketName:
    Description: S3 bucket name
    Value: !Ref MyBucket
    Export:
      Name: !Sub '${AWS::StackName}-BucketName'
スタックをデプロイする

AWS CLI:

# Create stack
aws cloudformation create-stack \
  --stack-name my-stack \
  --template-body file://template.yaml \
  --parameters ParameterKey=Environment,ParameterValue=prod \
  --capabilities CAPABILITY_IAM

# Wait for completion
aws cloudformation wait stack-create-complete --stack-name my-stack

# Update stack
aws cloudformation update-stack \
  --stack-name my-stack \
  --template-body file://template.yaml \
  --parameters ParameterKey=Environment,ParameterValue=prod

# Delete stack
aws cloudformation delete-stack --stack-name my-stack
変更セットを使用する
# Create change set
aws cloudformation create-change-set \
  --stack-name my-stack \
  --change-set-name my-changes \
  --template-body file://template.yaml \
  --parameters ParameterKey=Environment,ParameterValue=prod

# Describe changes
aws cloudformation describe-change-set \
  --stack-name my-stack \
  --change-set-name my-changes

# Execute change set
aws cloudformation execute-change-set \
  --stack-name my-stack \
  --change-set-name my-changes
Lambda 関数
Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub '${AWS::StackName}-function'
      Runtime: python3.12
      Handler: index.handler
      Role: !GetAtt LambdaRole.Arn
      Code:
        ZipFile: |
          def handler(event, context):
              return {'statusCode': 200, 'body': 'Hello'}
      Environment:
        Variables:
          ENVIRONMENT: !Ref Environment

  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
サブネットを含む VPC
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-vpc'

  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true

  PrivateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: 10.0.10.0/24

  InternetGateway:
    Type: AWS::EC2::InternetGateway

  AttachGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC

  PublicRoute:
    Type: AWS::EC2::Route
    DependsOn: AttachGateway
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  PublicSubnet1RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet1
      RouteTableId: !Ref PublicRouteTable
DynamoDB テーブル
Resources:
  OrdersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub '${AWS::StackName}-orders'
      AttributeDefinitions:
        - AttributeName: PK
          AttributeType: S
        - AttributeName: SK
          AttributeType: S
        - AttributeName: GSI1PK
          AttributeType: S
        - AttributeName: GSI1SK
          AttributeType: S
      KeySchema:
        - AttributeName: PK
          KeyType: HASH
        - AttributeName: SK
          KeyType: RANGE
      GlobalSecondaryIndexes:
        - IndexName: GSI1
          KeySchema:
            - AttributeName: GSI1PK
              KeyType: HASH
            - AttributeName: GSI1SK
              KeyType: RANGE
          Projection:
            ProjectionType: ALL
      BillingMode: PAY_PER_REQUEST
      PointInTimeRecoverySpecification:
        PointInTimeRecoveryEnabled: true

CLI リファレンス

スタック操作
コマンド説明
aws cloudformation create-stackスタックを作成
aws cloudformation update-stackスタックを更新
aws cloudformation delete-stackスタックを削除
aws cloudformation describe-stacksスタック情報を取得
aws cloudformation list-stacksスタックを一覧表示
aws cloudformation describe-stack-eventsイベントを取得
aws cloudformation describe-stack-resourcesリソースを取得
変更セット
コマンド説明
aws cloudformation create-change-set変更セットを作成
aws cloudformation describe-change-set変更内容を表示
aws cloudformation execute-change-set変更を適用
aws cloudformation delete-change-set変更セットを削除
テンプレート
コマンド説明
aws cloudformation validate-templateテンプレートを検証
aws cloudformation get-templateスタックテンプレートを取得
aws cloudformation get-template-summaryテンプレート情報を取得

ベストプラクティス

テンプレートの設計
  • 環境固有の値にはパラメータを使用する
  • 静的なルックアップテーブルにはマッピングを使用する
  • オプションのリソースには条件を使用する
  • スタック間の参照には出力をエクスポートする
  • パラメータと出力に説明を追加する
セキュリティ
  • アクセスキーの代わりにIAM ロールを使用する
  • 本番環境では終了保護を有効にする
  • リソースを保護するにはスタックポリシーを使用する
  • シークレットをハードコードしない — Secrets Manager を使用する
# Enable termination protection
aws cloudformation update-termination-protection \
  --stack-name my-stack \
  --enable-termination-protection
構成
  • 複雑なインフラストラクチャにはネストされたスタックを使用する
  • 再利用可能なモジュールを作成する
  • テンプレートをバージョン管理する
  • 一貫した命名規則を使用する
信頼性
  • 明示的な依存関係にはDependsOn を使用する
  • インスタンスに作成ポリシーを設定する
  • Auto Scaling グループには更新ポリシーを使用する
  • ロールバックトリガーを実装する

トラブルシューティング

スタックの作成に失敗した場合
# Get failure reason
aws cloudformation describe-stack-events \
  --stack-name my-stack \
  --query 'StackEvents[?ResourceStatus==`CREATE_FAILED`]'

# Common causes:
# - IAM permissions
# - Resource limits
# - Invalid property values
# - Dependency failures
スタックが DELETE_FAILED の状態で止まった場合
# Identify resources that couldn't be deleted
aws cloudformation describe-stack-resources \
  --stack-name my-stack \
  --query 'StackResources[?ResourceStatus==`DELETE_FAILED`]'

# Retry with resources to skip
aws cloudformation delete-stack \
  --stack-name my-stack \
  --retain-resources ResourceLogicalId1 ResourceLogicalId2
ドリフト検出
# Detect drift
aws cloudformation detect-stack-drift --stack-name my-stack

# Check drift status
aws cloudformation describe-stack-drift-detection-status \
  --stack-drift-detection-id abc123

# View drifted resources
aws cloudformation describe-stack-resource-drifts \
  --stack-name my-stack
ロールバックに失敗した場合
# Continue update rollback
aws cloudformation continue-update-rollback \
  --stack-name my-stack \
  --resources-to-skip ResourceLogicalId1

参考資料

コメント