{"id":"cloudformation","name":"cloudformation","summary":"AWS CloudFormationインフラストラクチャをスタック管理用のコードとして使います。テンプレート作成、スタックのデプロイ、ドリフト管理、デプロイのトラブルシューティング、またはネストスタックを用いたインフラの整理などに利用可能です。","body":"# AWS CloudFormation\n\nAWS CloudFormation provisions and manages AWS resources using templates. Define infrastructure as code, version control it, and deploy consistently across environments.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### Templates\n\nJSON or YAML files defining AWS resources. Key sections:\n- **Parameters**: Input values\n- **Mappings**: Static lookup tables\n- **Conditions**: Conditional resource creation\n- **Resources**: AWS resources (required)\n- **Outputs**: Return values\n\n### Stacks\n\nCollection of resources managed as a single unit. Created from templates.\n\n### Change Sets\n\nPreview changes before executing updates.\n\n### Stack Sets\n\nDeploy stacks across multiple accounts and regions.\n\n## Common Patterns\n\n### Basic Template Structure\n\n```yaml\nAWSTemplateFormatVersion: '2010-09-09'\nDescription: My infrastructure template\n\nParameters:\n  Environment:\n    Type: String\n    AllowedValues: [dev, staging, prod]\n    Default: dev\n\nMappings:\n  EnvironmentConfig:\n    dev:\n      InstanceType: t3.micro\n    prod:\n      InstanceType: t3.large\n\nConditions:\n  IsProd: !Equals [!Ref Environment, prod]\n\nResources:\n  MyBucket:\n    Type: AWS::S3::Bucket\n    Properties:\n      BucketName: !Sub 'my-app-${Environment}-${AWS::AccountId}'\n      VersioningConfiguration:\n        Status: !If [IsProd, Enabled, Suspended]\n\nOutputs:\n  BucketName:\n    Description: S3 bucket name\n    Value: !Ref MyBucket\n    Export:\n      Name: !Sub '${AWS::StackName}-BucketName'\n```\n\n### Deploy a Stack\n\n**AWS CLI:**\n\n```bash\n# Create stack\naws cloudformation create-stack \\\n  --stack-name my-stack \\\n  --template-body file://template.yaml \\\n  --parameters ParameterKey=Environment,ParameterValue=prod \\\n  --capabilities CAPABILITY_IAM\n\n# Wait for completion\naws cloudformation wait stack-create-complete --stack-name my-stack\n\n# Update stack\naws cloudformation update-stack \\\n  --stack-name my-stack \\\n  --template-body file://template.yaml \\\n  --parameters ParameterKey=Environment,ParameterValue=prod\n\n# Delete stack\naws cloudformation delete-stack --stack-name my-stack\n```\n\n### Use Change Sets\n\n```bash\n# Create change set\naws cloudformation create-change-set \\\n  --stack-name my-stack \\\n  --change-set-name my-changes \\\n  --template-body file://template.yaml \\\n  --parameters ParameterKey=Environment,ParameterValue=prod\n\n# Describe changes\naws cloudformation describe-change-set \\\n  --stack-name my-stack \\\n  --change-set-name my-changes\n\n# Execute change set\naws cloudformation execute-change-set \\\n  --stack-name my-stack \\\n  --change-set-name my-changes\n```\n\n### Lambda Function\n\n```yaml\nResources:\n  LambdaFunction:\n    Type: AWS::Lambda::Function\n    Properties:\n      FunctionName: !Sub '${AWS::StackName}-function'\n      Runtime: python3.12\n      Handler: index.handler\n      Role: !GetAtt LambdaRole.Arn\n      Code:\n        ZipFile: |\n          def handler(event, context):\n              return {'statusCode': 200, 'body': 'Hello'}\n      Environment:\n        Variables:\n          ENVIRONMENT: !Ref Environment\n\n  LambdaRole:\n    Type: AWS::IAM::Role\n    Properties:\n      AssumeRolePolicyDocument:\n        Version: '2012-10-17'\n        Statement:\n          - Effect: Allow\n            Principal:\n              Service: lambda.amazonaws.com\n            Action: sts:AssumeRole\n      ManagedPolicyArns:\n        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole\n```\n\n### VPC with Subnets\n\n```yaml\nResources:\n  VPC:\n    Type: AWS::EC2::VPC\n    Properties:\n      CidrBlock: 10.0.0.0/16\n      EnableDnsHostnames: true\n      Tags:\n        - Key: Name\n          Value: !Sub '${AWS::StackName}-vpc'\n\n  PublicSubnet1:\n    Type: AWS::EC2::Subnet\n    Properties:\n      VpcId: !Ref VPC\n      AvailabilityZone: !Select [0, !GetAZs '']\n      CidrBlock: 10.0.1.0/24\n      MapPublicIpOnLaunch: true\n\n  PrivateSubnet1:\n    Type: AWS::EC2::Subnet\n    Properties:\n      VpcId: !Ref VPC\n      AvailabilityZone: !Select [0, !GetAZs '']\n      CidrBlock: 10.0.10.0/24\n\n  InternetGateway:\n    Type: AWS::EC2::InternetGateway\n\n  AttachGateway:\n    Type: AWS::EC2::VPCGatewayAttachment\n    Properties:\n      VpcId: !Ref VPC\n      InternetGatewayId: !Ref InternetGateway\n\n  PublicRouteTable:\n    Type: AWS::EC2::RouteTable\n    Properties:\n      VpcId: !Ref VPC\n\n  PublicRoute:\n    Type: AWS::EC2::Route\n    DependsOn: AttachGateway\n    Properties:\n      RouteTableId: !Ref PublicRouteTable\n      DestinationCidrBlock: 0.0.0.0/0\n      GatewayId: !Ref InternetGateway\n\n  PublicSubnet1RouteTableAssociation:\n    Type: AWS::EC2::SubnetRouteTableAssociation\n    Properties:\n      SubnetId: !Ref PublicSubnet1\n      RouteTableId: !Ref PublicRouteTable\n```\n\n### DynamoDB Table\n\n```yaml\nResources:\n  OrdersTable:\n    Type: AWS::DynamoDB::Table\n    Properties:\n      TableName: !Sub '${AWS::StackName}-orders'\n      AttributeDefinitions:\n        - AttributeName: PK\n          AttributeType: S\n        - AttributeName: SK\n          AttributeType: S\n        - AttributeName: GSI1PK\n          AttributeType: S\n        - AttributeName: GSI1SK\n          AttributeType: S\n      KeySchema:\n        - AttributeName: PK\n          KeyType: HASH\n        - AttributeName: SK\n          KeyType: RANGE\n      GlobalSecondaryIndexes:\n        - IndexName: GSI1\n          KeySchema:\n            - AttributeName: GSI1PK\n              KeyType: HASH\n            - AttributeName: GSI1SK\n              KeyType: RANGE\n          Projection:\n            ProjectionType: ALL\n      BillingMode: PAY_PER_REQUEST\n      PointInTimeRecoverySpecification:\n        PointInTimeRecoveryEnabled: true\n```\n\n## CLI Reference\n\n### Stack Operations\n\n| Command | Description |\n|---------|-------------|\n| `aws cloudformation create-stack` | Create stack |\n| `aws cloudformation update-stack` | Update stack |\n| `aws cloudformation delete-stack` | Delete stack |\n| `aws cloudformation describe-stacks` | Get stack info |\n| `aws cloudformation list-stacks` | List stacks |\n| `aws cloudformation describe-stack-events` | Get events |\n| `aws cloudformation describe-stack-resources` | Get resources |\n\n### Change Sets\n\n| Command | Description |\n|---------|-------------|\n| `aws cloudformation create-change-set` | Create change set |\n| `aws cloudformation describe-change-set` | View changes |\n| `aws cloudformation execute-change-set` | Apply changes |\n| `aws cloudformation delete-change-set` | Delete change set |\n\n### Template\n\n| Command | Description |\n|---------|-------------|\n| `aws cloudformation validate-template` | Validate template |\n| `aws cloudformation get-template` | Get stack template |\n| `aws cloudformation get-template-summary` | Get template info |\n\n## Best Practices\n\n### Template Design\n\n- **Use parameters** for environment-specific values\n- **Use mappings** for static lookup tables\n- **Use conditions** for optional resources\n- **Export outputs** for cross-stack references\n- **Add descriptions** to parameters and outputs\n\n### Security\n\n- **Use IAM roles** instead of access keys\n- **Enable termination protection** for production\n- **Use stack policies** to protect resources\n- **Never hardcode secrets** — use Secrets Manager\n\n```bash\n# Enable termination protection\naws cloudformation update-termination-protection \\\n  --stack-name my-stack \\\n  --enable-termination-protection\n```\n\n### Organization\n\n- **Use nested stacks** for complex infrastructure\n- **Create reusable modules**\n- **Version control templates**\n- **Use consistent naming conventions**\n\n### Reliability\n\n- **Use DependsOn** for explicit dependencies\n- **Configure creation policies** for instances\n- **Use update policies** for Auto Scaling groups\n- **Implement rollback triggers**\n\n## Troubleshooting\n\n### Stack Creation Failed\n\n```bash\n# Get failure reason\naws cloudformation describe-stack-events \\\n  --stack-name my-stack \\\n  --query 'StackEvents[?ResourceStatus==`CREATE_FAILED`]'\n\n# Common causes:\n# - IAM permissions\n# - Resource limits\n# - Invalid property values\n# - Dependency failures\n```\n\n### Stack Stuck in DELETE_FAILED\n\n```bash\n# Identify resources that couldn't be deleted\naws cloudformation describe-stack-resources \\\n  --stack-name my-stack \\\n  --query 'StackResources[?ResourceStatus==`DELETE_FAILED`]'\n\n# Retry with resources to skip\naws cloudformation delete-stack \\\n  --stack-name my-stack \\\n  --retain-resources ResourceLogicalId1 ResourceLogicalId2\n```\n\n### Drift Detection\n\n```bash\n# Detect drift\naws cloudformation detect-stack-drift --stack-name my-stack\n\n# Check drift status\naws cloudformation describe-stack-drift-detection-status \\\n  --stack-drift-detection-id abc123\n\n# View drifted resources\naws cloudformation describe-stack-resource-drifts \\\n  --stack-name my-stack\n```\n\n### Rollback Failed\n\n```bash\n# Continue update rollback\naws cloudformation continue-update-rollback \\\n  --stack-name my-stack \\\n  --resources-to-skip ResourceLogicalId1\n```\n\n## References\n\n- [CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)\n- [CloudFormation API Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/)\n- [CloudFormation CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/)\n- [Resource and Property Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/cloudformation","license":"MIT","category":"writing","lang":"en","tokens":2260,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"template-patterns.md","size":8693,"sha256":"d396285079c3650befaa6e27cbe5e58e84f1cf663ca73d131cdabcfdcb165850"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["docs.aws.amazon.com","s3.amazonaws.com"]}}