有没有办法在AWS CloudFormation模板中进行继承或代码重用?

问题描述 投票:2回答:2

我正在构建一个CloudFormation模板,其中包含使用LaunchConfiguration的AWS::AutoScaling::LaunchConfigurationAWS::AutoScaling::AutoScalingGroup。对于我的堆栈,我将需要多个AutoScalingGroups,但我希望它们位于不同的安全组中。

我也将使用CodeDeploy,因此我的LaunchConfiguration包含Metadata和UserData属性以安装和运行CodeDeploy代理(如http://s3.amazonaws.com/aws-codedeploy-us-east-1/templates/latest/CodeDeploy_SampleCF_Template.json第262行所示)。因为我必须在LaunchConfiguration而不是AutoScalingGroup中指定安全组,所以我必须在模板中有多个LaunchConfiguration副本,只有一行差异。

有没有办法减少冗长的元数据和UserData部分在我的模板中出现的次数?我尝试创建映射,但它们只允许使用字母数字字符。

amazon-web-services amazon-cloudformation aws-code-deploy
2个回答
2
投票

编写代码来创建模板JSON而不是手动编写 - 然后您可以使用您选择的语言中可用的任何抽象来创建不同的LaunchConfiguration资源。

将地图和向量表示为文字的语言比那些不使用的语言更适合这种语言。

例如,Clojure文字

{"Type" "AWS::AutoScaling::LaunchConfiguration"
 "Properties" {"KeyName" {"Ref" "KeyName"}
               "ImageId" {"Ref" "AMI"}}}

可以自动转换为JSON字符串

{"Type":"AWS::AutoScaling::LaunchConfiguration",
 "Properties":{"ImageId":{"Ref":"AMI"},
               "KeyName":{"Ref":"KeyName"}}}

(虽然在实践中,您只会为完整模板创建JSON,而不是单个资源。)

然后你可以做一些事情

(defn launch-configuration
  [ami]
  {"Type" "AWS::AutoScaling::LaunchConfiguration"
   "Properties" {"KeyName" {"Ref" "KeyName"}
                 "ImageId" ami}})

(map launch-configuration ["ami1" "ami2" "ami3"])

创建多个类似的资源。

手工制作模板JSON实际上只对非常小的模板很方便。


0
投票

我最近发现了CDK。尚未使用它,但它似乎比直接写出所有模板代码更好。可以使用TypeScript,JavaScript,Java和C#定义资源,并对其进行编译以生成CloudFormation模板。使用Java创建堆栈的示例:

public class MyStack extends Stack {
    public MyStack(final App scopy, final String id) {
        this(scope, id, null);
    }

    public MyStack(final App scope, final String id, final StackProps props) {
        super(scope, id, props);

        new Bucket(this, "MyFirstBucket", BucketProps.builder()
            .withVersioned(true)
            .build());
    }
}

更多关于CDK:https://docs.aws.amazon.com/CDK/latest/userguide/what-is.html

© www.soinside.com 2019 - 2024. All rights reserved.