Ubuntu – Run script on first boot

bootscriptingUbuntu

I want to create a script that will run only on first boot, and never again. I am working on a VM that will be converted on a template so I want to make sure I can create a script that can run automatically when the server boots.

I have some clues that I can put a script under /etc/init.d/firstboot for example, and use chkconfig to do it on rhel (which seems not available on Ubuntu), but I need to do it on Ubuntu 14 and 16, any ideas? — can I assume that if I put a script under /etc/init.d it will run at boot?

I've been googling but I see many different things. For example I saw something similar for rhel:

/etc/init.d/yourscript:
#!/bin/bash
# chkconfig: 2345 9 20
# description: long description

case "$1" in
  start)
    Do your thing !!!
    chkconfig yourscript off
  ;;
  stop|status|restart|reload|force-reload)
    # do nothing
  ;;
esac

any help is much appreciated

Best Answer

You could start your script with systemd. Write a systemd unit like:

[Unit]
Description=yourscript
ConditionPathExists=/path/to/some/file

[Service]
Type=oneshot
ExecStart=/path/to/yourscript

[Install]
WantedBy=multi-user.target

After enabling this unit it should only start if the file in ConditionPathExists exists. You could write your script to remove that file after running. Check systemd.unit there are more such checks, for example ConditionFileNotEmpty or ConditionDirectoryNotEmpty which can also be handy.