cloudformation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS CloudFormation

AWS CloudFormation

AWS CloudFormation provisions and manages AWS resources using templates. Define infrastructure as code, version control it, and deploy consistently across environments.
AWS CloudFormation 通过模板来预置和管理AWS资源。将基础设施定义为代码,进行版本控制,并在不同环境中一致部署。

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
定义AWS资源的JSON或YAML文件。关键部分:
  • Parameters(参数):输入值
  • Mappings(映射):静态查找表
  • Conditions(条件):条件化资源创建
  • Resources(资源):AWS资源(必填)
  • Outputs(输出):返回值

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'
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
undefined
AWS CLI:
bash
undefined

Create stack

创建堆栈

aws cloudformation create-stack
--stack-name my-stack
--template-body file://template.yaml
--parameters ParameterKey=Environment,ParameterValue=prod
--capabilities CAPABILITY_IAM
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
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
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
undefined
aws cloudformation delete-stack --stack-name my-stack
undefined

Use Change Sets

使用变更集

bash
undefined
bash
undefined

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
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
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
undefined
aws cloudformation execute-change-set
--stack-name my-stack
--change-set-name my-changes
undefined

Lambda Function

Lambda函数

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

带子网的VPC

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

DynamoDB表

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

CLI参考

Stack Operations

堆栈操作

CommandDescription
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
命令描述
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
获取堆栈资源

Change Sets

变更集

CommandDescription
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
命令描述
aws cloudformation create-change-set
创建变更集
aws cloudformation describe-change-set
查看变更内容
aws cloudformation execute-change-set
应用变更
aws cloudformation delete-change-set
删除变更集

Template

模板

CommandDescription
aws cloudformation validate-template
Validate template
aws cloudformation get-template
Get stack template
aws cloudformation get-template-summary
Get template info
命令描述
aws cloudformation validate-template
验证模板
aws cloudformation get-template
获取堆栈模板
aws cloudformation get-template-summary
获取模板信息

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
undefined
  • 使用IAM角色而非访问密钥
  • 为生产环境启用终止保护
  • 使用堆栈策略保护资源
  • 切勿硬编码密钥——使用Secrets Manager
bash
undefined

Enable termination protection

启用终止保护

aws cloudformation update-termination-protection
--stack-name my-stack
--enable-termination-protection
undefined
aws cloudformation update-termination-protection
--stack-name my-stack
--enable-termination-protection
undefined

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
  • 使用DependsOn定义显式依赖
  • 为实例配置创建策略
  • 为Auto Scaling组配置更新策略
  • 实现回滚触发器

Troubleshooting

故障排查

Stack Creation Failed

堆栈创建失败

bash
undefined
bash
undefined

Get failure reason

获取失败原因

aws cloudformation describe-stack-events
--stack-name my-stack
--query 'StackEvents[?ResourceStatus==
CREATE_FAILED
]'
aws cloudformation describe-stack-events
--stack-name my-stack
--query 'StackEvents[?ResourceStatus==
CREATE_FAILED
]'

Common causes:

常见原因:

- IAM permissions

- IAM权限问题

- Resource limits

- 资源配额限制

- Invalid property values

- 无效属性值

- Dependency failures

- 依赖项创建失败

undefined
undefined

Stack Stuck in DELETE_FAILED

堆栈卡在DELETE_FAILED状态

bash
undefined
bash
undefined

Identify resources that couldn't be deleted

识别无法删除的资源

aws cloudformation describe-stack-resources
--stack-name my-stack
--query 'StackResources[?ResourceStatus==
DELETE_FAILED
]'
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
undefined
aws cloudformation delete-stack
--stack-name my-stack
--retain-resources ResourceLogicalId1 ResourceLogicalId2
undefined

Drift Detection

漂移检测

bash
undefined
bash
undefined

Detect drift

检测漂移

aws cloudformation detect-stack-drift --stack-name my-stack
aws cloudformation detect-stack-drift --stack-name my-stack

Check drift status

检查漂移检测状态

aws cloudformation describe-stack-drift-detection-status
--stack-drift-detection-id abc123
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
undefined
aws cloudformation describe-stack-resource-drifts
--stack-name my-stack
undefined

Rollback Failed

回滚失败

bash
undefined
bash
undefined

Continue update rollback

继续更新回滚

aws cloudformation continue-update-rollback
--stack-name my-stack
--resources-to-skip ResourceLogicalId1
undefined
aws cloudformation continue-update-rollback
--stack-name my-stack
--resources-to-skip ResourceLogicalId1
undefined

References

参考资料