Get the FREE Ultimate OpenClaw Setup Guide →

cloudformation

Scanned
npx machina-cli add skill itsmostafa/aws-agent-skills/cloudformation --openclaw
Files (1)
SKILL.md
9.6 KB

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

CommandDescription
aws cloudformation create-stackCreate stack
aws cloudformation update-stackUpdate stack
aws cloudformation delete-stackDelete stack
aws cloudformation describe-stacksGet stack info
aws cloudformation list-stacksList stacks
aws cloudformation describe-stack-eventsGet events
aws cloudformation describe-stack-resourcesGet resources

Change Sets

CommandDescription
aws cloudformation create-change-setCreate change set
aws cloudformation describe-change-setView changes
aws cloudformation execute-change-setApply changes
aws cloudformation delete-change-setDelete change set

Template

CommandDescription
aws cloudformation validate-templateValidate template
aws cloudformation get-templateGet stack template
aws cloudformation get-template-summaryGet 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

Source

git clone https://github.com/itsmostafa/aws-agent-skills/blob/main/skills/cloudformation/SKILL.mdView on GitHub

Overview

AWS CloudFormation provisions and manages AWS resources using templates. Define infrastructure as code, version control it, and deploy consistently across environments. It supports drift detection, nested stacks, and StackSets for scalable deployments.

How This Skill Works

You author templates in JSON or YAML with sections like Parameters, Mappings, Resources, and Outputs. CloudFormation creates a stack from the template, and you can preview changes with Change Sets or extend deployments with StackSets to cover multiple accounts and regions.

When to Use It

  • When creating or updating AWS infrastructure from templates to ensure consistency across environments.
  • When deploying resources across multiple accounts or regions using StackSets.
  • When you want to preview changes before applying them with Change Sets.
  • When organizing complex infrastructure with modular, reusable templates and nested stacks.
  • When troubleshooting deployments, detecting drift, or needing controlled rollbacks.

Quick Start

  1. Step 1: Create a YAML or JSON CloudFormation template that defines Parameters, Resources, and Outputs.
  2. Step 2: Deploy the template with the AWS CLI (create-stack or update-stack) or use a Change Set.
  3. Step 3: Monitor stack events and, if needed, iterate changes with updates or new Change Sets.

Best Practices

  • Store templates in version control and tag stack versions for traceability.
  • Parameterize templates and use nested stacks to keep templates modular and reusable.
  • Use Change Sets to review proposed changes before applying them to a live stack.
  • Enable drift detection and monitor stack status to identify unintended changes.
  • Follow least-privilege IAM practices and validate templates before deployment.

Example Use Cases

  • Basic Template Structure in YAML/JSON showing Parameters, Mappings, Resources, and Outputs.
  • Deploy a stack via AWS CLI using aws cloudformation create-stack or deploy.
  • Use Change Sets to preview and then execute updates to an existing stack.
  • A Lambda Function defined in a CloudFormation template with role and code.
  • A VPC with Subnets and related resources defined in a CloudFormation template.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers