How to ensure something only happens once when provisioning

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the algorithms category.

Last Updated: 2021-05-16

I used the virtual machine Vagrant in a project and wanted to add some code that made a change (appended a line to file) only the first time the script was run, but not afterwards - idempotency of sorts.

The trick is to create a new file whose sole purpose is signifying "work has been done" after first execution, and then check for that file on subsequent runs - using its presence/absence to switch out logic.

if [ ! -f ~/.homestead_post_install_customisations_done ]; then
    # Add one time setup customisation
    echo "Installing setup customizations"

    # IMPORTANT: The version number for postgres will change over time,
    # potentially breaking this script.
    echo "host    all             all             0.0.0.0/0                md5" | sudo tee -a /etc/postgresql/12/main/pg_hba.conf
    sudo service postgresql restart

    touch ~/.homestead_post_install_customisations_done
else
  echo "Already made customizations"
fi