Ansible Variables
Table of contents
In Ansible we can define variables in many ways as shown below. Here is the order of precedence from least to greatest (the last listed variables override all other variables)
command line values (for example, -u my_user
, these are not variables)
role defaults (defined in role/defaults/main.yml) 1
inventory file or script group vars 2
inventory group_vars/all 3
playbook group_vars/all 3
inventory group_vars/* 3
playbook group_vars/* 3
inventory file or script host vars 2
inventory host_vars/* 3
playbook host_vars/* 3
host facts / cached set_facts 4
play vars
play vars_prompt
play vars_files
role vars (defined in role/vars/main.yml)
block vars (only for tasks in block)
task vars (only for the task)
include_vars
set_facts / registered vars
role (and include_role) params
include params
extra vars (for example,
-e "user=my_user"
)(always win precedence)
Variables in inventory file of ansible
In Ansible, the inventory file is where you define the target hosts and groups for your playbooks. You can also assign variables to hosts or groups in the inventory file. Here are the different variables you can use in an inventory file:
Host Variables: You can assign specific variables to individual hosts.
For example:
[target_host] host1 ansible_host=192.168.1.100 ansible_user=user1
In this example, ansible_host
and ansible_user
are host variables assigned to the host1
.
Group Variables: You can assign variables to a group of hosts.
For example:
[group_name:vars] ansible_ssh_user=user2
In this example, ansible_ssh_user
is a group variable assigned to the hosts belonging to the group_name
.
Global Variables: You can define global variables that apply to all hosts. For example:
[all:vars] ansible_connection=ssh
In this example, ansible_connection
is a global variable that applies to all hosts.