Reputation: 910
Similar question to this, but I know what a task is and cannot find much differentiation between tags and roles.
It seems to me, that tags may be a simpler version of roles, with their only use being accessible via the --tags
and --skip-tags
CLI parameters.
Roles on the other hand, are used for "automatically loading" things like tasks and variables?
Please, explain the benefits to using roles, because it seems to me like roles require you to have different yaml files for the different parts (tasks, vars, etc) which I could accomplish with less code using the include
and tags
directives.
Upvotes: 2
Views: 2518
Reputation: 358
Tags and roles are different things.
Roles are used to aggregate some group of tasks which do certain thing, e.g. one role can contain tasks that install some service and a second role tasks to configure this service.
Each role has its own directory structure:
site.yml
webservers.yml
fooservers.yml
roles/
common/
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webservers/
tasks/
defaults/
meta/
So for each role you can define e.g. variables, templates, tasks etc. It makes Ansible scripts clear and transparent. Another advantage is that you can reuse roles in different playbooks.
So instead of defining all tasks in a single playbook, which can become a little messy if playbook contained many tasks:
- name: Install nginx and mysql
hosts: all
become: yes
tasks:
- name: Install nginx
...
- name: Configure nginx
...
- name: Install mysql
...
- name: Configure mysql
...
You can create roles and include them:
- name: Install nginx and mysql
hosts: all
become: yes
roles:
- nginx
- mysql
I suggest to take a look at the examples where roles are used.
Tags are used while running ansible-playbook
command to indicate which tasks should be executed.
If you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.
So it is possible to tag some roles/tasks and run/skip only them while executing playbook.
Upvotes: 4
Reputation: 68289
It seems to me, that tags may be a simpler version of roles.
Sorry, but this is completely wrong.
Roles are self-contained reusable units (with own variables, tasks, handlers and even plugins and modules!). You can use them in multiple playbooks and/or plays in your project. You can share them between multiple projects. You can use role dependencies. You can redistribute them via external resources (e.g. Ansible Galaxy). For example, role nginx
to install and configure nginx server, and role apache
for apache server.
Tags are used to make it possible to execute only specific tasks in your project. You can mark plays/roles/tasks with tags. For example, tag config
to mark only configuration-related tasks inside our nginx
and apache
role. So later you can execute ansible-playbook -t config site.yml
to run configuration only tasks for all type of servers instead of whole playbook.
Upvotes: 6