ansible role and its directory structure - unix1998/technical_notes GitHub Wiki

ansible-galaxy can create the directory structure for an Ansible role. This command-line tool is used to create and manage roles and collections in Ansible. When you use ansible-galaxy to create a new role, it sets up a standardized directory structure that is recommended for organizing your Ansible roles.

Here’s how you can create a new role using ansible-galaxy:

Creating a New Role

To create a new role, use the following command:

ansible-galaxy init <role_name>

For example, if you want to create a role named my_role, you would run:

ansible-galaxy init my_role

Directory Structure

This command will create a directory structure like the following:

my_role/
β”œβ”€β”€ README.md
β”œβ”€β”€ defaults
β”‚   └── main.yml
β”œβ”€β”€ files
β”œβ”€β”€ handlers
β”‚   └── main.yml
β”œβ”€β”€ meta
β”‚   └── main.yml
β”œβ”€β”€ tasks
β”‚   └── main.yml
β”œβ”€β”€ templates
β”œβ”€β”€ tests
β”‚   β”œβ”€β”€ inventory
β”‚   └── test.yml
└── vars
    └── main.yml

Description of Directories and Files

  • README.md: Contains the documentation for the role.
  • defaults/main.yml: Default variables for the role.
  • files/: Directory for files that can be deployed by this role.
  • handlers/main.yml: Handlers, which are typically used to restart services.
  • meta/main.yml: Metadata about the role, including dependencies.
  • tasks/main.yml: The main list of tasks to be executed by the role.
  • templates/: Directory for Jinja2 templates that can be deployed by this role.
  • tests/: Contains test inventory and test playbook for the role.
  • vars/main.yml: Variables for the role.

Example Usage

After creating the role, you can define your tasks in tasks/main.yml:

# my_role/tasks/main.yml
---
- name: Ensure Apache is installed
  apt:
    name: apache2
    state: present
  when: ansible_os_family == "Debian"

You can then include this role in a playbook:

# playbook.yml
---
- hosts: webservers
  roles:
    - role: my_role

Running the Playbook

To run the playbook, use the ansible-playbook command:

ansible-playbook playbook.yml -i inventory

This will apply the role to the hosts defined in your inventory.

By using ansible-galaxy to create your roles, you ensure that your Ansible roles follow a consistent structure, making them easier to manage, share, and understand.

⚠️ **GitHub.com Fallback** ⚠️