mr_robot
mr_robot

Reputation: 547

Aws ec2 user data script not working on start up

I am trying to run a script on my EC2 at startup, with an image I created that runs ubuntu.

However, the script is failing although when I connect through ssh and run the script it is working.

My user data is:

#!/bin/bash    
echo '
#!/bin/bash
sleep 30
sudo apt-get update
cd /etc/apache2/sites-available
sudo sed -i 's/oldurl/newurl/g' 000-default.conf
sudo sed -i 's/oldurl/newurl/g' 000-default.conf
sudo certbot --apache -d url1 -d url2
sudo systemctl restart apache2' > init-ssl.sh
sleep 2 & init-ssl.sh

Cloud-init output1

I stopped my instance and changed my user data to something simple like:

#!/bin/bash
echo 'work' > try1.txt

I didn't see an error but I also didn't see my new try1.txt file.

Upvotes: 0

Views: 1209

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270089

A script passed via User Data will only be executed on the first boot of the instance. (Actually, the first boot per Instance ID.)

If you want to debug the script, the log file is available in:

/var/log/cloud-init-output.log

Your attempt to redirect to a file with echo ' ... ' >init-ssl.sh is being thwarted by the fact that the script also contains a single quote ('), which is closing the echo early. You should use different quotes to avoid this happening. Or, as @Mornor points out, simply run the script directly. If you want to sleep for a bit up-front, then just put the sleep() at the start of the script.

Upvotes: 1

Related Questions