5

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

user3311890
  • 181
  • 2
  • 8

2 Answers2

1

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.

duenni
  • 2,959
  • 1
  • 23
  • 38
  • but this would not work on Ubuntu 14 right? can I write then a script that deletes itself and put it at the end of `/etc/rc.local` ? would this work for both 14 and 16? – user3311890 Jun 01 '17 at 13:03
  • Well, I would not write a script which deletes itself, seems hack-ish and tricky to evaluate. You could do it the same way: let the script create a file and check the presence of that file before executing. `systemd` seems fully supported on Ubuntu 15.04 but available on older versions. Before `systemd` Ubuntu used `upstart`. Look into the `upstart` documentation on how to run a script there. – duenni Jun 01 '17 at 13:13
  • That's why chmod -x $0 is the best solution that I suggested. – Marco Jun 02 '17 at 12:30
  • @Marco I did not say otherwise and was not the one who downvoted you. I just provided another solution (with `systemd`). – duenni Jun 02 '17 at 13:00
  • @duenni: LOL, np mate! :) – Marco Jun 02 '17 at 13:01
-1

It won't run at boot just because it's in /etc/init.d/.

The script can be in /etc/init.d, but you will have to initctl reload-configuration or you may put the script where you want and echo "/path/to/yourscript start &" >> /etc/rc.local.

Then, just add chmod -x $0 at the end of the start section and it will never execute again.

Or if you prefer the script to be deleted instead, use rm $0. If you opted for initctl way, use rm $0 && initctl reload-configuration to disable instead.

Marco
  • 1,709
  • 3
  • 17
  • 31