Lakshmi Enjeti
Lakshmi Enjeti

Reputation: 21

Setting environment variables in cloudformation using command module within cfn-init

I'm trying to set environment variables through the commands module within cfn-init.

"commands": {
              "set-env": {
                "env": {
                  "HOSTNAME": "fb-iaas.elevatebilling.com"
                },
                "cwd": "~",
                "command": "echo \"$HOSTNAME\" > test.txt"
              }
            },

And this is the output I see in cfn-init.log

2016-09-22 10:26:53,638 DEBUG Running command set-env
2016-09-22 10:26:53,639 DEBUG No test for command set-env
2016-09-22 10:26:53,655 INFO Command set-env succeeded
2016-09-22 10:26:53,655 DEBUG Command set-env output: 

But environment variable HOSTNAME doesn't get updated. Can someone please explain what am I doing wrong?

Thanks

Upvotes: 2

Views: 9626

Answers (2)

Laurent Delhomme
Laurent Delhomme

Reputation: 1

The AWS documentation gives the syntax for Linux. Since your script starts with echo, I suppose you are running Windows. In that case, the environment variable syntax should be %HOSTNAME%, instead of $HOSTNAME.

Upvotes: -2

UraniumKnight
UraniumKnight

Reputation: 21

When you say that the variable doesn't get updated, how have you found this out? Did you open "test.txt" and read what was piped to it or did you ssh into the instance and run an "echo $HOSTNAME"? The reason why I ask is because the AWS docs on running commands with cfn-init (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html) say this for the "env" option:

env - Optional. Sets environment variables for the command. This property overwrites, rather than appends, the existing environment.

From my interpretation of this and from my experience, environment variables set using "env" exist only for the command in which it resides. If you read in the "test.txt" file that the variable is set to what you want but not when you run an "echo $HOSTNAME" it's because the variable exists only for the command. I suggest that if you want your environment variables to persist, you set them using "export" in the UserData section of the Cloudformation template.

Upvotes: 2

Related Questions