Question

I'm started using Packer and I have a question. Is there any solution to add a bash script which will be started automatically and only once after VM will be deployed from an image?

Was it helpful?

Solution

Add below code in /etc/rc.local of the linux VM's image:

####Marker_start####
sed -i '/####Marker_start####/,/####Marker_end####/d' /etc/rc.local
#Your custom code here
####Marker_end####

Explanation:

  1. rc.local script gets executed after every system start. Hence, adding the code there will cause it to execute after boot.
  2. Use sed to remove the custom code first time the script executes. Thus, the code is executed only once.

Other approach:

Create a script containing your custom code & append below code to it.

 chmod 644 "$0"

& create a symlink

ln -s /path/to/your-script.sh /etc/rc5.d/S99my-custom-script.sh

(Assuming your default runlevel is 5. Change it as required on your VM's distro - e.g. ubuntu has it on /etc/rc2.d)
Explanation:
Scripts named /etc/rc5.d/S* are executed automatically when entering run-level 5, with argument=start. Upon first execution, make the script as non-executable, so that it gets executed only once.

OTHER TIPS

I had the same question you asked here, but for a more specific case. I was building a custom AMI for AWS based upon the aws linux image.

If you have this case you can add the script to /var/lib/cloud/per-instance. This will run the script for every instance once. If you need it to run per boot you can add it to /var/lib/cloud/per-boot.

Make sure you first copy the folder to a location that you can write to like /home/ec2-user/ and then move the script to the location.

See AWS user_data with Packer for a more specific question on this case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top