DevOps Classroom notes 13/Feb/2026

Variables in Ansible

  • Refer Here for official docs
  • Ansible allows us to use variables which can be changed during execution.
  • Variables can have default values
  • Ansible allows to set variables from multiple places, ansible has precedence order.
  • Where we can set ansible variables
Give me tabular summary of where we can set variables in ansible
  • Ansible uses {{ variable_name }} to get the variable value.
  • This syntax is inspired for jinja2 templates
Give me simple examples of jinja2 template expressions, i will be using them in ansible

Lets create a simple playbook

  • The playbook is
---
- name: learning variables
  hosts: dev
  tasks:
    - name: var1
      ansible.builtin.debug:
        msg: Hello {{ var1  }}
    - name: var2
      ansible.builtin.debug:
        msg: Hello {{ var2 }}
  • The inventory is
[dev]
localhost
  • Lets execute the playbook without passing any values. The playbook execution fails
  • lets execute the playbook by passing variable values using extravars
ansible-playbook -i hosts var_demo.yaml -e var1=sita  -e var2=geeta
  • Now lets assign default values if variable is not defined
---
- name: learning variables
  hosts: dev
  tasks:
    - name: var1
      ansible.builtin.debug:
        msg: Hello {{ var1 | default(' ') }}
    - name: var2
      ansible.builtin.debug:
        msg: Hello {{ var2 | default(' ') }}

  • using default expression works but defining that everytime is often missed.
  • We can define variables in or around inventory files as well
  • Inventory has host and group, we can define variable at group level or inventory level
  • host level
[dev]
localhost var1=NA  var2=NA
  • Playbook
---
- name: learning variables
  hosts: dev
  tasks:
    - name: var1
      ansible.builtin.debug:
        msg: Hello {{ var1  }}
    - name: var2
      ansible.builtin.debug:
        msg: Hello {{ var2 }}

  • Group level vars
[dev]
localhost

[dev:vars]
var1=NA  
var2=NA

  • If you have many variables to add, directly adding them to inventory is not a good idea
inventory/
├── hosts
├── group_vars/
│   ├── all.yml
│   ├── webservers.yml
│   └── dbservers.yml
└── host_vars/
    ├── web1.yml
    ├── web2.yml
    └── db1.yml

  • Next topics
    • Ansible also has special variables list all ansible special variables with its purpose in tabular form
    • facts
Published
Categorized as Uncategorized Tagged

By continuous learner

devops & cloud enthusiastic learner

Leave a comment

Turn on JavaScript to leave a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Social Media Icons Powered by Acurax Web Design Company
Exit mobile version
%%footer%%