【发布时间】:2019-06-13 19:22:55
【问题描述】:
我正在寻找一种方法来重构我的 Cloud Formation 模板中的重复值导入。
我有以下配置一个简单应用程序的模板:
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access into the server
Type: AWS::EC2::KeyPair::KeyName
S3StackName:
Description: Name of S3 Stack
Type: String
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Metadata:
AWS::CloudFormation::Init:
config:
packages:
yum:
httpd: []
php: []
files:
/var/www/html/index.html:
source:
Fn::Sub:
- https://s3.amazonaws.com/${bucketName}/index.html
- bucketName:
Fn::ImportValue:
!Sub "${S3StackName}-s3Bucket"
/var/www/html/styles.css:
source:
Fn::Sub:
- https://s3.amazonaws.com/${bucketName}/styles.css
- bucketName:
Fn::ImportValue:
!Sub "${S3StackName}-s3Bucket"
/var/www/html/script.js:
source:
Fn::Sub:
- https://s3.amazonaws.com/${bucketName}/script.js
- bucketName:
Fn::ImportValue:
!Sub "${S3StackName}-s3Bucket"
services:
sysvinit:
httpd:
enabled: true
ensureRunning: true
AWS::CloudFormation::Authentication:
S3AccessCreds:
type: S3
roleName: !Ref EC2InstanceRole
buckets:
-
Fn::ImportValue:
!Sub "${S3StackName}-s3Bucket"
Properties:
IamInstanceProfile: !Ref EC2InstanceProfile
InstanceType: t2.micro
ImageId: ami-1853ac65
SecurityGroupIds:
- !Ref MySecurityGroup
KeyName: !Ref KeyName
UserData:
'Fn::Base64':
!Sub |
#!/bin/bash -xe
# Ensure AWS CFN Bootstrap is the latest
yum install -y aws-cfn-bootstrap
# Install the files and packages from the metadata
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EC2Instance --region ${AWS::Region}
MySecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Open Ports 22 and 80
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: '80'
ToPort: '80'
CidrIp: 0.0.0.0/0
Outputs:
Website:
Description: The Public DNS for the EC2 Instance
Value: !Sub 'http://${EC2Instance.PublicDnsName}'
你会注意到有很多重复,特别是导入一个已经从现有堆栈中导出的值,例如:
Fn::Sub:
- https://s3.amazonaws.com/${bucketName}/index.html
- bucketName:
Fn::ImportValue:
!Sub "${S3StackName}-s3Bucket"
这个模式在我上面发布的模板中总共使用了 4 次。我想简化这一点,我不会一遍又一遍地重复相同的 YAML 块。
我的第一个想法是向模板的元数据部分添加一个值,但这不起作用,因为资源部分不能从元数据部分!Ref。
如何减少此模板中重复 YAML 的数量?
【问题讨论】:
标签: amazon-web-services yaml amazon-cloudformation