Skip to content

Variables

Ansible supports variables that can be used to store values that can then be reused throughout files in an Ansible project.

Naming Variables

Variable names must start with a letter, and they can only contain letters, numbers, and underscores. For example web_server.

Variables can be defined in a variety of places:

  • Global scope
  • Play scope
  • Host scope

Defining Variables in Playbooks

A common method is to place a variable in a vars block at the beginning of a playbook:

- hosts: all
  vars:
    user: richard
    home: /home/richard

Or to define playbook variables in external files:

- hosts: all
  vars_files:
    - vars/packages.yml

Using Variables in Playbooks

When a variable is used as the first element to start a value, quotes are mandatory.

vars:
  user: richard

tasks:
  - name: Create user {{ user }}
    user:
      name: "{{ user }}"

Host Variables and Group Variables

Use directories to populate host and group variables by creating two directories group_vars and host_vars.

Example structure:

ansible
├── ansible.cfg
├── group_vars
│   ├── dc1
├── host_vars
│   ├── server.example.com
├── inventory
└── playbook.yml

Overriding Variables from the Command Line

Inventory variables are overridden by variables set in a playbook, which in turn may be overridden through arguments passed to the ansible or ansible-playbook commands on the command line. Variables set on the command line are called extra variables.

Example:

ansible-playbook main.yml -e "package=httpd"

Using Arrays as Variables

You cna also can use arrays, which are iterated over by ansible.

Example:

users:
  bjones:
    first_name: Joe
    last_name: Blogs
    home_dir: /users/jblogs
  acook:
    first_name: John
    last_name: Doe
    home_dir: /users/jdoe

These can be explicitly referenced like this:

users.jdoe.first_name
Registered Variables

Use the register statement to capture the output of a command:

---
- name: Install a package 
  hosts: all
  tasks:
    - name: Install package
      yum:
        name: httpd
        state: installed
      register: install_result

    - debug: var=install_result