Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 208
ColossusMark1 Avatar asked Feb 04 '23 19:02

ColossusMark1


1 Answers

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.

like image 65
Alex Harvey Avatar answered Feb 23 '23 10:02

Alex Harvey