ColossusMark1
ColossusMark1

Reputation: 1289

AWS CloudFormation UserData EC2 Environment Variable

I'm working on an infrastructure with CloudFormation. That is my own infrastructure code shown below .

 AWSRegionArch2AMI:
     us-east-1:
       HVM64: ami-0ff8a91507f77f867
       HVMG2: ami-0a584ac55a7631c0c
 ...
 ..
 .

 Resources:
 EC2Instance:
 Type: AWS::EC2::Instance
 Properties:
 InstanceType:
    Ref: InstanceType
  SecurityGroups:
  - Ref: InstanceSecurityGroup
  KeyName:
    Ref: KeyName
  UserData:
    Fn::Base64: !Sub |
      #!/bin/bash
      export MY_AMI_NAME=${ !GetAtt AWSRegionArch2AMI.us-east-1.HVM64 }

      echo $MY_AMI_NAME > $HOME/user_data.txt

I want to set the variable to the user_data file but it is empty, How I can get the environment variable to inside my user data field and use it my own application side How I can do it.

Please help !

Upvotes: 12

Views: 9390

Answers (1)

Alex Harvey
Alex Harvey

Reputation: 15472

Try this:

UserData:
  Fn::Base64: !Sub
    - |
      #!/bin/bash
      MY_AMI_NAME=${image_id}
      echo $MY_AMI_NAME > $HOME/user_data.txt
    - image_id: !GetAtt AWSRegionArch2AMI.us-east-1.HVM64

Explanation:

  • Use of export in Bash is to make variables available to subshells - "environment variables". You don't need it there.

  • See the docs for proper use of the !Sub function.

  • See also this related Stack Overflow answer.

Upvotes: 16

Related Questions