How to pass environment variables when programmatically starting a new Amazon EC2 from image?

user193116 picture user193116 · Mar 30, 2012 · Viewed 12.1k times · Source

I am using AWS Java API RunInstance() to start a new EC2 instance from my custom AMI image. How do I pass environment variables to the new EC2 INSTANCE such as database url, AWS credentials etc. ?

Answer

jcomeau_ictx picture jcomeau_ictx · Mar 31, 2012

http://alestic.com/2009/06/ec2-user-data-scripts explains how to do this with user-data. for gotchas about using Java see AmazonEC2 launch with userdata.

note that I've seen mention that this doesn't work with Windows, only Unix.

[update] more data on setting environment variables here: https://forums.aws.amazon.com/message.jspa?messageID=139744

[after much testing] for me, echoing the environment variables into /etc/environment works best, like this:

 reservation = connection.run_instances(image_id = image_id,
  key_name = keypair,
  instance_type = 'm1.small',
  security_groups = ['default'],
  user_data = '''#!/bin/sh\necho export foozle=barzle >> /etc/environment\n''')

then upon login:

ubuntu@ip-10-190-81-29:~$ echo $foozle
barzle