Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally call different provision in Vagrantfile

I have the following provisions setup in my Vagrant file.

 config.vm.provision :shell, :path => "provision/bootstrap.sh"
 config.vm.provision :shell, :path => "provision/step-1.sh"
 config.vm.provision :shell, :path => "provision/step-2.sh"
 config.vm.provision :shell, :path => "provision/dev-setup.sh"

provision/bootstrap.sh needs to be run always, however i need to conditionally run the remaining provisions. For Eg. if dev mode, run the provision/dev-setup.sh

Is there some inbuilt Vagrant config setting to achieve this? ( like passing command line args to vagrant provision) ?

I would not like to rely on ENV variables like this if possible.

like image 406
CodeRain Avatar asked Mar 09 '15 11:03

CodeRain


2 Answers

I think environment variables are the most common way to handle this, and there isn't a way to pass anything through the vagrant up or vagrant provision command. Here are a couple of alternative ideas you could explore:

  1. Have something else that is different on the Dev versus Prod environment. The Vagrantfile is just a Ruby script, so anything that can be detected can be used to control the provisioning script sequence. For example, presence/absence of a file, local network, hostname, etc.

  2. Define separate Vagrant nodes which are actually the same, but differ based on provisioning. For example with a file like the following, you could do vagrant up prod or vagrant up dev, depending on your environment:

    Vagrant.configure("2") do |config|
      config.vm.provision :shell, :path => "provision/bootstrap.sh"
      config.vm.provision :shell, :path => "provision/step-1.sh"
      config.vm.provision :shell, :path => "provision/step-2.sh"
    
      config.vm.define "prod" do |prod|
        ...
      end
    
      config.vm.define "dev" do |dev|
        ...
        config.vm.provision :shell, :path => "provision/dev-setup.sh"
    
      end
    end
    
like image 122
BrianC Avatar answered Oct 13 '22 02:10

BrianC


You can also create a new variable in your inventory to hold the environment, for example env: dev in the dev inventory and env: production in the prod inventory and then use that to conditionally include your individual task files, like this:

# provision.yml (your main playbook)

- include: provision/bootstrap.sh
- include: provision/step-1.sh
- include: provision/step-2.sh
- include: provision/dev-setup.sh
  when: env == 'dev'

Then in Vagrant you can specify the inventory to use, for example:

config.vm.provision "provision", type: "ansible" do |ansible|
    ansible.playbook = 'provision.yml'
    ansible.inventory_path = 'inventory/dev'
end

More info:

  • Conditional includes
  • Inventories
like image 24
Emmet O'Grady Avatar answered Oct 13 '22 01:10

Emmet O'Grady