Search code examples
amazon-web-servicesyamlaws-cloudformation

Start cfn-init in Ubuntu instance with cloudformation (yaml)


I try to start the cfn-init with:

Fn::Base64: !Sub | 
  #!/bin/bash
  sudo apt-get -y install python-setuptools
  mkdir aws-cfn-bootstrap-latest
  curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1
  sudo easy_install aws-cfn-bootstrap-latest
  sudo /usr/local/bin/cfn-init --stack !Ref 'AWS::StackName' --resource xxx --region !Ref 'AWS::Region'

The first steps work. I can access the instance and cfn-init is installed. When I execute the cfn-init --stack.. command inside my ec2 instance it works fine when I hardcode the values for stackname and region.

How to make it work in the yaml script? It seems it can not read the values for StackName and region.


Solution

  • If you are using !Sub you need to wrap your variables with ${} instead of using !Ref

    Try this

    Fn::Base64: !Sub | 
      #!/bin/bash
      sudo apt-get -y install python-setuptools
      mkdir aws-cfn-bootstrap-latest
      curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1
      sudo easy_install aws-cfn-bootstrap-latest
      sudo /usr/local/bin/cfn-init --stack ${AWS::StackName} --resource xxx --region ${AWS::Region}
    

    If you specify template parameter names or resource logical IDs, such as ${InstanceTypeParameter}, AWS CloudFormation returns the same values as if you used the Ref intrinsic function. If you specify resource attributes, such as ${MyInstance.PublicIp}, AWS CloudFormation returns the same values as if you used the Fn::GetAtt intrinsic function.

    For more details check AWS - Fn::Sub