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:

$ ansible-galaxy init my-role
- 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:

$ cat my-role/tests/test.yml
---
- hosts: localhost
remote_user: root
roles:
- my-role

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

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

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

$ vagrant up
...
PLAY [localhost] ***************************************************************
skipping: no hosts matched

PLAY RECAP *********************************************************************

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

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

Afterwards, configuration succeeds:

$ vagrant up --provision
...
PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [default]
...
PLAY RECAP *********************************************************************
default                    : ok=10   changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

Sharing is caring

Leave a Reply