How Do You Transform an Ansible Playbook into a Role?

Problem scenario
You want to refactor a playbook into a role. How do you do this?

Solution

  1. A role will be in a "roles" directory. Create the directory as such.
  2. Take your playbook (.yml or .yaml file) and eliminate the word "tasks" from it. The role should still be in the .yml or .yaml format.
  3. Variables must be extracted. This is the confusing portion. When you run a playbook that uses this new role, the variables must be in a directory that is visible to the playbook. If you use the "-i" flag when you call the playbook, make certain that the variables for this newly-created role (based on, perhaps minor, modifications of a playbook) are visible in a location that Ansible will look for. The way your ansible.cfg file is configured may affect this.
  4. Remove the hosts: stanza. That line doesn't belong in a .yaml file that is a role.

For more information, see these links:

Leave a comment

Your email address will not be published. Required fields are marked *