This article explains variable precedence in Ansible, detailing how values are determined when variables are defined in multiple locations.
This article explains how variables work in Ansible and outlines the concept of variable precedence—i.e., which value Ansible uses when the same variable is defined in multiple locations.Ansible variables store information that might differ between hosts. They serve two main purposes:• Configuring connectivity for Ansible itself.
• Defining settings for your playbooks (for example, configuring DNS server IPs, NTP server IPs, firewall rules, etc.).
Ansible variables are assigned to host objects during playbook execution. Initially, group variables are associated with each host, and then any host-specific variables override these values.
Below is an example inventory file that defines host variables for each host and includes a group variable for the DNS server:
When the same variable is defined both on the host level and in the group, the host-specific variable takes precedence. Consider modifying the inventory for “web2” as follows:
In this scenario, Ansible first associates the group variable (dns_server=10.5.5.3) with all hosts. However, since “web2” is explicitly defined with its own variable (dns_server=10.5.5.4), that value is used during playbook execution.
Variables can also be declared directly within a playbook. Defining variables at the play level overrides both host and group inventory variables. For example, consider the following playbook that configures the DNS server using a play-level variable:
Copy
Ask AI
---- name: Configure DNS Server hosts: all vars: dns_server: 10.5.5.5 tasks: - name: Update DNS settings nsupdate: server: '{{ dns_server }}'
Here, the playbook variable (dns_server: 10.5.5.5) overrides the inventory-defined values during playbook runtime.
ensures that the value provided (dns_server=10.5.5.6) supersedes any values defined in the inventory or playbook. The command below demonstrates a similar override with a different value:
Ansible applies variables following a defined hierarchical order. The order starts from the lowest precedence (role default variables), then proceeds through inventory and playbook variables, and finally applies extra vars provided directly on the command line (the highest precedence). This structure guarantees that more specific variables override more general ones.
That concludes our discussion on variable precedence in Ansible. In the next article, we will explore additional methods to manage and override variables effectively in your Ansible deployments.