Run a bash script after EC2 instance boots

Solution 1:

I'd suggest just using the user-data option to ec2-run-instances. It lets you give a script of some sort to the VM which will be run on first boot. If you're using ubuntu or debian, you can use cloud-init, which puts some nice polish on the process. If using cloud-init, you can use the [runcmd] section of the config file to specify arbitrary commands to run after boot.

Thanks to SF user Eric Hammond for the user-data page. Check out his site - it has a wealth of information on AWS.

Edit: After re-reading, it's not clear whether you wanted to run a command on initial boot or on every boot. The above instructions only apply to the initial boot. If you want to run a command on every boot, you have a couple options - you can run a command via the @reboot cron directive, or alternatively you can add the script to /etc/rc.local, which will be run each time the system boots.

Solution 2:

If you were using an AMI that had the cloud-init package installed (like Amazon Linux or Ubuntu) then you could simply pass the bash script (which starts with #!) as the user-data-file and it would run automatically at the end of the boot process.

For example, it could be as simple as:

ec2-run-instances                             \
  --user-data-file /home/root/beginProcess.sh \
  --key $USER                                 \
  ami-XXXXXXXX

Here's the article where I introduced the user-data script concept, now available in major EC2 AMIs like Amazon Linux and Ubuntu: http://alestic.com/2009/06/ec2-user-data-scripts

Unfortunately, it looks like you're wanting to use a RHEL AMI. I ran a copy of that and could not find any references to cloud-init or running user-data scripts on first boot, nor did a test of the same work.

I'm not saying you should switch Linux distros just for this, but Amazon Linux is based on RHEL, so that might work for you.

Here's an article I wrote that might help you debug your user-data script if it doesn't work the first time: http://alestic.com/2010/12/ec2-user-data-output