Sam Hooke

Detect if Ansible is running under Vagrant

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 }

Update your playbook §

In your playbook, set is_vagrant to default to false.

  is_vagrant: false  # Vagrant overrides this to true

Then you can conditionally import tasks depending upon whether is_vagrant is true or not:

    - 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.

  1. Thanks to gildegoma for giving this example↩︎