Ubuntu – Run sh file when Amazon EC2 instance starts

amazon ec2amazon-web-servicesnode.jsUbuntuubuntu-12.04

I have a "sh" file that starts a node server.

It works well if I run

sh /var/www/init_node.sh

I want the script to run everytime my instance restarts (so I have a node server up and running).

I added the script to my /etc/rc.local file as follows:

sh /var/www/init_node.sh 
exit 0

However, when I restart the instance, the nodejs server is not running. It's a Ubuntu 64 instance.

I think that it's not important, but here is the content of my sh file:

cd /var/www/myproject
eval `ssh-agent -s`
ssh-add -D
ssh-add ~/.ssh/id_rsa
git stash
git pull origin master --force
forever start express.js 

Also

sh /etc/rc.local 

works fine

Any ideas?

Best Answer

I had a similar issue with the rc.local file on an amazon instance. It turned out for me that I had an error with the script in rc.local that would not allow it to execute unless I had a tty.

So how do you find out if your getting a similar error? Use cloud-init to execute your script.

For my amazon linux distro I first edited /etc/init.d/cloud-init-user-scripts.

Change this line /usr/bin/cloud-init-run-module once-per-instance user-scripts execute run-parts ${SCRIPT_DIR} >/dev/null && success || failure

TO "always"

/usr/bin/cloud-init-run-module always user-scripts execute run-parts ${SCRIPT_DIR} >/dev/null && success || failure

Then create a directory mkdir /var/lib/cloud/data/scripts .. Now copy your script that you wish to have executed on startup to /var/lib/cloud/data/scripts. Make sure your scripts executable bit is set.

Now you should be able to execute sudo /etc/init.d/cloud-init-user-scripts start .. Then you can check /var/log/cloud-init.log for errors.

Related Topic