cloudformation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS 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
undefinedAWS CLI:
bash
undefinedCreate stack
创建堆栈
aws cloudformation create-stack
--stack-name my-stack
--template-body file://template.yaml
--parameters ParameterKey=Environment,ParameterValue=prod
--capabilities CAPABILITY_IAM
--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
--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
--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
--stack-name my-stack
--template-body file://template.yaml
--parameters ParameterKey=Environment,ParameterValue=prod
Delete stack
删除堆栈
aws cloudformation delete-stack --stack-name my-stack
undefinedaws cloudformation delete-stack --stack-name my-stack
undefinedUse Change Sets
使用变更集
bash
undefinedbash
undefinedCreate 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
--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
--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
--stack-name my-stack
--change-set-name my-changes
aws cloudformation describe-change-set
--stack-name my-stack
--change-set-name my-changes
--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
--stack-name my-stack
--change-set-name my-changes
undefinedaws cloudformation execute-change-set
--stack-name my-stack
--change-set-name my-changes
--stack-name my-stack
--change-set-name my-changes
undefinedLambda 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/AWSLambdaBasicExecutionRoleyaml
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/AWSLambdaBasicExecutionRoleVPC 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 PublicRouteTableyaml
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 PublicRouteTableDynamoDB 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: trueyaml
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: trueCLI Reference
CLI参考
Stack Operations
堆栈操作
| Command | Description |
|---|---|
| Create stack |
| Update stack |
| Delete stack |
| Get stack info |
| List stacks |
| Get events |
| Get resources |
| 命令 | 描述 |
|---|---|
| 创建堆栈 |
| 更新堆栈 |
| 删除堆栈 |
| 获取堆栈信息 |
| 列出堆栈 |
| 获取堆栈事件 |
| 获取堆栈资源 |
Change Sets
变更集
| Command | Description |
|---|---|
| Create change set |
| View changes |
| Apply changes |
| Delete change set |
| 命令 | 描述 |
|---|---|
| 创建变更集 |
| 查看变更内容 |
| 应用变更 |
| 删除变更集 |
Template
模板
| Command | Description |
|---|---|
| Validate template |
| Get stack template |
| 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
undefined- 使用IAM角色而非访问密钥
- 为生产环境启用终止保护
- 使用堆栈策略保护资源
- 切勿硬编码密钥——使用Secrets Manager
bash
undefinedEnable termination protection
启用终止保护
aws cloudformation update-termination-protection
--stack-name my-stack
--enable-termination-protection
--stack-name my-stack
--enable-termination-protection
undefinedaws cloudformation update-termination-protection
--stack-name my-stack
--enable-termination-protection
--stack-name my-stack
--enable-termination-protection
undefinedOrganization
组织管理
- 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
undefinedbash
undefinedGet failure reason
获取失败原因
aws cloudformation describe-stack-events
--stack-name my-stack
--query 'StackEvents[?ResourceStatus==]'
--stack-name my-stack
--query 'StackEvents[?ResourceStatus==
CREATE_FAILEDaws cloudformation describe-stack-events
--stack-name my-stack
--query 'StackEvents[?ResourceStatus==]'
--stack-name my-stack
--query 'StackEvents[?ResourceStatus==
CREATE_FAILEDCommon causes:
常见原因:
- IAM permissions
- IAM权限问题
- Resource limits
- 资源配额限制
- Invalid property values
- 无效属性值
- Dependency failures
- 依赖项创建失败
undefinedundefinedStack Stuck in DELETE_FAILED
堆栈卡在DELETE_FAILED状态
bash
undefinedbash
undefinedIdentify resources that couldn't be deleted
识别无法删除的资源
aws cloudformation describe-stack-resources
--stack-name my-stack
--query 'StackResources[?ResourceStatus==]'
--stack-name my-stack
--query 'StackResources[?ResourceStatus==
DELETE_FAILEDaws cloudformation describe-stack-resources
--stack-name my-stack
--query 'StackResources[?ResourceStatus==]'
--stack-name my-stack
--query 'StackResources[?ResourceStatus==
DELETE_FAILEDRetry with resources to skip
跳过指定资源重试删除
aws cloudformation delete-stack
--stack-name my-stack
--retain-resources ResourceLogicalId1 ResourceLogicalId2
--stack-name my-stack
--retain-resources ResourceLogicalId1 ResourceLogicalId2
undefinedaws cloudformation delete-stack
--stack-name my-stack
--retain-resources ResourceLogicalId1 ResourceLogicalId2
--stack-name my-stack
--retain-resources ResourceLogicalId1 ResourceLogicalId2
undefinedDrift Detection
漂移检测
bash
undefinedbash
undefinedDetect 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
--stack-drift-detection-id abc123
aws cloudformation describe-stack-drift-detection-status
--stack-drift-detection-id abc123
--stack-drift-detection-id abc123
View drifted resources
查看漂移资源
aws cloudformation describe-stack-resource-drifts
--stack-name my-stack
--stack-name my-stack
undefinedaws cloudformation describe-stack-resource-drifts
--stack-name my-stack
--stack-name my-stack
undefinedRollback Failed
回滚失败
bash
undefinedbash
undefinedContinue update rollback
继续更新回滚
aws cloudformation continue-update-rollback
--stack-name my-stack
--resources-to-skip ResourceLogicalId1
--stack-name my-stack
--resources-to-skip ResourceLogicalId1
undefinedaws cloudformation continue-update-rollback
--stack-name my-stack
--resources-to-skip ResourceLogicalId1
--stack-name my-stack
--resources-to-skip ResourceLogicalId1
undefined