Search code examples
amazon-web-servicesyamlaws-cloudformationstring-interpolation

Why do I need an extra element in AWS CloudFormation for interpolating variables


I am trying to pass user data to an EC2 instance created in Cloudformation, using the following:

      UserData: !Base64
        'Fn::Join':
          - ''
          - - |
              #!/bin/bash -xe
              echo '
            - !Ref 'someVar'
            - |
              ' > /tmp/some-content

which works. Here is the expanded user data (btw, I also don't know why there is a new line after echo ' but that is not the main question):

#!/bin/bash -xe
echo '
some string passed as parameter' > /tmp/some-content

But if I remove the - from the !Ref part, it treats !Ref as a string:

      UserData: !Base64
        'Fn::Join':
          - ''
          - - |
              #!/bin/bash -xe
              echo '
              !Ref 'License'
              ' > /tmp/some-content

Here is the expanded user data.

#!/bin/bash -xe
echo '
!Ref 'someVar'
' > /tmp/some-content

Why is this happening? Is this a cloudformation internal thing, that expands !Ref variables only if they are alone as an element in a list?


Solution

  • Wouldn't be it just easier to do this this way:

      UserData: 
        Fn::Base64: !Sub |
              #!/bin/bash -xe 
              echo "${someVar}" > /tmp/some-content
    

    Basically there is no need to use Join and suffer. use !Sub | which is much less painful to work with. The code is much more readable and much easier to manage.