# ansible / foundations / variables

Dynamic Playbooks with Variables

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.

Variable Injection
Declarationapp_port: 8080
Usagelisten: "{{ app_port }}"
Outputlisten: 8080
Dynamic
Execution
Reusable
Code
# concept

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.

scalability

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.

safety

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.

# catalog

Types of Ansible Variables

Variable Type Example Implementation Purpose & 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.
# demonstration

Variables in Action

site.ymlYAML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
---
- 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.

# best-practices

Critical Rules & Precedence

SYNTAX RULE

Always put quotes around a variable if it starts a value! For example, name: {{ myname }} will trigger a YAML syntax error. It must be written as name: "{{ myname }}".

PRECEDENCE

If the same variable is defined in multiple places, Ansible follows a strict precedence list. Extra vars (passed via the CLI with -e) have the highest priority and will overwrite any variable in files or roles.