How To Use Variables In Ansible Playbooks: The Ultimate guide

Variables In Ansible

Table of Contents

Objectives

By the end of this guide, you’ll know how to:

  • Create and use variables in Ansible playbooks

  • Manage variables for hosts and groups

  • Capture command outputs using registered variables

  • Understand which variable value takes priority when conflicts happen

What is Ansible Variables?

Ansible supports variables that can be used to store values and Variables in Ansible help you reuse information, reduce repetition, and make playbooks easier to manage and update .

Examples of what variables can store:

• Users to create

• Packages to install

• Services to restart

• Files to remove

• Archives to retrieve from the internet

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

The following table illustrates the difference between invalid and valid variable names.

Examples of Invalid and Valid Ansible Variable Names:

How to Define Variables ?

In Ansible, you can define variables in several places. To keep things easy, think of them as three main levels:

  1. Global Level – These are variables you set from the command line or in the Ansible configuration file.

  2. Play Level – These are variables defined inside a playbook or related files.

  3. Host Level – These are variables set for specific hosts or groups in the inventory, discovered through fact gathering, or created with registered tasks.

When Ansible finds the same variable name in more than one place, it follows a simple rule:
The more specific variable wins .

  • Host-level variables can be overridden by play-level variables.

  • Play-level variables can be overridden by global-level variables.

In other words, the closer the variable is to the command being run, the higher its priority.

How To Use Variables in Ansible Playbooks?

Variables are an important part of Ansible playbooks because they make it easy to manage values that may change. Instead of repeating the same information in multiple tasks, you can define a variable once and reuse it anywhere in the playbook.

Defining Variables in a Playbook:

You can define your own variables directly inside a playbook. For example:

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

Here, user and home are variables that can be used later in tasks.

Using External Variable Files:

Instead of defining variables inside the playbook, you can store them in external files. This helps keep playbooks clean and organized.

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

The file vars/users.yml might contain:

user: joe
home: /home/joe

 Using Variables in Tasks:

Once you define variables, you can use them in tasks by wrapping the name in double curly braces: 

vars:
   user: joe
tasks:
- name: Creates the user {{ user }}
user:
name: "{{ user }}"

Ansible will replace {{ user }} with “joe” when the play runs.

Important:

Always Use Quotes When a Variable Starts a Value

When a variable is the first item after a colon (:), you must put it in quotes.
Without quotes, Ansible may think you are trying to start a YAML dictionary and give an error.

Incorrect:

yum:
  name: {{ service }}

Correct:

yum:
  name: "{{ service }}"

Using quotes avoids YAML parsing errors and ensures Ansible reads the variable correctly.

Host And Group Variables in Ansible

Ansible lets you assign variables to specific hosts or whole groups of hosts. These are called host variables and group variables.

  • Host variables → Apply to one specific host

  • Group variables → Apply to every host in a host group

In terms of priority:
Host variables override group variables, and playbook variables override both.

You may see variables defined directly inside the inventory file, although this method is now considered outdated.

Example: Setting a variable for a single host

[servers]
demo.example.com ansible_user=joe

Example: Setting a variable for an entire group 

[servers]
 demo1.example.com
 demo2.example.com

[servers:vars]
user=joe
Example: Setting variables in a group made of subgroups
 [servers1]
demo1.example.com
demo2.example.com

[servers2]
demo3.example.com
demo4.example.com

[servers:children]
servers1
servers2

[servers:vars]
user=joe

Some disadvantages of this approach are that it makes the inventory file more difficult to work with, it mixes information about hosts and variables in the same file, and uses an obsolete syntax.

Using Directories to Populate Host and Group Variables:

The preferred approach to defining variables for hosts and host groups is to create two directories, group_vars and host_vars, in the same working directory as the inventory file or directory. These directories contain files defining group variables and host variables, respectively.

    group_vars/
→ Contains files for group variables
    host_vars/ → Contains files for host-specific variables

The following examples illustrate this approach in more detail. Consider a scenario where there are two Data Centers to manage and the data center hosts are defined in the ~/project/inventory inventory file:

[admin@station project]$ cat ~/project/inventory
[datacenter1]
demo1.example.com
demo2.example.com
[datacenter2]
demo3.example.com
demo4.example.com
[datacenters:children]
datacenter1
datacenter2

 If you need to define a general value for all servers in both data centers, set a group variable for the datacenters host group:

