Ansible Roles - Role Variables
Introduction
In Ansible, roles are a way to organize playbooks and facilitate reusability. Role variables are crucial to define and control the behavior of roles. This lesson will delve into the types, usage, and best practices for role variables in Ansible.
Definition
Role variables are variables defined within the context of a role that can influence how tasks within that role operate. They allow for a flexible and dynamic configuration of roles based on their environment or usage context.
Types of Role Variables
Role variables can be categorized into the following types:
- Default Variables: Defined in the
defaults/main.yml
file of the role. - Vars: Defined in the
vars/main.yml
file of the role. - Extra Variables: Passed at runtime using the
-e
option in the command line. - Inventory Variables: Defined in the inventory file or through host_vars/group_vars.
Usage
To use role variables effectively, follow these steps:
- Define default variables in
defaults/main.yml
: - Define role-specific variables in
vars/main.yml
: - Use variables in your tasks:
- Override variables at runtime:
# defaults/main.yml
---
http_port: 80
max_clients: 200
# vars/main.yml
---
server_name: myserver.local
# tasks/main.yml
- name: Ensure Apache is installed
apt:
name: apache2
state: present
- name: Configure Apache
template:
src: httpd.conf.j2
dest: /etc/apache2/sites-available/{{ server_name }}.conf
ansible-playbook site.yml -e "http_port=8080"
Best Practices
When working with role variables, consider the following best practices:
- Use descriptive names for variables to enhance readability.
- Document variables in your role to explain their purpose.
- Use defaults for optional variables to prevent errors.
- Avoid hardcoding values; prefer using variables instead.
FAQ
What are role variables in Ansible?
Role variables are specific to a role's context and are used to configure tasks within that role.
How do I override role variables?
You can override role variables at runtime using the -e
flag followed by the variable assignment.
Where should I define my role variables?
Default variables should be defined in defaults/main.yml
and any role-specific variables in vars/main.yml
.