Ansible variables: register, include_vars and anchors
Define, capture and import Ansible variables, and reuse YAML blocks with anchors and aliases.
Ansible variables let you parameterise playbooks, roles and inventories. This page covers defining a variable, capturing command output with register, importing a variable file and using YAML anchors.
Define a variable in a playbook
- name: Example Simple Variable
hosts: all
become: yes
vars:
username: bob
tasks:
- name: Add the user {{ username }}
ansible.builtin.user:
name: "{{ username }}"
state: present
Capture output with register
A variable saved with register belongs to the host that ran the task. Another host can read it through hostvars.
- hosts: localhost
tasks:
- command: /bin/echo "this is a test"
register: foo
- hosts: anotherhost
tasks:
- debug: var=foo
when: foo is defined
- debug: var=hostvars['localhost']['foo']
when: hostvars['localhost']['foo'] is defined
On anotherhost, foo is not defined: the first task is skipped, and the second reads the value stored for localhost.
Import a variable file
File var_name.yaml:
name1: test1
Playbook:
---
- name: writing something
hosts: all
tasks:
- include_vars: var_name.yaml
- debug: msg="My name is {{ name1 }}"
YAML anchors and aliases
An anchor (&) names a block, an alias (*) references it, and the merge key << copies a block into another one.
- name: Example Anchors and Aliases
hosts: all
become: yes
vars:
user_groups: &user_groups
- devs
- support
user_1:
user_info: &user_info
name: bob
groups: *user_groups
state: present
create_home: yes
user_2:
user_info:
<<: *user_info
name: christina
user_3:
user_info:
<<: *user_info
name: jessica
groups: support
tasks:
- name: Add several groups
ansible.builtin.group:
name: "{{ item }}"
state: present
loop: "{{ user_groups }}"
- name: Add several users
ansible.builtin.user:
<<: *user_info
name: "{{ item.user_info.name }}"
groups: "{{ item.user_info.groups }}"
loop:
- "{{ user_1 }}"
- "{{ user_2 }}"
- "{{ user_3 }}"
Notes
- The variable file imported with
include_varsmust be given by its path. - In the anchors example, the missing closing quote on
"{{ user_2 }}was added. - Sources: Ansible variables (EDUCBA), Ansible up and running, chapter 4 (O'Reilly), Ansible lists and dictionaries (Red Hat), Ansible variables (Spacelift).