【发布时间】:2017-05-16 22:38:19
【问题描述】:
在 Cloudformation 中,我有两个堆栈(一个嵌套)。
嵌套堆栈“ec2-setup”:
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Parameters" : {
// (...) some parameters here
"userData" : {
"Description" : "user data to be passed to instance",
"Type" : "String",
"Default": ""
}
},
"Resources" : {
"EC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"UserData" : { "Ref" : "userData" },
// (...) some other properties here
}
}
},
// (...)
}
现在在我的主模板中,我想引用上面介绍的嵌套模板并使用 userData 参数传递一个 bash 脚本。此外,我不想内联用户数据脚本的内容,因为我想为少数几个 ec2 实例重用它(所以我不想每次在我的主模板中声明 ec2 实例时都复制脚本)。
我试图通过将脚本的内容设置为参数的默认值来实现这一点:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters" : {
"myUserData": {
"Type": "String",
"Default" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash \n",
"yum update -y \n",
"# Install the files and packages from the metadata\n",
"echo 'tralala' > /tmp/hahaha"
]]}}
}
},
(...)
"myEc2": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "s3://path/to/ec2-setup.json",
"TimeoutInMinutes": "10",
"Parameters": {
// (...)
"userData" : { "Ref" : "myUserData" }
}
但在尝试启动堆栈时出现以下错误:
"模板验证错误:模板格式错误:Every Default 成员必须是字符串。”
该错误似乎是由于声明 { Fn::Base64 (...) } 是一个对象而不是字符串(尽管它导致返回 base64 编码的字符串)这一事实引起的。
一切正常,如果我在调用嵌套模板时将脚本直接粘贴到参数部分(作为内联脚本)(而不是将字符串设置为参数):
"myEc2": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "s3://path/to/ec2-setup.json",
"TimeoutInMinutes": "10",
"Parameters": {
// (...)
"userData" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash \n",
"yum update -y \n",
"# Install the files and packages from the metadata\n",
"echo 'tralala' > /tmp/hahaha"
]]}}
}
但我想将userData 脚本的内容保留在参数/变量中以便能够重用它。
有没有机会重复使用这样的 bash 脚本而无需每次都复制/粘贴?
【问题讨论】:
-
不幸的是,内部函数(
Fn::Base64、Fn::Join和朋友)不能在参数部分中使用。见docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/…。此外,如果您在Parameters部分中使用默认值,它仍然会在 2 个脚本中重复。
标签: linux amazon-web-services amazon-ec2 amazon-cloudformation