Variables
Hard‑coding values in playbooks makes them rigid. Variables allow you to write reusable, dynamic automation. You can define variables in many places – playbooks, inventory, files, or even from command line.
Defining Variables in a Playbook
Use the
vars section in a play:---
- name: Use variables
hosts: all
vars:
package_name: nginx
service_name: nginx
tasks:
- name: Install {{ package_name }}
apt:
name: "{{ package_name }}"
state: present
- name: Start {{ service_name }}
service:
name: "{{ service_name }}"
state: startedVariable substitution uses double curly braces: {{ variable_name }}.Variable Precedence
Variables can be defined in many places. The order of precedence (from lowest to highest) includes: inventory group vars, inventory host vars, playbook
vars, extra vars (-e). In general, the last defined wins.Inventory Variables
You can define variables per host or per group in the inventory file:
[webservers]
web1 ansible_host=192.168.1.10 http_port=8080
[webservers:vars]
nginx_version=1.18Passing Variables from Command Line
Override any variable with
--extra-vars or -e:ansible-playbook playbook.yml -e "package_name=apache2"Using Variables from Files
You can include a file containing variables:
vars_files:
- vars/common.yml
- vars/{{ ansible_os_family }}.ymlRegistering Output as Variables
You can capture a task’s output into a variable using
register:- name: Get uptime
command: uptime
register: uptime_result
- name: Print uptime
debug:
msg: "Uptime is {{ uptime_result.stdout }}"Two Minute Drill
- Variables make playbooks reusable.
- Define in
vars, inventory,vars_files, or command line (-e). - Use
{{ variable }}for substitution. - Register task output with
register.
Need more clarification?
Drop us an email at career@quipoinfotech.com
