Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud-init per-boot script doing nothing

I am new to cloud-init, my final goal is to run an R script each time an EC2 Spot Instance becomes active, but in order to test it I created an on-demand Ubuntu 12.04 instance and created a simple script but nothing happens after reboot. Here are the steps I took:

  • Launched the new Ubunut 12.04 instance
  • Navigate to /var/lib/cloud/scripts/per-boot
  • sudo vi script.sh
  • Added the following code:

#!/bin/sh
echo "test"

  • sudo reboot

At this point I thought I should see a "test" print when the instance reboots, but there is nothing there. I went to take a look at /var/log/cloud-init.log but there is no error or anything out of the ordinary.

I am clearly missing something so any tip in the right direction will be much appreciated!

Thanks!

like image 931
JordanBelf Avatar asked Jun 06 '26 20:06

JordanBelf


1 Answers

The accepted answer is not adequate imo, so after I spent my whole morning getting to the bottom of this I will write my view since I believe people will find this useful and save time.

If the scripts-user module is set to always run then the runcmd: section of your cloudinit will run at every boot.

This can be done with by adding the following section on your cloud-config file,

cloud_final_modules:
 - [scripts-user, always]

If you want to run certain scripts at every boot then you need to place under the

/var/lib/cloud/scripts/per-boot/ folder. To achieve that, add the following section to your cloud-config file,

write_files:
  - content: |
      #!/bin/bash
      echo "Hello World.  The time is now $(date -R)!"
    path: /var/lib/cloud/scripts/per-boot/myScript.sh
    permissions: "0755"

Now everytime I reboot my EC2 instance it will run myScript.sh

And a full example of cloud-config that installs amazon ssm agent on Rhel 8

#cloud-config
cloud_final_modules:
 - rightscale_userdata
 - scripts-per-once
 - scripts-per-boot
 - scripts-per-instance
 - scripts-user
 - keys-to-console
 - phone-home
 - final-message

write_files:
  - content: |
      #!/bin/bash
      echo "Hello World.  The time is now $(date -R)!"
    path: /var/lib/cloud/scripts/per-boot/myScript.sh
    permissions: "0755"


runcmd:
  - sudo dnf install -y python3
  - sudo yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm
  - sudo systemctl enable amazon-ssm-agent
  - sudo systemctl start amazon-ssm-agent

Please note that in this case myScript.sh precedes the execution of runcmd: on first boot and subsequent boots only execute myScript.sh

like image 113
furydrive Avatar answered Jun 08 '26 14:06

furydrive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!