Variables in Playbooks
Introduction
In Ansible, variables are a powerful way to manage dynamic values that can change from one run to another. Variables can be used to store values that you want to reuse throughout your playbooks. This allows for more flexible and maintainable playbooks.
Defining Variables
Variables in Ansible can be defined in several places, including:
- Inventory files
- Playbooks
- Roles
- Extra vars
Here is an example of defining a variable in a playbook:
--- - name: Example playbook hosts: all vars: example_variable: "Hello, World!" tasks: - name: Print the variable debug: msg: "{{ example_variable }}"
Using Variables
Once defined, variables can be used in playbooks using the Jinja2 templating syntax {{ variable_name }}
. Here is an example:
--- - name: Using variables example hosts: all vars: greeting: "Welcome to Ansible" tasks: - name: Print greeting debug: msg: "{{ greeting }}"
Variable Precedence
Ansible variables have different levels of precedence. The following list shows the order of precedence from the lowest to the highest:
- Role defaults
- Inventory file or script group vars
- Inventory group_vars/all
- Playbook group_vars/all
- Inventory group_vars/*
- Playbook group_vars/*
- Inventory file or script host vars
- Inventory host_vars/*
- Playbook host_vars/*
- Host facts / cached facts
- Play vars
- Play vars_prompt
- Play vars_files
- Registered vars
- Set_facts / include_vars
- Role (and include_role) vars
- Block vars (only for tasks in block)
- Task vars (only for the task)
- Extra vars (always win)
Facts as Variables
Facts are system properties collected by the setup
module when a playbook runs. These facts can be used as variables in your playbooks. Here is an example:
--- - name: Using facts example hosts: all tasks: - name: Print the system's architecture debug: msg: "The system architecture is {{ ansible_architecture }}"
Default Values
You can provide default values for variables using the Jinja2 syntax. This is useful when a variable might not always be defined. Here is an example:
--- - name: Default values example hosts: all tasks: - name: Print variable with default debug: msg: "{{ my_variable | default('Default Value') }}"
Conclusion
Variables are a fundamental part of creating flexible and maintainable playbooks in Ansible. By understanding how to define, use, and manage variables, you can write more powerful and reusable automation scripts.