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.
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 }}
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With