TExcelTAD

Variables

Variables are what let one playbook configure a staging box and a production cluster differently. They are referenced with Jinja2: "{{ app_port }}".

Where you can define them

Place Typical use
group_vars/, host_vars/ per-environment and per-host settings (Groups, host_vars & group_vars)
a role's defaults/main.yml the role's tunable settings, meant to be overridden
a role's vars/main.yml the role's internal constants, not meant to be overridden
vars: in a play values local to that play
vars_files: in a play values from a file, e.g. an encrypted one
-e / --extra-vars on the command line one-off overrides; always win
register, set_fact values computed during the run (register, facts)

Types and structures

Variables are YAML, so they can be strings, numbers, booleans, lists and dictionaries, nested freely:

bash · try it yourself
cat > vars.yml <<'YML'
- name: Variable types
  hosts: localhost
  gather_facts: false
  vars:
    app_name: linkly
    app_replicas: 3
    app_debug: false
    app_ports: [8080, 8443]
    app_db:
      host: db1.internal
      port: 5432
      name: linkly
  tasks:
    - name: Use them
      ansible.builtin.debug:
        msg:
          - "{{ app_name }} x{{ app_replicas }}, debug={{ app_debug }}"
          - "first port: {{ app_ports[0] }}, all: {{ app_ports | join(',') }}"
          - "db: {{ app_db.host }}:{{ app_db['port'] }}/{{ app_db.name }}"
          - "replicas + 1 = {{ app_replicas + 1 }}"
YML
ansible-playbook vars.yml | sed -n '/msg/,/]/p'
    "msg": [
        "linkly x3, debug=False",
        "first port: 8080, all: 8080,8443",
        "db: db1.internal:5432/linkly",
        "replicas + 1 = 4"
    ]

app_db.host and app_db['port'] are the same thing. Use brackets when the key has a dash or clashes with a Python method name (app_db['items'], not app_db.items).

Naming rules

  • Letters, digits and underscores only, starting with a letter: app_port, never app-port.
  • Prefix with the role or app name (nginx_worker_processes, linkly_db_host). Variables are global per host, so a generic port set in one role leaks into every other role.
  • Avoid reserved names: Ansible's own keywords and magic variables (name, port, environment, hosts, vars, tags, remote_user, …). ansible-core 2.21 warns:
bash · try it yourself
cat > bad.yml <<'YML'
- name: Reserved names
  hosts: localhost
  gather_facts: false
  vars:
    environment: prod
  tasks:
    - name: Show it
      ansible.builtin.debug:
        msg: "{{ environment }}"
YML
ansible-playbook bad.yml 2>&1 | head -3
[WARNING]: Found variable using reserved name 'environment'.
Origin: /home/learner/bad.yml:5:5

Extra vars from the command line

-e accepts key=value pairs (values are strings), YAML/JSON (types kept) or @file:

bash · try it yourself
cat > deploy.yml <<'YML'
- name: Extra vars
  hosts: localhost
  gather_facts: false
  vars:
    release: v1
    replicas: 2
  tasks:
    - name: Show
      ansible.builtin.debug:
        msg: "release={{ release }} replicas={{ replicas }} ({{ replicas | type_debug }})"
YML
ansible-playbook deploy.yml | grep msg
ansible-playbook deploy.yml -e release=v2 -e replicas=5 | grep msg
ansible-playbook deploy.yml -e '{"release": "v3", "replicas": 5}' | grep msg
printf 'release: v4\nreplicas: 7\n' > prod.yml
ansible-playbook deploy.yml -e @prod.yml | grep msg
    "msg": "release=v1 replicas=2 (int)"
    "msg": "release=v2 replicas=5 (str)"
    "msg": "release=v3 replicas=5 (int)"
    "msg": "release=v4 replicas=7 (int)"

With key=value, 5 arrived as the string '5'; with JSON or a file it stayed an integer. That difference matters in comparisons (replicas > 3 fails on a string), so cast with | int or pass JSON.

Magic variables

Ansible defines some variables itself:

Variable Value
inventory_hostname the host's name in the inventory
group_names the groups this host is in
groups every group → its hosts
hostvars every host → its variables
playbook_dir, role_path folders, for building paths
ansible_check_mode true during --check
ansible_play_hosts the hosts still active in this play

Test yourself

Why prefix variables with the role name, e.g. nginx_port?

  1. Ansible requires it
  2. Variables are global per host, so short names collide between roles
  3. It makes them secret
  4. It is faster

-e replicas=5 is passed. What type is replicas?

  1. int
  2. string
  3. float
  4. list

Which variable holds the current host's name as written in the inventory?

  1. ansible_host
  2. inventory_hostname
  3. hostname
  4. group_names