Ansible Variables Tutorial: Data Types, Lists, Dictionaries, and Practical Examples

Hello DevOps enthusiasts!

Many repetitive and time-consuming tasks in our daily work can be automated effectively using tools like Ansible. However, to build powerful and reusable automation, one of the most important concepts you need to master is variables.

Variables allow you to write flexible playbooks that can adapt to different environments, applications, and operating systems without hardcoding values.

In this article, we'll explore how variables work in Ansible and learn how to use different data types, lists, and dictionaries through practical examples.

Ansible Variables Overview


What We'll Learn

By the end of this article, you will be able to:

  • Understand variable fundamentals in Ansible
  • Work with common Ansible data types
  • Create and access list variables
  • Manipulate list elements
  • Create and use dictionary variables
  • Access dictionary keys and values
  • Debug variable types using type_debug
  • Build more reusable and maintainable playbooks

Why are Variables important 

Imagine we need to work in Organization managing IT infrastructure requires environments such as:

Development
Testing
Staging
Production

Without variables, you would need separate playbooks for each environment.

With variables, a single playbook can dynamically adapt to different environments by simply changing variable values.

Benefits include:
  • Reusable Playbooks
  • Reduced Hardcoding
  • Easier Maintenance
  • Environment Flexibility
  • Better Automation Design

Variables and Data Types in Ansible

Variables can be defined at various levels:

  • Playbook level
  • Task level
  • Inventory level
  • Group variables
  • Host variables
  • Role defaults
  • Role variables

Ansible supports many of the common Python data types.

Common examples include:

Data TypeExample
String"Vybhava Technologies"
Booleanyes, true
Integer100
Float500.99
List['Linux','Docker']
Dictionary{"el":"httpd"}

Example 1: Understanding Basic Datatypes

In Ansible variables can be defined under global tasks or they can be defined at local to a task level. support all the Python supported datatypes.
---
# Filename: varibles_datatypes.yml
 - name: varibles in ansible
   hosts: localhost
   gather_facts: false
   vars:
     a: "Vybhava Technologies"
     b: yes
     n: 100
     m: 500.99
   tasks:
     - debug:
         msg:
           - "a= {{ a }} a type: {{ a |type_debug }}"
           - "b= {{ b }} b type: {{ b |type_debug }}"
           - "n= {{ n }} n type: {{ n |type_debug }}"
           - "m= {{ m }} m type: {{ m |type_debug }}"
The execution output is :
ansible-playbook varibles_datatypes.yml
 
The type_debug filter helps identify the actual data type stored in each variable.
Example to Understand Ansible Datatypes

Why This Matters

Understanding data types helps prevent issues when:

  • Performing comparisons
  • Running loops
  • Using conditional statements
  • Building templates
  • Consuming API responses

Ansible Lists

A list is one of the most frequently used data structures in automation. In Ansible List object is similar to the Python list. Which can be assigned a list variable within a single line or lease it can be represented in the column which will start by using "-" for each element. 

Example 2: Working with Lists

Here I've experimented with two options.
# File: hello.yml
 - name: List variables from ansible playbook
   hosts: localhost
   gather_facts: no
   vars:
     mylearning_list: ['Linux','git','Jenkins','Docker','Kubernetes','Ansible']
   tasks:
     - name: printing list
       debug:
         msg:
         - "mylearning_list:"
         - "{{  mylearning_list  }}"

     - name: Concatenate a list to string
       set_fact:
         my_string: "{{ mylearning_list | join(',') }}"
     - name: Print the String
       debug:
         msg: "{{ my_string }}"

     - name: printing list element
       debug:
         msg: "mylearning_list: {{  mylearning_list[1] }}"
     - name: printing list range of elements
       debug:
         msg:
         - "mylearning_list[3:5]:"
         - "{{  myle
Execution of Playbook:

Ansible list of element usage 

Understanding List Indexing

Lists start with index 0.

Our Example uses list and its indexes as :

Index   Value
-----   ---------
0       Linux
1       Git
2       Jenkins
3       Docker
4       Kubernetes
5       Ansible

Therefore:

mylearning_list[1]

returns:

Git

And extract range of items from List use [x:y]:

mylearning_list[3:5]

returns:

Docker
Kubernetes

Example 2: Managing Team Members Using Lists

Lists are often used to manage users, servers, environments, or applications.


 hosts: localhost
  gather_facts: no
  vars:
    devops_team:
      - srinu
      - rajshekhar
      - arun
      - charan
      - suresh
      - elavarsi

  tasks:
  - name: Display all elements of List
    debug:
      msg: "{{ devops_team }}"

  - name: Display a elements of List
    debug:
        msg: "{{ devops_team[3] }}"

  - name: Display rage of elements from List
    debug:
        msg: "{{ devops_team[3:6] }}"
~

Real-World Use Cases

Lists are commonly used for:

  • Server inventories
  • User management
  • Package installations
  • Loop operations
  • Application deployments


		   

Ansible Dictionaries

A dictionary stores data as key-value pairs. The python style of dictionaries can be used in Ansible playbooks. The representation is within {} when we have few key:value
The data item will be stored with key and value

Defining Dictionaries

We can define a dictionary variable as two forms : 

1. single line
osfam_web: {"el": "httpd", "ubuntu": "apache2"}

2. multiline form
osfam_web:
  el: httpd 
  ubuntu: apache2
Both representations are valid.

Example 3: Working with Dictionaries


The key identifies the item, and the value stores the associated data.

Example Execution
[ansible@master qa]$ cat mydict.yml
---
# Filename: mydict.yml
 - name: Dictionaries in ansible
   hosts: localhost
   gather_facts: false
   vars:
     osfam: {"el":"httpd","ubuntu":"apache2"}
   tasks:
     - debug:
         msg:
           - "osfam.keys {{ osfam.keys() }}"
           - "osfam {{ osfam }}"
           - "osfam type {{ osfam |type_debug }}"
           - "osfam[el] {{ osfam['el'] }}"
Execution output
ansible-playbook mydict.yml

Why Dictionaries Are Powerful

Dictionaries are extremely useful when you need environment-specific values.

Example:

web_service:
  rhel: httpd
  ubuntu: apache2
  suse: apache2

Then you can dynamically select the correct package:

{{ web_service[ansible_os_family] }}

This allows one playbook to support multiple Linux distributions.

Reader Challenge

Now it's your turn!

Create a playbook that demonstrates all three concepts:

Task Requirements

  1. Create variables for:
    • Company name
    • Number of employees
    • Active status
  2. Create a list containing:
    • Linux
    • Docker
    • Kubernetes
    • Ansible
  3. Create a dictionary that maps:
    • RHEL → httpd
    • Ubuntu → apache2
    • Rocky → httpd
  4. Display:
    • Data types of all variables
    • First and last list elements
    • All dictionary keys
    • Service name for Ubuntu

Bonus Challenge

Create a playbook that automatically selects the correct web server package based on the operating system family.

More variable stories on Ansible Automations are share:

Comments

Popular Articles

Ansible URI Module Tutorial: Real-World Application Health Checks, REST API Validation and DevOps Automation

DevOps Weapons

Ansible Jinja2 Templates: A Complete Guide with Examples