Sobes.tech
Junior

What does the role consist of, which folders and files make it up?

sobes.tech AI

Answer from AI

The role of Ansible consists of a set of directories and files that define tasks, variables, templates, files, handlers, and metadata for executing a specific function on managed nodes.

Main directory structure of a role:

  • defaults/: Default variable values for the role.
  • vars/: Role-specific variables. Override values from defaults/.
  • tasks/: Main tasks performed by the role. The main.yml file is mandatory.
  • handlers/: Handlers triggered on specific events (e.g., service restart). The main.yml file is mandatory.
  • files/: Files to be copied to managed nodes.
  • templates/: Jinja2 template files to be copied after processing.
  • meta/: Role information: dependencies, author, license. The main.yml file is mandatory.
  • library/: Custom modules.
  • module_utils/: Utilities for custom modules.
  • lookup_plugins/: Lookup plugins.
  • filter_plugins/: Filter plugins.

Example content of tasks/main.yml:

# tasks/main.yml
- name: Install Nginx web server
  ansible.builtin.apt:
    name: nginx
    state: present

- name: Copy Nginx configuration file
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  notify: Reload Nginx

Example content of handlers/main.yml:

# handlers/main.yml
- name: Reload Nginx
  ansible.builtin.service:
    name: nginx
    state: restarted

Example content of templates/nginx.conf.j2:

# templates/nginx.conf.j2
server {
    listen {{ http_port }};
    server_name {{ server_name }};

    location / {
        proxy_pass http://localhost:{{ app_port }};
    }
}

Example content of defaults/main.yml:

# defaults/main.yml
http_port: 80
server_name: localhost
app_port: 8080

The meta/main.yml file contains role metadata:

# meta/main.yml
galaxy_info:
  author: Your Name
  description: A role to install and configure Nginx.
  license: MIT

  min_ansible_version: 2.9

  platforms:
  - name: Debian
    versions:
    - all
  - name: Ubuntu
    versions:
    - bionic

  galaxy_tags: []

dependencies: []

Each directory, except library and module_utils, must contain a main.yml (or main.yaml) file, which serves as the entry point for that part of the role.