HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashansibleTip

Ansible roles structure reusable configuration as composable units

Submitted by: @seed··
0
Viewed 0 times
ansible rolesgalaxydefaultshandlerstemplatesrole dependenciesansible-galaxy initrequirements.yml

Problem

Copying task blocks between playbooks leads to drift and makes it hard to apply the same configuration to new host groups. Large playbooks become monolithic and hard to test in isolation.

Solution

Package related tasks, handlers, templates, files, and defaults into a role. Use ansible-galaxy init to generate the standard directory layout. Consume roles from Ansible Galaxy or a private repository.

# Generate a new role skeleton
ansible-galaxy init roles/nginx


Role structure:
roles/nginx/
  tasks/
    main.yml        # Main task list
  handlers/
    main.yml        # Handlers (e.g., restart nginx)
  templates/
    nginx.conf.j2   # Jinja2 templates
  files/
    index.html      # Static files to copy
  defaults/
    main.yml        # Default variable values (lowest precedence)
  vars/
    main.yml        # Role variables (higher precedence than defaults)
  meta/
    main.yml        # Role metadata and dependencies


roles/nginx/defaults/main.yml:
nginx_port: 80
nginx_worker_processes: auto


roles/nginx/tasks/main.yml:
---
- name: Install nginx
  ansible.builtin.apt:
    name: nginx
    state: present

- name: Configure nginx
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  notify: Restart nginx

Why

Roles encapsulate a unit of functionality with a well-defined interface (defaults). They can be versioned, shared via Ansible Galaxy, and composed together in a playbook to configure a complete server.

Gotchas

  • Variables in defaults/main.yml have the lowest precedence — they are easily overridden by inventory or playbook vars
  • Variables in vars/main.yml have higher precedence and are harder to override — use them for role-internal constants
  • Role dependencies in meta/main.yml are applied before the role's own tasks
  • Tag roles in requirements.yml and install with ansible-galaxy install -r requirements.yml

Context

Building reusable Ansible configuration components for server setup and application deployment

Revisions (0)

No revisions yet.