Effective variable management is crucial for creating flexible and maintainable Ansible playbooks and roles. Current stable version: Ansible-core 2.20.2 (released January 29, 2026). Here are the latest best practices:
database_port instead of database-port).group_vars, host_vars, and role-specific variables.secrets.yml, config.yml).defaults/main.yml in roles to set default values that can be easily overridden by users.vars/main.yml for role variables that should not be easily overridden.defaults have the lowest precedence, vars have higher precedence.defaults, vars, inventory vars, host vars, group vars, facts, play vars, task vars, role and include vars, block vars, set_facts, registered vars, role defaults, command line values.!vault tags to embed encrypted values directly in playbooks when needed.hostvars to access variables from other hosts.omit to conditionally skip parameter assignment.default filter to provide fallback values: {{ my_var | default('fallback_value') }}combine filter to merge dictionaries: {{ dict1 | combine(dict2) }}regex_replace, replace, and other filters to manipulate variable values.&) and aliases (*) for repeated variable structures:# In vars/main.yml or group_vars/all
defaults: &defaults
max_connections: 100
timeout: 30
production: &production
<<: *defaults
max_connections: 500
timeout: 60
development: &development
<<: *defaults
max_connections: 50
timeout: 15
assert module to validate variable values and ensure requirements are met:- name: Validate required variables
assert:
that:
- database_host is defined
- database_host | length > 0
- database_port is number
- database_port >= 1 and database_port <= 65535
fail_msg: "Database configuration is invalid"
success_msg: "Database configuration is valid"
- name: Get value from environment variable
set_fact:
api_key: "{{ lookup('env', 'API_KEY') }}"
- name: Read value from file
set_fact:
certificate: "{{ lookup('file', '/path/to/cert.pem') }}"
Here is an example of how to define and use variables in a playbook with modern practices:
---
- name: Example Playbook with Modern Variable Practices
hosts: all
vars:
# Basic variable
example_variable: "Hello, World!"
# Using YAML anchors to reduce duplication
app_config_base: &app_config
port: 8080
workers: 4
debug: false
# Environment-specific configuration
app_config_prod:
<<: *app_config
port: 443
workers: 16
debug: false
app_config_dev:
<<: *app_config
port: 8080
workers: 2
debug: true
tasks:
- name: Print example variable
debug:
msg: "{{ example_variable }}"
- name: Set app configuration based on environment
set_fact:
app_config: >-
{{
app_config_prod if inventory_hostname in groups['production']
else app_config_dev
}}
- name: Display app configuration
debug:
var: app_config
namespace.collection_name.variable_nameBy following these best practices, you can ensure that your Ansible playbooks and roles are flexible, secure, and easy to maintain in modern DevOps environments.