Short tip: Utilize Ansible role via Vagrant

When implementing larger tasks in Ansible, you might thinking about writing your own Ansible role sooner or later. For this, the ansible-galaxy command can help you:

1$ ansible-galaxy init my-role
2- my-role was created successfully

Beside handlers, variables and meta data, also a test task is created. Using this task, the role can easily be assigned to a host:

1$ cat my-role/tests/test.yml
3- hosts: localhost
4  remote_user: root
5  roles:
6    - my-role

This task can be linked within Vagrant to configure a freshly deployed system:

1config.vm.provision "ansible_local" do |ansible|
2  ansible.install_mode = "default"
3  ansible.playbook = "my-role/tests/test.yml"

If you execute Vagrant now, it is very likely that Ansible won't find matching hosts:

1$ vagrant up
3PLAY [localhost] ***************************************************************
4skipping: no hosts matched
6PLAY RECAP *********************************************************************

To fix this, simply replace localhost with all in the test task:

1$ sed -i "s/localhost/all/g" my-role/tests/test.yml

Afterwards, configuration succeeds:

1$ vagrant up --provision
3PLAY [all] *********************************************************************
5TASK [Gathering Facts] *********************************************************
6ok: [default]
8PLAY RECAP *********************************************************************
9default                    : ok=10   changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0