Linux Labs

Automation: Git and Ansible / Stage 7 of 8

Roles, variables and secrets

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 6 · on a machine · 7 min

A role: tasks in one place

Tasks that several playbooks need go into a role. A playbook then only names the role and sets its own values.

A role is a roles/<name>/ directory next to the playbook. It holds subdirectories with fixed names, and in each of them Ansible reads the main.yml file:

Where What
tasks/main.yml tasks — the same list as under a play's tasks:
handlers/main.yml handlers
templates/ templates: src: index.html.j2 in a role's task is looked up here
defaults/main.yml default values of variables

A play calls a role with the roles list and sets its own values in vars, as before (in the Wiki):

yaml
- name: Сайт shop
  hosts: web
  become: true
  vars:
    site_name: shop
    site_port: 8081
  roles:
    - site

A role's tasks run just like a play's tasks, and a role's handler fires on notify at the end of the play. In the output the role's name comes before the task's name: TASK [site : Страница]. A value from defaults/main.yml is what the role takes when nobody else has set it: a phone shared by all the sites is written there once.

One command runs several playbooks in a row — ansible-playbook shop.yml blog.yml docs.yml. It prints PLAY RECAP after each playbook with a running total: the last one counts all three.

Exercise · do it

Move the playbooks onto the role

In ~/ansible-lab your colleague started the roles/site role and moved shop.yml onto it. Move blog.yml and docs.yml onto the role, then change the support phone to 8-800-555-02-02 for all three sites at once with a single edit. Run all three playbooks.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Move blog.yml and docs.yml onto the site role not done yet
  • Change the phone on all three sites with a single edit not done yet

Step goals

0 of 2
  • Move blog.yml and docs.yml onto the site role — not done yet
  • Change the phone on all three sites with a single edit — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Move blog.yml and docs.yml onto the site role — not done yet
  • Change the phone on all three sites with a single edit — not done yet
Loading…