AWS CloudFormation - 在EC2上使用cfn-init共享用户数据脚本

时间:2017-06-16 16:45:42

标签: amazon-ec2 amazon-cloudformation user-data

我有一个像这样的实例资源:

testservice:
  Type: 'AWS::EC2::Instance'
  Metadata:
    AWS::CloudFormation::Init:
      configSets:
        serviceConfigSet:
          - serviceConfig
      serviceConfig:
        packages:
          yum:
            salt-minion: []
        commands:
          hostnameConfig:
            command: hostname test-service-1.0
        services:
          sysvinit:
            salt-minion:
              enabled: 'true'
              ensureRunning: 'true'
  Properties:
    ImageId: !Ref BaseServiceAmi
    KeyName: test_ssh_key
    SubnetId: !Ref ServiceSubnetId
    UserData:
      'Fn::Base64':
        'Fn::Sub': |
          #!/bin/bash

          yum update -y

          yum install -y aws-cfn-bootstrap

          /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource testservice --configsets serviceConfigSet --region ${AWS::Region}

但是,我想将UserData脚本移动到一个参数中,并在多个Instance资源中重用它。这应该是微不足道的,但我找不到在用户数据脚本中获取当前资源名称的方法(我在这部分中明确设置了它:--resource testservice)。

有没有办法可以通过引用从用户数据脚本中获取资源名称,这样我可以推广它?它不会出现在伪参数列表中。

1 个答案:

答案 0 :(得分:0)

我认为最好的选择是使用嵌套堆栈。如果您可以将“AWS :: EC2 :: Instance”资源中的所有设置转换为参数,则可以为该资源创建模板堆栈并从另一个模板中调用它。

快速信息: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html#stackpolicy

使用方法: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html

相关问题