Search code examples
amazon-web-servicescloudaws-cloudformationinfrastructure-as-code

Does using the Sub function in CloudFormation hinder the use of bash scripts?


I've got the following UserData in a CloudFormation LaunchTemplate for an Auto Scaling group. The first two commands are picked up with no problems, where the third doesn't get called. Without the Sub function, all goes well, but our code has developed to need that EBS variable to be passed in somewhere (not necessarily within the bash script, however). Is the way I've done this bad practice? If not, how might I ensure the final line gets executed?

          Fn::Base64: 
            !Sub 
              - |
                #!/bin/bash
                echo ${EBS} > /home/ubuntu/test.txt
                aws s3 cp s3://s3url/script.sh /home/ubuntu
                bash script.sh "$(curl http://169.254.169.254/latest/meta-data/local-ipv4)" "$(cat /home/ubuntu/test.txt)"
              - {EBS: !Ref DevEBS} 

I've used cloud-boothook, however placing this just before #!/bin/bash here just seems to lock users out of the instances created (the key doesn't get accepted?) when used with the Sub function.

An help is greatly appreciated!


Solution

  • You are copying your script to /home/ubuntu. But your userdata runs in the root folder. Thus your subsequent commands wil not work. You have to cd into /home/ubuntu:

              Fn::Base64: 
                !Sub 
                  - |
                    #!/bin/bash
                    echo ${EBS} > /home/ubuntu/test.txt
                    aws s3 cp s3://s3url/script.sh /home/ubuntu
                    cd  /home/ubuntu  
                    bash script.sh "$(curl http://169.254.169.254/latest/meta-data/local-ipv4)" "$(cat /home/ubuntu/test.txt)"
                  - {EBS: !Ref DevEBS}