Ansible Roles

Ansible roles are one of the most important building blocks for organizing automation in a scalable and reusable way. They let you take a large playbook and break it into modular, reusable components. A role is a standardized directory structure that automatically organizes:

  • tasks (what to do)
  • variables (inputs/config)
  • handlers (restart services, etc.)
  • templates (Jinja2 config files)
  • files (static files to copy)
  • defaults (lowest-priority variables)
  • meta (dependencies)

Instead of writing one giant playbook, you call the roles.

Let’s create a sample role.

mkdir roles
cd roles
ansible-galaxy init myrole

Let’s take a look at what that did.

cd myrole
find .

You’ll see that it created a directory structure for all components with a main.yml in each directory. Now, let’s populate some details into our role.

Edit vars/main.yml and add the following

motd_message: "Welcome to this system - managed by Ansible"

Create templates/motd.j2 and add the following content:

{{ motd_message }}

Hostname: {{ ansible_hostname }}

Unauthorized access is prohibited.

Edit tasks/main.yml and add the following:

- name: Deploy MOTD template
  ansible.builtin.template:
    src: motd.j2
    dest: /etc/motd
    owner: root
    group: root
    mode: '0644'
  notify: restart ssh

Edit handlers/main.yml and add the following:

- name: restart ssh
  ansible.builtin.service:
    name: sshd
    state: restarted

Back in the playbooks directory (up two levels) create a playbook named myplaybook.yml and add the following:

- name: Apply MOTD role
  hosts: all
  become: true

  roles:
    - myrole

Now execute the playbook that calls the role.

ansible-playbook myplaybook.yml

Verify the results.

ansible all -m command -a "cat /etc/motd"