Issue
I'm running the following user data script for my AWS EC2 on an Amazon Linux AMI. I want to run a simple socketio server, however whenever I stop and start the instance, the script doesn't run. When I SSH via the Connect portal, and run these commands, it works. Furthermore when creating an AMI from my functioning instance, Git is present but not Node on instances generated from that AMI.
I followed the AWS docs for installing node and it alludes that it should work with an AMI.
#!/bin/bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node
sudo yum install git -y
git clone https://github.com/justincervantes/socketio-server-demo.git
cd socketio-server-demo
npm i
node index.ts
Thanks in advance for your advice.
Solution
User data shell scripts must start with the #!
characters and the path to the interpreter you want to read the script (commonly /bin/bash
).
So for this script works add the following at beginning:
#!/bin/bash
Also you need to source the NVM files to ensure that variables are available within the current shell
To works you script will be like the following one:
#!/bin/bash
apt-get -y update
cat > /tmp/subscript.sh << EOF
# START UBUNTU USERSPACE
echo "Setting up NodeJS Environment"
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
echo 'export NVM_DIR="/home/ubuntu/.nvm"' >> /home/ubuntu/.bashrc
echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm' >> /home/ubuntu/.bashrc
# Dot source the files to ensure that variables are available within the current shell
. /home/ubuntu/.nvm/nvm.sh
. /home/ubuntu/.profile
. /home/ubuntu/.bashrc
# Install NVM, NPM, Node.JS & Grunt
nvm install node
sudo yum install git -y
git clone https://github.com/justincervantes/socketio-server-demo.git
cd socketio-server-demo
node index.ts
EOF
chown ubuntu:ubuntu /tmp/subscript.sh && chmod a+x /tmp/subscript.sh
sleep 1; su - ubuntu -c "/tmp/subscript.sh"
Answered By - valdeci Answer Checked By - Senaida (WPSolving Volunteer)