0

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.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
mr_robot
  • 415
  • 1
  • 5
  • 16

1 Answers1

1

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.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • I guess you want to create a script before executing it? ```echo '...' > init_ssl.sh``` is not necessary. Just execute the script directly, no need to output it into a file first. – Mornor Nov 23 '22 at 12:21
  • Oh! I hadn't realised that is what they are doing. The quotes will ruin things. I'll update my answer. – John Rotenstein Nov 23 '22 at 20:36