简体   繁体   中英

cfn-init for cloudformation launchtemplate

How do you use cfn-init within a LaunchTemplate? This is for EC2 instances, in an autoscaling group, for an ECS cluster.

Where does the Metadata section for the instance go and what is the --resource to pass to cnf-init ?

LaunchTemplate:
  Type: AWS::EC2::LaunchTemplate
  Properties:
    LaunchTemplateName: !Sub ${AWS::StackName}-launch-template
    LaunchTemplateData: 
      SecurityGroups: 
        - !Ref DMZSecurityGroup
        - !Ref ECSSecurityGroup
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            yum update -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource ??? --region ${AWS::Region}
            yum -y update

My best guess for Metadata produces the error:

    Property validation failure: [Encountered unsupported properties in {/LaunchTemplateData}: [Metadata]]

I had the metadata at the wrong nesting level, it should be at topmost level along with Type: and Properties: , not under Properties:LaunchTemplateData: .

LaunchTemplate:
  Type: AWS::EC2::LaunchTemplate
  Metadata: 
    AWS::CloudFormation::Init: 
      config:
        files:
          /var/www/html/index2.html:
            content: TestString
  Properties:
    LaunchTemplateData: 
      SecurityGroupIds: 
        - !GetAtt DMZSecurityGroup.GroupId
        - !GetAtt ECSSecurityGroup.GroupId
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            yum update -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource ECSLaunchTemplate --region ${AWS::Region}
            yum -y update

cfn-init should only be used if you define some initialisation steps for your instance in the cloudformation template itself.

The cfn-init scripts tells cloudformation to read your configuration steps from the template definition (the AWS::CloudFormation::Init section) and to 'execute' them on the instance.

You can also bootstrap your instance by passing a shell script in the user-data section.

In your case, as I can not see any bootstrap configuration steps defined in your YAML file, there is no need to call cfn-init in your user-data script.

More about cfn-init : https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html

More about AWS::CloudFormation::Init : https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM