Ansible Automation

Dynamic Playbooks with Variables

Lesson 6 of 12 · 8 min · Intermediate

In Ansible, a variable is a placeholder used to store a value that can be reused across playbooks, roles, inventories, and tasks. Stop hard-coding data and make your automation scalable and flexible.

Why Use Variables?

Writing a unique playbook for every single server is impossible to maintain. Variables solve this by allowing you to define the structure once, and feed the specifics in later.

Avoid Hard-Coding

By extracting values like IPs, usernames, and ports, you can reuse the exact same playbook across different environments (dev, test, prod) simply by swapping the variable file.

Reduce Human Errors

If you need to change a package version or a directory path, you update it in one central variable location instead of hunting through hundreds of tasks.

Types of Ansible Variables

Variable TypeExample ImplementationPurpose & Context
Play varsvars:Defined and used directly inside a specific playbook.
Inventory varshost varValues attached to a specific host in the inventory.
Group varsgroup_vars/web.ymlApplied to all hosts within a specific inventory group.
Host varshost_vars/server.ymlApplied exclusively to one specific host.
Role defaultsdefaults/main.ymlFallback variables for roles (Lowest priority).
Role varsvars/main.ymlStrict variables for roles (High priority).
Factsansible_os_familySystem information automatically collected from the target.
Extra vars-e "a=1"Passed via CLI at runtime (Highest priority, overrides all).
Registerregister: resultCaptures and stores the output of a specific task.
Set factsset_fact:Variables dynamically created or calculated during runtime.
vars_promptUser inputPauses execution to ask the user for a value at runtime.
vars_filesvars_files:Loads external YAML files containing variable definitions.
Environment varsenvironment:Sets OS-level environment variables for the shell.
Loop varsitemThe magic variable representing the current iteration of a loop.
Magic varshostvarsBuilt-in Ansible engine variables holding state data.

Variables in Action

site.yml
---
- 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 Breakdown

  • 1. Hosts - hosts: web limits the playbook to run only on the web host group defined in your inventory.
  • 2. Playbook Vars vars: defines variables (myname, myage) that are available exclusively inside this play.
  • 3. External File vars_files: imports external variables from ak.yaml (which contains fname: Kumar and mname: Lakshmi).
  • 4. System Facts {{ ansible_distribution }} is an automatic "Fact" variable collected by Ansible representing the remote OS (e.g., Ubuntu).
  • 5. Host Vars {{ location }} is pulled directly from a file like host_vars/node1.yaml, applying only to that specific host.

Critical Rules & Precedence