Operations 16 min read

Mastering Ansible Playbook Variables: Priorities, Definitions, and Best Practices

This guide explains Ansible variable precedence, various ways to define variables—including inventory files, host_vars/group_vars, var_files, vars_prompt, command‑line extra vars, playbook vars, role vars, facts, register, and hostvars—while providing practical YAML examples and code snippets for each method.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Ansible Playbook Variables: Priorities, Definitions, and Best Practices

Variable Priority

extra vars

(passed with -e) – highest priority

Connection variables defined in inventory (e.g., ansible_ssh_user) – second priority

Other variables such as command‑line overrides, play vars, include vars, role vars – third priority

Variables defined directly in the inventory file – fourth priority

Automatically discovered facts – fifth priority

Role default variables – lowest priority

In an inventory list, a variable defined for a single host overrides the same variable defined for a group.

YAML Trap

When a value starts with {{ foo }}, the entire line must be quoted to avoid being interpreted as a YAML dictionary.

|---
| hosts: app_servers
| vars:
|   app_path: "{{ base_path }}/data/web"

Methods to Define Variables

1. Define in Inventory Host List

Variables can be added directly to /etc/ansible/hosts and apply only to the specified host or group.

| $ egrep -v "^#|^$" /etc/ansible/hosts
| 10.4.7.101 key=20180101
| 10.4.7.102 key="niubility"
|---
| - hosts: all
|   gather_facts: False
|   tasks:
|   - name: show key
|     debug: msg="the {{ inventory_hostname }} value is {{ key }}"

2. Use host_vars and group_vars Directories

Create host_vars and group_vars under the Ansible configuration directory ( /etc/ansible/ or /usr/local/etc/ansible/) and place variable files there.

# /etc/ansible/host_vars/10.4.7.101
---
user: root
pass: root@123

# /etc/ansible/group_vars/test
---
user: work
pass: work@123

3. Define with vars_files

# vars.yml
---
key: jiayou

# bo.yml
---
- hosts: all
  gather_facts: False
  vars_files:
    - vars.yml
  tasks:
    - name: display
      debug: msg="the {{ inventory_hostname }} value is {{ key }}"

4. Interactive Prompt with vars_prompt

# prom.yml
---
- hosts: test
  remote_user: root
  vars_prompt:
    - name: "var1"
      prompt: "please input your name"
      private: no
    - name: "var2"
      prompt: "please input your age"
      private: yes
      default: 18
  tasks:
    - name: display var1
      debug: msg="your name is {{ var1 }}"
    - name: display var2
      debug: msg="your age is {{ var2 }}"

5. Pass Variables via Command Line ( --extra-vars )

# exap.yml
---
- hosts: "{{ hosts }}"
  remote_user: "{{ user }}"
  tasks:
    - name: test
      debug: msg="your hosts is {{ hosts }}, user is {{ user }}"

# Run
ansible-playbook exap.yml -e "hosts=test user=root"

6. Define Variables Inside Playbook ( vars Section)

# playbook.yml
---
- hosts: test
  remote_user: root
  vars:
    dir1: /root/Ansible
    dir2: /root/Ansible/test1
    dir3: /root/Ansible/test2
  tasks:
    - name: create dir1
      file: name={{ dir1 }} state=directory
    - name: create dir2
      file: name={{ dir2 }} state=directory
    - name: create dir3
      file: name={{ dir3 }} state=directory

7. Define Variables in Roles

# roles/test/vars/main.yml
---
var1: value1
var2: value2
var3: value3

8. Use Automatically Collected Facts

Facts provide system information such as IP address, OS version, hostname, etc.

# ansible test -m setup | grep "ansible_python_version"
"ansible_python_version": "2.7.5",
# ansible test -m setup | grep "ansible_nodename"
"ansible_nodename": "template",

Facts can be disabled with gather_facts: no to speed up execution.

9. Register Variable from Task Output

# register.yml
---
- hosts: test
  remote_user: root
  tasks:
    - name: get IP
      shell: hostname -I
      register: info
    - name: display IP
      debug: msg="this host ip is {{ info.stdout }}"

10. Access Variables of Other Hosts with hostvars

# test.yml
---
- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
    - name: show addr from host 10.4.7.101
      debug: msg="She comes from {{ hostvars['10.4.7.101']['addr'] }}"
    - name: show user and age from host 10.4.7.102
      debug: msg="I am {{ hostvars['10.4.7.102']['user'] }}, age {{ hostvars['10.4.7.102']['age'] }}"

11. List, Loop, and Dictionary Variables

Variables can be lists and used with loops.

# test.yml
---
- hosts: test
  remote_user: root
  gather_facts: False
  vars:
    list: [1,2,3]
  tasks:
    - name: echo list
      debug: msg="{{ list }}"
    - name: loop over list
      debug: msg="{{ item }}"
      with_items: "{{ list }}"
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationVariablesAnsiblePlaybook
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.