ANSIBLE VARIABLES

What is a Variable in Ansible?

In Ansible, a variable is a name (placeholder) used to store a value that can be reused across playbooks, roles, inventories, and tasks.

Variables help make automation:

Simple Definition

Ansible Variable = Placeholder for data

Example

app_port: 8080
        

Usage inside playbook:

{{ app_port }}
        

Why Use Variables?

Types of Ansible Variables

Variable Type Example Purpose
Play vars vars: Used inside a playbook
Inventory vars host var Per host values
Group vars group_vars/web.yml Per group values
Host vars host_vars/server.yml Per host values
Role defaults defaults/main.yml Lowest priority
Role vars vars/main.yml High priority
Facts ansible_os_family System information
Extra vars -e "a=1" Highest priority
Register register: result Capture task output
Set facts set_fact: Runtime variables
vars_prompt User input Ask at runtime
vars_files vars_files: Load from file
Environment vars environment: Set environment variables
Loop vars item Loop iteration
Magic vars hostvars Built-in variables

Example Playbook

---
- hosts: web
  vars:
    myname: "shan"
    myage: 26

  vars_files:
    - ak.yaml

  tasks:
    - name: Display my name and age
      debug:
        msg: "My name is {{ myname }} and my age is {{ myage }}"

    - name: Display OS distribution
      debug:
        msg: "The OS distribution is {{ ansible_distribution }}"

    - name: Display values from external file
      debug:
        msg: "Son of {{ fname }} & {{ mname }}"

    - name: Display host-specific variable
      debug:
        msg: "The server is located in {{ location }}"
        

Step-by-Step Explanation

1️⃣ Hosts Section

- hosts: web

The playbook runs on the web host group.

2️⃣ Playbook Variables

vars:
  myname: "shan"
  myage: 26
        

Available only inside this play.

3️⃣ External Variable File

vars_files:
  - ak.yaml
        

Example ak.yaml:

fname: Kumar
mname: Lakshmi
        

4️⃣ Using Facts

{{ ansible_distribution }}

Automatically collected system information.

5️⃣ Host-Specific Variables

File: host_vars/node1.yaml

location: Chennai
        

This value applies only to that specific host.