amazon-web-servicesamazon-ec2aws-cloudformation

AWS CloudFormation EC2 UserData - Using an "!If"


I'm creating a .bashrc file in the UserData portion of my CloudFormation Template

      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe

At this point, I want to use one of two statements based on a condition. Either

      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            echo "export JOIN_STR=${ExistingJoinString}" >> /home/ec2-user/.bashrc

or

      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            echo "export JOIN_STR=${CRDBIPNode01.PrimaryPrivateIpAddress},${CRDBIPNode02.PrimaryPrivateIpAddress},${CRDBIPNode03.PrimaryPrivateIpAddress}" >> /home/ec2-user/.bashrc

I already have a conditional defined:

Conditions: 
  UseNewJoinString: !Equals [!Ref ExistingJoinString, NONE]

Does anyone know of a way to use an "!If" statement, or any other hack I can use to control which statement ends up in my .bashrc. Something like this:

      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            !If
              - UseNewJoinString
              -
                echo "export JOIN_STR=${CRDBIPNode01.PrimaryPrivateIpAddress},${CRDBIPNode02.PrimaryPrivateIpAddress},${CRDBIPNode03.PrimaryPrivateIpAddress}" >> /home/ec2-user/.bashrc
              -
                echo "export JOIN_STR=${ExistingJoinString}" >> /home/ec2-user/.bashrc

Thanks in advance for help and insights.


Solution

  • I am currently learning CloudFormation and do not know all the tricks but would using a macro to modify the template be a possible solution?

    https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/macros-example.html