Detect if Ansible is running under Vagrant
TL;DR: To tell if Ansible was invoked by Vagrant, define an is_vagrant
flag as false
in the playbook, but set it to true
using extra_vars
in the Vagrantfile
.
You can detect if Ansible is being run under Vagrant by adding an is_vagrant
flag, which defaults to false
in your playbook, but is set to true
in the Vagrantfile
.1
Update your Vagrantfile
§
Use extra_vars
to set is_vagrant
to true
when called via Vagrant.
config.vm.provision "ansible" do |ansible|
ansible.playbook = "playbook.yml"
ansible.extra_vars = { is_vagrant: true }
end
Update your playbook §
In your playbook, set is_vagrant
to default to false
.
vars:
is_vagrant: false # Vagrant overrides this to true
Then you can conditionally import tasks depending upon whether is_vagrant
is true or not:
tasks:
- import_tasks: tasks/general_tasks.yml
when: is_vagrant
- import_tasks: tasks/vagrant_tasks.yml
Now the vagrant_tasks.yml
will only be imported if vagrant up
(or vagrant provision
) is executed. If ansible-playbook
is called directly it will not run.
Thanks to gildegoma for giving this example. ↩︎