Ansible Variables

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)

  1. role defaults (defined in role/defaults/main.yml) 1

  2. inventory file or script group vars 2

  3. inventory group_vars/all 3

  4. playbook group_vars/all 3

  5. inventory group_vars/* 3

  6. playbook group_vars/* 3

  7. inventory file or script host vars 2

  8. inventory host_vars/* 3

  9. playbook host_vars/* 3

  10. host facts / cached set_facts 4

  11. play vars

  12. play vars_prompt

  13. play vars_files

  14. role vars (defined in role/vars/main.yml)

  15. block vars (only for tasks in block)

  16. task vars (only for the task)

  17. include_vars

  18. set_facts / registered vars

  19. role (and include_role) params

  20. include params

  21. 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:

  1. 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.

  1. 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.

  1. 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.