Claude Skill

cloudformation

AWS CloudFormation infrastructure as code for stack management. Use when writing templates, deploying stacks, managing drift, troubleshooting deployments, or organizing infrastructure with nested stacks.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download itsmostafa-aws-agent-skills-skills_cloudformation-e786d25.zip · 5 KB
Part of itsmostafa/aws-agent-skills — 17 skills

Install

skills CLI npx skills add https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/cloudformation
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install itsmostafa-aws-agent-skills@llmmart
Git git clone https://github.com/itsmostafa/aws-agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole itsmostafa/aws-agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

AWS CloudFormation

AWS CloudFormation provisions and manages AWS resources using templates. Define infrastructure as code, version control it, and deploy consistently across environments.

Table of Contents

Core Concepts

Templates

JSON or YAML files defining AWS resources. Key sections:

  • Parameters: Input values
  • Mappings: Static lookup tables
  • Conditions: Conditional resource creation
  • Resources: AWS resources (required)
  • Outputs: Return values

Stacks

Collection of resources managed as a single unit. Created from templates.

Change Sets

Preview changes before executing updates.

Stack Sets

Deploy stacks across multiple accounts and regions.

Common Patterns

Basic Template Structure

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'

Deploy a Stack

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

Use Change Sets

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

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 with Subnets

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 Table

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 Reference

Stack Operations

Command Description
aws cloudformation create-stack Create stack
aws cloudformation update-stack Update stack
aws cloudformation delete-stack Delete stack
aws cloudformation describe-stacks Get stack info
aws cloudformation list-stacks List stacks
aws cloudformation describe-stack-events Get events
aws cloudformation describe-stack-resources Get resources

Change Sets

Command Description
aws cloudformation create-change-set Create change set
aws cloudformation describe-change-set View changes
aws cloudformation execute-change-set Apply changes
aws cloudformation delete-change-set Delete change set

Template

Command Description
aws cloudformation validate-template Validate template
aws cloudformation get-template Get stack template
aws cloudformation get-template-summary Get template info

Best Practices

Template Design

  • Use parameters for environment-specific values
  • Use mappings for static lookup tables
  • Use conditions for optional resources
  • Export outputs for cross-stack references
  • Add descriptions to parameters and outputs

Security

  • Use IAM roles instead of access keys
  • Enable termination protection for production
  • Use stack policies to protect resources
  • Never hardcode secrets — use Secrets Manager
# Enable termination protection
aws cloudformation update-termination-protection \
  --stack-name my-stack \
  --enable-termination-protection

Organization

  • Use nested stacks for complex infrastructure
  • Create reusable modules
  • Version control templates
  • Use consistent naming conventions

Reliability

  • Use DependsOn for explicit dependencies
  • Configure creation policies for instances
  • Use update policies for Auto Scaling groups
  • Implement rollback triggers

Troubleshooting

Stack Creation Failed

# 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

Stack Stuck in 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

Drift Detection

# 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

Rollback Failed

# Continue update rollback
aws cloudformation continue-update-rollback \
  --stack-name my-stack \
  --resources-to-skip ResourceLogicalId1

References

