关于 cloudformation
面向开发者和基础设施团队的 AWS CloudFormation 参考技能,介绍模板化资源配置、堆栈管理、变更预览、跨账户和区域部署及故障排查。
主要功能
- 01用 JSON 或 YAML 模板定义资源
- 02创建和管理堆栈
- 03通过变更集预览更新
- 04跨账户和区域部署堆栈
- 05验证模板并诊断故障
适用场景
- 01在多个环境中一致地配置基础设施
- 02在更新堆栈前审查拟议变更
- 03用嵌套堆栈组织复杂基础设施
- 04排查部署失败或资源偏差
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ itsmostafa/ aws-agent-skills --skill cloudformation安装后在 Claude Code 中输入/cloudformation确认已加载。
附带文件template-patterns.md
详细介绍
AWS CloudFormation
AWS CloudFormation 使用模板预置和管理 AWS 资源。将基础设施定义为代码,进行版本控制,并在各个环境中一致地部署。
目录
核心概念
模板
用于定义 AWS 资源的 JSON 或 YAML 文件。主要部分:
- 参数:输入值
- 映射:静态查找表
- 条件:有条件地创建资源
- 资源:AWS 资源(必需)
- 输出:返回值
堆栈
作为一个整体进行管理的资源集合。根据模板创建。
更改集
在执行更新前预览更改。
堆栈集
跨多个账户和区域部署堆栈。
常见模式
基本模板结构
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'
部署堆栈
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
使用更改集
# 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 函数
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
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 表
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 参考
堆栈操作
| 命令 | 说明 |
|---|---|
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 | 获取资源 |
更改集
| 命令 | 说明 |
|---|---|
aws cloudformation create-change-set | 创建更改集 |
aws cloudformation describe-change-set | 查看更改 |
aws cloudformation execute-change-set | 应用更改 |
aws cloudformation delete-change-set | 删除更改集 |
模板
| 命令 | 说明 |
|---|---|
aws cloudformation validate-template | 验证模板 |
aws cloudformation get-template | 获取堆栈模板 |
aws cloudformation get-template-summary | 获取模板信息 |
最佳实践
模板设计
- 使用参数指定特定于环境的值
- 使用映射创建静态查找表
- 使用条件创建可选资源
- 导出输出以供跨堆栈引用
- 为参数和输出添加说明
安全性
- 使用 IAM 角色,而非访问密钥
- 为生产环境启用终止保护
- 使用堆栈策略保护资源
- 切勿硬编码密钥——请使用 Secrets Manager
# Enable termination protection
aws cloudformation update-termination-protection \
--stack-name my-stack \
--enable-termination-protection
组织管理
- 使用嵌套堆栈管理复杂基础设施
- 创建可重用模块
- 对模板进行版本控制
- 采用一致的命名约定
可靠性
- 使用 DependsOn明确指定依赖关系
- 为实例配置创建策略
- 为 Auto Scaling 组使用更新策略
- 实施回滚触发条件
故障排除
堆栈创建失败
# 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
堆栈卡在 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
漂移检测
# 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
回滚失败
# Continue update rollback
aws cloudformation continue-update-rollback \
--stack-name my-stack \
--resources-to-skip ResourceLogicalId1
参考资料
评论
支持 Markdown