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
:
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
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
- 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.
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
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.