As of now we have written playbooks that include all the details like hosts, variables, tasks and plays. This is not an ideal way if we have many tasks and lots and lots of plays to be included, the best way to do it is to separate each item into its own directory and this is how its done in prodution especially if a organization use cloud. So let’s do some Role things.
Before knowing anything further about Roles, we need to understand about the ‘include’ which is core for the Roles to work. include can be used in a playbook to use another playbook instead of rewriting the entire playbook again. The placement of include determines the use of it. The include statement mentioned in a task referes to the tasks and include mentioned at the hosts refers to another playbook.
Roles – Directory Structure
Roles directory includes directoryies based on the functionality rather than by the name of the server for a better reusability and each directory has a directory within for each item and all the details are mentioned in the main.yml file. Below is the sample directory structure i have.
Let’s now see what’s included in each main.yml file and also finally to make use of all this roles, I created two yml files my_webrole.yml and my_dbrole.yml. To make use of the include and demonstrate it i created another playbook called final.yml. Each subdirectory under the dbrole/webrole is optional and you use them based on your environment. All we do here is convert our existing playbook to respective main.yml files under roles.
The main.yml files under the dbrole are also similar. Now let’s cat the my_webrole.yml and my_dbrole.yml files which basically makes use of the roles we created.
These yml playbooks can be executed separately and they just work fine. But to demonstrate the usage of include command, we used the final.yml and here is the cat output of final.yml.
Finally running the final.yml playbook just works fine as earlier. Note that ansible mentions the role it is executing and also the task in the role in the output, this is great for troubleshooting.
Hope this was informative. Thanks!