Ansible's roles (Roles) are a way to organize and manage tasks and variables, which can help you better organize and reuse Ansible code. A role is a reusable, self-contained Ansible unit that encapsulates a set of tasks and variables that can be easily reused across different playbooks.
The directory structure for roles is as follows:
roles/
myrole/
tasks/
handlers/
templates/
files/
vars/
defaults/
meta/
Below is a description of each directory:
tasks/
: Store the main task file of the role, which can contain multiple YAML files, and each file defines a task.handlers/
: Stores the character's processor file, which is used to handle events triggered by tasks.templates/
: store the template file used by the role, which can be rendered by using the Jinja2 template syntax in the task.files/
: Stores common files used by the character, which will be copied to the target host.vars/
: Store the variable file of the role, which can define the variables used by the role.defaults/
: Store the default variable file of the role, and the default value of these variables will be overwritten by other variables.meta/
: Store the metadata file of the role, including the description information and dependencies of the role.
When using roles, they can be imported and invoked via import_role
or .include_role
Here is an example using roles:
-
Create a
myrole
role called :ansible-galaxy init myrole
This will create a role directory named under the current directory
myrole
with the above directory structure. -
The main tasks of the role are defined in
tasks/main.yml
the file:--- - name: Task 1 debug: msg: "This is Task 1" - name: Task 2 debug: msg: "This is Task 2"
Two tasks are defined here, which output different debugging information respectively.
-
Import and use roles in playbooks:
--- - name: Playbook using role hosts: all roles: - myrole
This
myrole
adds the role to the playbook'sroles
list. -
Run the playbook:
ansible-playbook playbook.yml
Ansible will execute
myrole
the tasks defined in the role.
By using roles, you can encapsulate task and variable logic in a reusable unit and reuse code across different playbooks more easily and flexibly. Role tasks, processors, templates, files, variables and default variables can be defined according to actual needs. At the same time, the directory structure of roles makes managing and maintaining code clearer and more orderly.