smeeb smeeb - 2 months ago 9
Bash Question

Are Vagrant shell provisioner scripts idempotent or OTO?

I want to write a

Vagrantfile
and accompanying shell script so that the script runs/executes only the very 1st time a user executes a
vagrant up
for that VM. That's because this shell script will install all sorts of system services that should only happen one time.

According to the shell provisioner docs, it looks like I might be able to do something like:

Vagrant.configure("2") do |config|
config.vm.provision "shell", path: "init-services.sh"
end


However, from the docs I can't tell if
init-services.sh
will be executed every time a user does a
vagrant up
(in which case I need to write it carefully so as to be idempotent), or whether it truly only executes the script one time, when the box is first being provisioned.

And, if it does only execute the script one time, then how does Vagrant handle updates to the script (if we want to, say, add a new service to the machine)?

Answer

However, from the docs I can't tell if init-services.sh will be executed every time a user does a vagrant up (in which case I need to write it carefully so as to be idempotent), or whether it truly only executes the script one time, when the box is first being provisioned.

yes the script will be executed only at the first time the machine is spinned up during the vagrant up. There is an option is you want to run it everytime (even though its not something you want in this case)

Vagrant.configure("2") do |config|
    config.vm.provision "shell", path: "init-services.sh", :run => 'always'
end

And, if it does only execute the script one time, then how does Vagrant handle updates to the script (if we want to, say, add a new service to the machine)?

There are 2 commands you can use for this:

  • A specific call to vagrant provision will still force the script to run wether the machine has already been initialized or not.
  • Calling vagrant up --provision when spining an existing VM will run the provisioning script

on this point though vagrant will not check what are the update in your script, it will just run the whole script again; if you need to run just a specific update you will need to manage this yourself in your script file.

You can read a bit more about how the provisioning work in the doc

Comments