Ansible Tutorial · Playbooks · Lesson 9 of 20

Ansible Variables

Define, override and inspect variables in playbooks.

Members can save this page, take notes and track progress. See membership · Sign in

Where to define variables

Ansible variables can come from many places. Here are the most common, in rough order of increasing precedence:

  1. Role defaults (roles/myrole/defaults/main.yml) — lowest priority, easy to override.
  2. Inventory variables (group_vars/, host_vars/).
  3. Playbook vars (the vars: section of a play).
  4. Task vars (the vars: on an individual task).
  5. Extra vars (-e on the command line) — highest priority, overrides everything.

The full precedence list has 22 levels, but these five cover 95% of real-world usage.

Defining variables in a playbook

---
- name: Deploy app
  hosts: webservers
  vars:
    app_port: 8080
    app_name: myapp
    app_env: production

  tasks:
    - name: Show app config
      ansible.builtin.debug:
        msg: "{{ app_name }} on port {{ app_port }} ({{ app_env }})"

Extra vars from the command line

ansible-playbook site.yml -e "app_env=staging app_port=3000"

Extra vars win over everything else, so they are ideal for one-off overrides.

register — capture task output

  tasks:
    - name: Get disk usage
      ansible.builtin.command: df -h /
      register: disk_result

    - name: Show disk usage
      ansible.builtin.debug:
        var: disk_result.stdout_lines

The registered variable is a dictionary with keys like .stdout, .stderr, .rc (return code), .stdout_lines and .changed.

set_fact — create a variable at runtime

  tasks:
    - name: Compute app URL
      ansible.builtin.set_fact:
        app_url: "https://{{ inventory_hostname }}:{{ app_port }}"

    - name: Show it
      ansible.builtin.debug:
        var: app_url

Accessing nested variables

vars:
  database:
    host: db.example.com
    port: 5432

tasks:
  - debug:
      msg: "Connect to {{ database.host }}:{{ database.port }}"
  # Bracket notation also works:
  - debug:
      msg: "Connect to {{ database['host'] }}:{{ database['port'] }}"

Undefined variables

By default Ansible errors on undefined variables. You can provide a fallback with the default filter:

msg: "Port is {{ custom_port | default(8080) }}"
Variables and set_fact
cat > /tmp/vars_demo.yml << 'EOF'
---
- name: Variable demo
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    greeting: "Hello"
    target: "World"
  tasks:
    - name: Use variables
      ansible.builtin.debug:
        msg: "{{ greeting }}, {{ target }}!"
    - name: Set a fact
      ansible.builtin.set_fact:
        combined: "{{ greeting }} {{ target }}"
    - name: Use the fact
      ansible.builtin.debug:
        var: combined
EOF
ansible-playbook /tmp/vars_demo.yml

Output

PLAY [Variable demo] **********************************************************

TASK [Use variables] **********************************************************
ok: [localhost] => {
    "msg": "Hello, World!"
}

TASK [Set a fact] *************************************************************
ok: [localhost]

TASK [Use the fact] ***********************************************************
ok: [localhost] => {
    "combined": "Hello World"
}

PLAY RECAP ********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Run this on your computer — see “Get Started” for setup.

Override with extra vars
ansible-playbook /tmp/vars_demo.yml -e "greeting=Hi target=Ansible"

Output

PLAY [Variable demo] **********************************************************

TASK [Use variables] **********************************************************
ok: [localhost] => {
    "msg": "Hi, Ansible!"
}

TASK [Set a fact] *************************************************************
ok: [localhost]

TASK [Use the fact] ***********************************************************
ok: [localhost] => {
    "combined": "Hi Ansible"
}

PLAY RECAP ********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Run this on your computer — see “Get Started” for setup.

Test yourself

Which variable source has the highest precedence?

  1. Role defaults
  2. Playbook vars
  3. Inventory group_vars
  4. Extra vars (-e)
Show answer

Answer: Extra vars (-e)

Extra vars passed with -e on the command line have the highest precedence and override all other variable sources.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake