CloudFormation 基础
模板结构
AWSTemplateFormatVersion: '2010-09-09'
Description: '我的应用栈'
Parameters:
Environment:
Type: String
AllowedValues: [dev, staging, prod]
Default: dev
Conditions:
IsProd: !Equals [!Ref Environment, prod]
Resources:
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub 'my-app-${Environment}-${AWS::AccountId}'
Outputs:
BucketArn:
Value: !GetAtt MyBucket.Arn
Export:
Name: !Sub '${AWS::StackName}-BucketArn'
参数与伪参数
Parameters:
InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.micro, t3.small, t3.medium]
DBPassword:
Type: String
NoEcho: true # 在控制台中隐藏
# 伪参数(始终可用)
# AWS::AccountId - 账户 ID
# AWS::Region - 区域
# AWS::StackName - 栈名称
# 内置函数
!Ref ParameterName
!Sub 'Hello ${AWS::Region}'
!GetAtt Resource.Attribute
!If [IsProd, t3.large, t3.micro]
资源示例
Resources:
WebServerSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Web server SG
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
WebServer:
Type: AWS::EC2::Instance
DependsOn: WebServerSG
Properties:
InstanceType: !Ref InstanceType
ImageId: !FindInMap [RegionAMI, !Ref AWS::Region, ami]
SecurityGroupIds: [!Ref WebServerSG]
跨栈引用
# 栈 A 导出
Outputs:
VpcId:
Value: !Ref MyVPC
Export:
Name: NetworkStack-VpcId
# 栈 B 导入
Resources:
AppServer:
Type: AWS::EC2::Instance
Properties:
SubnetId: !ImportValue NetworkStack-SubnetId
栈操作与变更集
# 创建栈
aws cloudformation create-stack \
--stack-name my-stack \
--template-body file://template.yaml \
--capabilities CAPABILITY_IAM
# 创建变更集(更新前预览)
aws cloudformation create-change-set \
--stack-name my-stack \
--change-set-name my-changes \
--template-body file://template.yaml
# 查看并执行变更集
aws cloudformation describe-change-set \
--stack-name my-stack --change-set-name my-changes
aws cloudformation execute-change-set \
--stack-name my-stack --change-set-name my-changes
漂移检测
# 检测配置漂移
aws cloudformation detect-stack-drift --stack-name my-stack
aws cloudformation describe-stack-drift-detection-status \
--stack-drift-detection-id abc123