In our previous articles, we discussed Ansible installation and configuration and How to create and run/execute Ansible Playbooks. Now let’s learn to create an Ansible Role step by step. Within Ansible there are two techniques for reusing a set of configuration management tasks, includes and roles. Both techniques function in similar ways, but roles appear to be the official way to reuse and organize Ansible Plabooks.
Creating a New Role
The first step in creating a role is creating its directory structure. In order to create the base directory structure, we’re going to use a tool bundled with Ansible called
ansible@devops$ ansible-galaxy init my-role my.role was created successfully
Above command will create the following directory structure
├── README.md ├── defaults │ └── main.yml ├── files ├── handlers │ └── main.yml ├── meta │ └── main.yml ├── tasks │ └── main.yml ├── templates └── vars └── main.yml
Role Directory Structure or Role Framework
A role’s directory structure consists of
- files: This directory contains regular files that need to be transferred to the hosts you are configuring for this role. This may also include script files to run. Basically this is used for static file transfer.
- handlers: All handlers that were in your playbook previously can now be added into this directory.
- meta: This directory can contain files that establish role dependencies. You can list roles that must be applied before the current role can work correctly.
- templates: You can place all files that use variables to substitute information during creation in this directory. Basically this is used for dynamic file transfer.
- tasks: This directory contains all of the tasks that would normally be in a playbook. These can reference files and templates contained in their respective directories without using a path.
- defaults: Variables for the roles can be specified in this directory and used in your configuration files. Variables in
defaultshave the lowest priority of any variables available, which means they’re easy to override.
- vars: Variables for the roles can be specified in this directory and used in your configuration files. Variables in
varshave a higher priority, which means that they are more difficult to override.
Sample role example
You can find roles example here https://galaxy.ansible.com/avinash6784/