Save Environment Variables in Amazon EC2 User Data
I don’t think it’s new, but it’s new to me. When you launch an instance in Amazon EC2, you have the option of passing User Data to store any text value, or define a script that will be executed on first boot. This is useful for standalone instances, and extremely helpful for Auto Scaling groups, when there is a need to change settings without touching VM image.
There is an important limitation for scripts: they only run during the first boot cycle when an instance is launched. But what if you want to save a command(s) that will run on-demand, or read environment variables to start your app? Just to keep your family and business code and configuration completely separated.
You may use Amazon-specific CLI tools, that retrieve information about current VM. For example, to get instance ID, run ec2metadata --instance-id. ec2metadata retrieves User Data text as well. The text may be parsed with grep or awk, but working with shell variables is much easier. Here is a quick example of storing and reading environment variables:
Example User Data
APP_URL=example.com?id=123 S3_KEY="ABC XYZ" S3_SECRET=ABC
Example bash script
#!/bin/bash eval $(ec2metadata --user-data) echo APP_URL=$APP_URL # start your node app APP_URL=$APP_URL S3_KEY=$S3_KEY node /path/app.js
This is it. It sounds like a weird as-seen-on-TV thing, but you've completely separated your configuration and code. Done.