[admin@station project]$ cat ~/project/group_vars/datacenters
package: httpd

 If the value to define varies for each data center, set a group variable for each data center host group:

[admin@station project]$ cat ~/project/group_vars/datacenter1
package: httpd
[admin@station project]$ cat ~/project/group_vars/datacenter2
package: apache

 If the value to be defined varies for each host in every data center, then define the variables in separate host variable files:

[admin@station project]$ cat ~/project/host_vars/demo1.example.com
package: httpd
[admin@station project]$ cat ~/project/host_vars/demo2.example.com
package: apache
[admin@station project]$ cat ~/project/host_vars/demo3.example.com
package: mariadb-server
[admin@station project]$ cat ~/project/host_vars/demo4.example.com
package: mysql-server

The directory structure for the example project, project, if it contained all the example files above, would appear as follows:

project
├── ansible.cfg
├── group_vars
│ ├── datacenters
│ ├── datacenters1
│ └── datacenters2
├── host_vars
│ ├── demo1.example.com
│ ├── demo2.example.com
│ ├── demo3.example.com
│ └── demo4.example.com
├── inventory
└── playbook.yml

Inventory variables are overridden by variables set in a playbook, but both kinds of variables 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.

Extra variables can be useful when you need to override the defined value for a variable for a one- off run of a playbook. For example:

[user@demo ~]$ ansible-playbook main.yml -e "package=apache"

Using Arays as Variables

Instead of assigning configuration data that relates to the same element (a list of packages, a list of services, a list of users, and so on), to multiple variables, administrators can use arrays. One consequence of this is that an array can be browsed.

For example, consider the following snippet:

user1_first_name: Bob
user1_last_name: Jones
user1_home_dir: /users/bjones
user2_first_name: Anne
user2_last_name: Cook
user2_home_dir: /users/acook

This could be rewritten as an array called users:

users:
bjones:
first_name: Bob
last_name: Jones
home_dir: /users/bjones
acook:
first_name: Anne
last_name: Cook
home_dir: /users/acook

You can then use the following variables to access user data:

Dot notation

users.bjones.first_name   # Returns "Bob"
users.acook.home_dir # Returns "/users/acook"

Dictionary-style syntax

users['bjones']['first_name']   # Returns "Bob"
users['acook']['home_dir'] # Returns "/users/acook"

Both styles work because the array is stored internally as a Python dictionary.

Capturing Command Output With Registered Variables

Administrators can use the register statement to capture the output of a command. The output is saved into a temporary variable that can be used later in the playbook for either debugging purposes or to achieve something else, such as a particular configuration based on a command’s output.

How Registered Variables Work:

When you add register: some_variable to a task, Ansible stores everything about that task’s result—messages, return codes, output, and more—inside the variable you specify.

The following playbook demonstrates how to capture the output of a command for debugging purposes:

---
- name: Installs a package and prints the result
hosts: all
tasks:
- name: Install the package
yum:
name: httpd
state: installed
register: install_result
- debug: var=install_result
  • The yum task attempts to install the httpd package.

  • The result of that task is saved in install_result.

  • The debug task prints the contents of the variable.

When you run the playbook, the debug task displays what was stored:

[user@demo ~]$ ansible-playbook playbook.yml
PLAY [Installs a package and prints the result] ****************************
TASK [setup] ***************************************************************
ok: [demo.example.com]
TASK [Install the package] *************************************************
ok: [demo.example.com]
TASK [debug] ***************************************************************
ok: [demo.example.com] => {
"install_result": {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.6-40.el7.x86_64 providing httpd is already installed"
]
}
}
PLAY RECAP *****************************************************************
demo.example.com : ok=3 changed=0 unreachable=0 failed=0

Conclusion:

Successfully managing variables in ansible is what separates a beginner from a professional automation engineer. By using the techniques we discussed—such as group_vars, host_vars, and encrypted secrets—you can create playbooks that are both flexible and secure. Keep practicing by managing variables in ansible across different environments to see how much time you can save with proper automation!

You can also visit ansible official website https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_variables.html to know more about Ansible Variables.

You can also visit my official website https://linuxgktech.com/ansible/to know more about Ansible concept.

Scroll to Top