Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]]
like image 763
gregn Avatar asked Feb 14 '19 13:02

gregn


People also ask

What is the CloudFormation helper script CFN-init used for?

cfn-init: Use to retrieve and interpret resource metadata, install packages, create files, and start services.

What is CFN-init?

The cfn-init helper script reads template metadata from the AWS::CloudFormation::Init key and acts accordingly to: Fetch and parse metadata from CloudFormation. Install packages. Write files to disk. Enable/disable and start/stop services.

What is CFN CloudFormation?

The CloudFormation CLI (cfn) allows you to author your own resource providers, hooks, and modules that can be used by CloudFormation.

How do you create a key pair using CloudFormation?

To create a new key pair, omit the PublicKeyMaterial property from the template. When Amazon EC2 creates a new key pair, the private key is saved to an AWS Systems Manager Parameter Store. The name of the Systems Manager parameter follows the format /ec2/keypair/{key_pair_id} .


1 Answers

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
like image 123
gregn Avatar answered Nov 16 '22 03:11

gregn