3

I am deploying my code to AWS EC2. The documentation says there's something called "user data" or "user data scripts" that you can enter this info when you're launching an ec2 instance and the script will be executed at instance startup.

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-shell-scripts

the following is in my user data script:

#!/bin/bash
echo 1111 >> /home/ubuntu/1111.txt
export MONGODB_HOST=www.mongodb.com
export MONGODB_PORT=12345
export MONGODB_USER=user
export MONGODB_PASS=pass

enter image description here

So when I launch the instance with this user data script I would expect to see the environment variables being set, but it didn't.

So is there something that I did wrong?

Shih-Min Lee
  • 9,350
  • 7
  • 37
  • 67
  • Already answered in this thread http://stackoverflow.com/questions/9764145/amazon-ec2-user-data-how-does-it-work – Tommy Oct 27 '15 at 09:23
  • yes I have read that post but somehow it's not working. I can see the user data inside `/var/lib/cloud/instance/user-data.txt` also I can get `$user_data` variable with `user_data=`curl http://169.254.169.254/latest/user-data/` but I just cannot get them into environment variables.. (my node.js app reads credentials from env variables..) – Shih-Min Lee Oct 27 '15 at 10:04
  • are you sshing to the machine and starting node by hand? or how are you starting it? – tedder42 Oct 27 '15 at 11:47
  • AWS codedeploy will tell code-deploy agent to run some scripts (start.sh) when all is done the final script will do `node server.js` – Shih-Min Lee Oct 28 '15 at 01:25
  • Some help at https://forums.aws.amazon.com/message.jspa?messageID=139744. Also note that userdata scripts are run as root. – jarmod Oct 28 '15 at 01:38
  • what is interesting is in the above script 1111.txt is created on the machine. but environment variables are not being set. – Shih-Min Lee Oct 28 '15 at 01:54
  • Did you see /var/logs/cloud-init.log to check whether its executed on not? – Gangaraju Nov 26 '15 at 03:36

1 Answers1

6

Your user data script is actually run. Nevertheless, it is run on its own bash process which dies at the end of your script.

Exported variables are preserved only for the lifetime of your script and they are also visible from child processes of your script.

Since new connections to your ec2 instance are not children of the original script that ran the user data, they don't inherit exported variables.

Daniel777
  • 851
  • 8
  • 20
  • see https://stackoverflow.com/questions/34205532/how-to-set-environment-variables-on-ec2-instance-via-user-data for a workaround – m1m1k Apr 23 '20 at 21:06