Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass environment variable to provisioner in Vagrant

I am using the Ansible (local) provisioner for my Vagrant setup. Is there a recommended way to pass an environment variable to the provisioner?

For example, I want to run ENV=development vagrant up and have Vagrant pass the environment variable ENV to Ansible.

I tried using extra_vars, taken from the Vagrant documentation:

Vagrant.configure(2) do |vagrant|
    # other configuration
    vagrant.vm.provision :ansible_local do |ansible|
        ansible.playbook = "ansible/server.yml"
        ansible.extra_vars = {
          env: ENV.fetch("ENV", "development")
        }
    end
end

However, when I run vagrant provision (without even using the env variable in Ansible), I get the following:

$ vagrant provision
 ==> default: Running provisioner: ansible_local...
    default: Running ansible-playbook...
ERROR: Expecting property name: line 1 column 2 (char 1)
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.

Removing ansible.extra_vars fixes this error, but then I can't accomplish what I wanted to.

like image 481
Rushy Panchal Avatar asked Jun 15 '16 17:06

Rushy Panchal


2 Answers

You need to install the plugin for Vagrant:

vagrant plugin install vagrant-env

I hope my code snippets will help:

config.vm.define "k8s-master" do |master|
    master.vm.box = IMAGE_NAME
    master.env.enable # Enable vagrant-env(.env)
    master.vm.network "private_network", ip: "192.168.50.10"
    master.vm.hostname = "k8s-master"
    master.vm.provision "ansible" do |ansible|
        ansible.playbook = "./playbooks/master.yml"
        ansible.compatibility_mode = "2.0"
        ansible.extra_vars = {
            env: development,
        }
    end
end

With config.env.enable added whenever you run a Vagrant command it’ll load .env into ENV which will allow your customizations. And you can use this inside playbook as {{ variable_name }} .

like image 149
noobmaster69 Avatar answered Sep 20 '22 09:09

noobmaster69


To access development environment variable, use: ENV['development'] syntax.

You can also assign it to the variable at the beginning of the file:

development = ENV['development']

and use variable instead:

ansible.extra_vars = {
  env: development
}

Check the following Vagrantfile as example.

like image 34
kenorb Avatar answered Sep 22 '22 09:09

kenorb