Testing Ansible Playbooks with Vagrant

Evren Yortuçboylu
2 min readJan 27, 2019

--

Testing locally makes it easier.

We use Ansible playbooks to configure EC2 instances at work. But it’s not always a breeze to have your desired configuration on the machine at first try. It requires lots of refactoring and retries. And at the end, we should be able to test playbooks locally.

Vagrant to the rescue! You can create, launch and restart virtual machines easily. And plays well with Ansible.

There are two ways of testing your playbook with a Vagrant vm. You can create and launch a vm and then apply the playbook with ansible-playbook command, specifying ip address of vm and required ssh certificate like any other remote machine.

But there is a better way! We can use Vagrant’s Ansible provisioning feature.

All we need to do is put the Ansible provisioning setting into Vagrantfile.

Vagrant.configure("2") do |config| 
config.vm.box = "bento/ubuntu-18.04"

config.vm.provider "virtualbox" do |vb|
vb.memory = "4024"
vb.cpus = "1"
end
config.vm.provision "ansible" do |ansible|
ansible.become = true
ansible.verbose = "v"
ansible.extra_vars = "ansible_extra_vars.yml"
ansible.vault_password_file="~/.vault_pass.txt"
ansible.playbook = "/home/yortuc/ansible/playbook.yaml"
end
end

Ansible configuration is not limited with specifying the playbook but also we can give bunch of other options like extra_args , vault_password and so on. (see all the options available)

After launching vm with Vagrant, we can provision vm with the specified playbook by running provision command.

> vagrant provision==> default: Running provisioner: ansible...
...
default: Running ansible-playbook...
...
PLAY [JupyterSetup] ************************************************************
...

That’s all.

Happy hacking.

--

--