Home > OS >  AWS CloudFormation EC2 UserData - Using an "!If"
AWS CloudFormation EC2 UserData - Using an "!If"

Time:12-31

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.

CodePudding user response:

I chose to embed the "if" statement directly into my .bashrc

            echo "if [ '${ExistingJoinString}' = 'NONE' ]; then"  >> /home/ec2-user/.bashrc
            echo "  export JOIN_STR=${CRDBIPNode01.PrimaryPrivateIpAddress},${CRDBIPNode02.PrimaryPrivateIpAddress},${CRDBIPNode03.PrimaryPrivateIpAddress}" >> /home/ec2-user/.bashrc
            echo "else"  >> /home/ec2-user/.bashrc
            echo "  export JOIN_STR=${ExistingJoinString}" >> /home/ec2-user/.bashrc
            echo "fi"  >> /home/ec2-user/.bashrc

Not very happy with this solution, but it works. Still looking for better ideas.

CodePudding user response:

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

  • Related