【问题标题】:Is there a way to do inheritance or code reuse in an AWS CloudFormation template?有没有办法在 AWS CloudFormation 模板中进行继承或代码重用?
【发布时间】:2015-04-27 19:05:46
【问题描述】:

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

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

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

【问题讨论】:

    标签: amazon-web-services amazon-cloudformation aws-code-deploy


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案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 确实只对非常小的模板很方便。

      【讨论】:

        猜你喜欢
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 2017-02-06
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多