Files (aws-agent-skills)
  • SKILL.md 9.6 KB
    ---
    name: cloudformation
    description: AWS CloudFormation infrastructure as code for stack management. Use when writing templates, deploying stacks, managing drift, troubleshooting deployments, or organizing infrastructure with nested stacks.
    last_updated: "2026-01-07"
    doc_source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/
    ---
    
    # AWS CloudFormation
    
    AWS CloudFormation provisions and manages AWS resources using templates. Define infrastructure as code, version control it, and deploy consistently across environments.
    
    ## Table of Contents
    
    - [Core Concepts](#core-concepts)
    - [Common Patterns](#common-patterns)
    - [CLI Reference](#cli-reference)
    - [Best Practices](#best-practices)
    - [Troubleshooting](#troubleshooting)
    - [References](#references)
    
    ## Core Concepts
    
    ### Templates
    
    JSON or YAML files defining AWS resources. Key sections:
    - **Parameters**: Input values
    - **Mappings**: Static lookup tables
    - **Conditions**: Conditional resource creation
    - **Resources**: AWS resources (required)
    - **Outputs**: Return values
    
    ### Stacks
    
    Collection of resources managed as a single unit. Created from templates.
    
    ### Change Sets
    
    Preview changes before executing updates.
    
    ### Stack Sets
    
    Deploy stacks across multiple accounts and regions.
    
    ## Common Patterns
    
    ### Basic Template Structure
    
    ```yaml
    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'
    ```
    
    ### Deploy a Stack
    
    **AWS CLI:**
    
    ```bash
    # 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
    ```
    
    ### Use Change Sets
    
    ```bash
    # 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 Function
    
    ```yaml
    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 with Subnets
    
    ```yaml
    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 Table
    
    ```yaml
    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 Reference
    
    ### Stack Operations
    
    | Command | Description |
    |---------|-------------|
    | `aws cloudformation create-stack` | Create stack |
    | `aws cloudformation update-stack` | Update stack |
    | `aws cloudformation delete-stack` | Delete stack |
    | `aws cloudformation describe-stacks` | Get stack info |
    | `aws cloudformation list-stacks` | List stacks |
    | `aws cloudformation describe-stack-events` | Get events |
    | `aws cloudformation describe-stack-resources` | Get resources |
    
    ### Change Sets
    
    | Command | Description |
    |---------|-------------|
    | `aws cloudformation create-change-set` | Create change set |
    | `aws cloudformation describe-change-set` | View changes |
    | `aws cloudformation execute-change-set` | Apply changes |
    | `aws cloudformation delete-change-set` | Delete change set |
    
    ### Template
    
    | Command | Description |
    |---------|-------------|
    | `aws cloudformation validate-template` | Validate template |
    | `aws cloudformation get-template` | Get stack template |
    | `aws cloudformation get-template-summary` | Get template info |
    
    ## Best Practices
    
    ### Template Design
    
    - **Use parameters** for environment-specific values
    - **Use mappings** for static lookup tables
    - **Use conditions** for optional resources
    - **Export outputs** for cross-stack references
    - **Add descriptions** to parameters and outputs
    
    ### Security
    
    - **Use IAM roles** instead of access keys
    - **Enable termination protection** for production
    - **Use stack policies** to protect resources
    - **Never hardcode secrets** — use Secrets Manager
    
    ```bash
    # Enable termination protection
    aws cloudformation update-termination-protection \
      --stack-name my-stack \
      --enable-termination-protection
    ```
    
    ### Organization
    
    - **Use nested stacks** for complex infrastructure
    - **Create reusable modules**
    - **Version control templates**
    - **Use consistent naming conventions**
    
    ### Reliability
    
    - **Use DependsOn** for explicit dependencies
    - **Configure creation policies** for instances
    - **Use update policies** for Auto Scaling groups
    - **Implement rollback triggers**
    
    ## Troubleshooting
    
    ### Stack Creation Failed
    
    ```bash
    # 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
    ```
    
    ### Stack Stuck in DELETE_FAILED
    
    ```bash
    # 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
    ```
    
    ### Drift Detection
    
    ```bash
    # 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
    ```
    
    ### Rollback Failed
    
    ```bash
    # Continue update rollback
    aws cloudformation continue-update-rollback \
      --stack-name my-stack \
      --resources-to-skip ResourceLogicalId1
    ```
    
    ## References
    
    - [CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)
    - [CloudFormation API Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/)
    - [CloudFormation CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/)
    - [Resource and Property Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)
    
  • template-patterns.md 8.5 KB
    # CloudFormation Template Patterns
    
    Advanced template patterns and techniques.
    
    ## Intrinsic Functions
    
    ### Reference Functions
    
    ```yaml
    # Reference a resource or parameter
    !Ref MyResource
    
    # Get attribute from resource
    !GetAtt MyLambda.Arn
    !GetAtt MyBucket.DomainName
    !GetAtt MyBucket.RegionalDomainName
    
    # Import from another stack
    !ImportValue other-stack-BucketName
    ```
    
    ### String Functions
    
    ```yaml
    # Substitution
    !Sub 'arn:aws:s3:::${BucketName}/*'
    !Sub
      - 'arn:aws:s3:::${Bucket}/*'
      - Bucket: !Ref MyBucket
    
    # Join
    !Join
      - ','
      - - !Ref Subnet1
        - !Ref Subnet2
    
    # Split
    !Split [',', !Ref SubnetList]
    
    # Select
    !Select [0, !GetAZs '']
    !Select [1, !Split [',', !Ref SubnetList]]
    ```
    
    ### Conditional Functions
    
    ```yaml
    Conditions:
      IsProd: !Equals [!Ref Environment, prod]
      HasBucket: !Not [!Equals [!Ref BucketName, '']]
      IsProdAndHasBucket: !And [!Condition IsProd, !Condition HasBucket]
      IsDevOrStaging: !Or
        - !Equals [!Ref Environment, dev]
        - !Equals [!Ref Environment, staging]
    
    Resources:
      MyResource:
        Type: AWS::S3::Bucket
        Condition: IsProd
        Properties:
          BucketName: !If
            - IsProd
            - !Sub 'prod-${AWS::StackName}'
            - !Sub 'dev-${AWS::StackName}'
    ```
    
    ### Transform Functions
    
    ```yaml
    # Include from S3
    !Transform
      Name: AWS::Include
      Parameters:
        Location: s3://my-bucket/snippet.yaml
    
    # Use macros
    Transform: AWS::Serverless-2016-10-31
    ```
    
    ## Parameters
    
    ### Comprehensive Parameter Types
    
    ```yaml
    Parameters:
      # String with validation
      ProjectName:
        Type: String
        MinLength: 3
        MaxLength: 20
        AllowedPattern: ^[a-z][a-z0-9-]*$
        ConstraintDescription: Must start with letter, lowercase alphanumeric and hyphens
    
      # Constrained values
      Environment:
        Type: String
        AllowedValues: [dev, staging, prod]
        Default: dev
    
      # Number with range
      InstanceCount:
        Type: Number
        MinValue: 1
        MaxValue: 10
        Default: 2
    
      # AWS-specific types
      VpcId:
        Type: AWS::EC2::VPC::Id
      SubnetIds:
        Type: List<AWS::EC2::Subnet::Id>
      KeyPair:
        Type: AWS::EC2::KeyPair::KeyName
      AMI:
        Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
        Default: /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2
    
      # Secrets (NoEcho)
      DatabasePassword:
        Type: String
        NoEcho: true
        MinLength: 8
    ```
    
    ## Mappings
    
    ```yaml
    Mappings:
      RegionAMI:
        us-east-1:
          HVM64: ami-0123456789abcdef0
          HVM32: ami-0987654321fedcba0
        us-west-2:
          HVM64: ami-abcdef01234567890
          HVM32: ami-fedcba0987654321
    
      EnvironmentConfig:
        dev:
          InstanceType: t3.micro
          MinSize: 1
          MaxSize: 2
        prod:
          InstanceType: t3.large
          MinSize: 2
          MaxSize: 10
    
    Resources:
      Instance:
        Type: AWS::EC2::Instance
        Properties:
          ImageId: !FindInMap [RegionAMI, !Ref 'AWS::Region', HVM64]
          InstanceType: !FindInMap [EnvironmentConfig, !Ref Environment, InstanceType]
    ```
    
    ## Cross-Stack References
    
    ### Stack A (Exporter)
    
    ```yaml
    Resources:
      VPC:
        Type: AWS::EC2::VPC
        Properties:
          CidrBlock: 10.0.0.0/16
    
    Outputs:
      VpcId:
        Value: !Ref VPC
        Export:
          Name: !Sub '${AWS::StackName}-VpcId'
    
      VpcCidr:
        Value: !GetAtt VPC.CidrBlock
        Export:
          Name: !Sub '${AWS::StackName}-VpcCidr'
    ```
    
    ### Stack B (Importer)
    
    ```yaml
    Parameters:
      NetworkStackName:
        Type: String
        Default: network-stack
    
    Resources:
      SecurityGroup:
        Type: AWS::EC2::SecurityGroup
        Properties:
          VpcId: !ImportValue
            Fn::Sub: '${NetworkStackName}-VpcId'
          SecurityGroupIngress:
            - IpProtocol: tcp
              FromPort: 443
              ToPort: 443
              CidrIp: !ImportValue
                Fn::Sub: '${NetworkStackName}-VpcCidr'
    ```
    
    ## Nested Stacks
    
    ### Parent Stack
    
    ```yaml
    Resources:
      NetworkStack:
        Type: AWS::CloudFormation::Stack
        Properties:
          TemplateURL: https://s3.amazonaws.com/my-bucket/network.yaml
          Parameters:
            Environment: !Ref Environment
    
      ComputeStack:
        Type: AWS::CloudFormation::Stack
        DependsOn: NetworkStack
        Properties:
          TemplateURL: https://s3.amazonaws.com/my-bucket/compute.yaml
          Parameters:
            VpcId: !GetAtt NetworkStack.Outputs.VpcId
            SubnetIds: !GetAtt NetworkStack.Outputs.SubnetIds
    ```
    
    ## Resource Policies
    
    ### Creation Policy
    
    ```yaml
    Resources:
      AutoScalingGroup:
        Type: AWS::AutoScaling::AutoScalingGroup
        CreationPolicy:
          ResourceSignal:
            Count: !Ref DesiredCapacity
            Timeout: PT15M
        Properties:
          # ...
    
      LaunchTemplate:
        Type: AWS::EC2::LaunchTemplate
        Properties:
          LaunchTemplateData:
            UserData:
              Fn::Base64: !Sub |
                #!/bin/bash
                # ... setup ...
                /opt/aws/bin/cfn-signal -e $? \
                  --stack ${AWS::StackName} \
                  --resource AutoScalingGroup \
                  --region ${AWS::Region}
    ```
    
    ### Update Policy
    
    ```yaml
    Resources:
      AutoScalingGroup:
        Type: AWS::AutoScaling::AutoScalingGroup
        UpdatePolicy:
          AutoScalingRollingUpdate:
            MinInstancesInService: 1
            MaxBatchSize: 1
            PauseTime: PT10M
            WaitOnResourceSignals: true
          AutoScalingScheduledAction:
            IgnoreUnmodifiedGroupSizeProperties: true
    ```
    
    ### Deletion Policy
    
    ```yaml
    Resources:
      Database:
        Type: AWS::RDS::DBInstance
        DeletionPolicy: Snapshot
        UpdateReplacePolicy: Snapshot
        Properties:
          # ...
    
      LogBucket:
        Type: AWS::S3::Bucket
        DeletionPolicy: Retain
        Properties:
          # ...
    ```
    
    ## Custom Resources
    
    ### Lambda-Backed Custom Resource
    
    ```yaml
    Resources:
      CustomResourceLambda:
        Type: AWS::Lambda::Function
        Properties:
          Runtime: python3.12
          Handler: index.handler
          Role: !GetAtt CustomResourceRole.Arn
          Timeout: 300
          Code:
            ZipFile: |
              import cfnresponse
              import boto3
    
              def handler(event, context):
                  try:
                      if event['RequestType'] == 'Create':
                          # Create logic
                          response_data = {'Result': 'Created'}
                      elif event['RequestType'] == 'Update':
                          # Update logic
                          response_data = {'Result': 'Updated'}
                      elif event['RequestType'] == 'Delete':
                          # Delete logic
                          response_data = {'Result': 'Deleted'}
    
                      cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
                  except Exception as e:
                      cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})
    
      MyCustomResource:
        Type: Custom::MyResource
        Properties:
          ServiceToken: !GetAtt CustomResourceLambda.Arn
          Parameter1: !Ref SomeParameter
    ```
    
    ## Stack Policies
    
    ### Prevent Updates to Critical Resources
    
    ```json
    {
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "Update:*",
          "Principal": "*",
          "Resource": "*"
        },
        {
          "Effect": "Deny",
          "Action": "Update:Replace",
          "Principal": "*",
          "Resource": "LogicalResourceId/ProductionDatabase"
        },
        {
          "Effect": "Deny",
          "Action": "Update:Delete",
          "Principal": "*",
          "Resource": "*",
          "Condition": {
            "StringEquals": {
              "ResourceType": ["AWS::RDS::DBInstance"]
            }
          }
        }
      ]
    }
    ```
    
    Apply stack policy:
    
    ```bash
    aws cloudformation set-stack-policy \
      --stack-name my-stack \
      --stack-policy-body file://stack-policy.json
    ```
    
    ## Rollback Configuration
    
    ```bash
    aws cloudformation create-stack \
      --stack-name my-stack \
      --template-body file://template.yaml \
      --rollback-configuration '{
        "RollbackTriggers": [
          {
            "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:alarm:HighErrorRate",
            "Type": "AWS::CloudWatch::Alarm"
          }
        ],
        "MonitoringTimeInMinutes": 10
      }'
    ```
    
    ## Transform Macros
    
    ### Using AWS::Serverless
    
    ```yaml
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    
    Globals:
      Function:
        Runtime: python3.12
        Timeout: 30
    
    Resources:
      MyFunction:
        Type: AWS::Serverless::Function
        Properties:
          Handler: app.handler
          CodeUri: ./src
          Events:
            Api:
              Type: Api
              Properties:
                Path: /items
                Method: GET
    ```
    
    ### Using AWS::LanguageExtensions
    
    ```yaml
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::LanguageExtensions
    
    Resources:
      # Use Fn::ForEach
      Fn::ForEach::Buckets:
        - BucketName
        - [logs, data, backup]
        - '${BucketName}Bucket':
            Type: AWS::S3::Bucket
            Properties:
              BucketName: !Sub 'my-app-${BucketName}-${AWS::AccountId}'
    ```
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related