Ansible Variable example
Limited Time Offer!
For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!
Declare variables with vars:
- name: To create group deploy
hosts: web
vars:
groupname: deploy
firstname: Bhavya
lastname: sharma
tasks:
- name: to create group deploy
ansible.builtin.group:
name={{ groupname }}
state=present
Declare variables in external file:
- name: To create group deploy
hosts: web
vars_files:
- vars-file.yaml
tasks:
- name: to create group deploy
ansible.builtin.group:
name={{ groupname }}
state=present
vars-file.yaml
groupname: deploy
firstname: Bhavya
lastname: sharma
Declare variables in include file:
- name: To create group deploy
hosts: web
vars_files:
- vars-file.yaml
tasks:
- name: to create group deploy
ansible.builtin.group:
name={{ groupname }}
state=present
- name: include default step variables
include_vars: var-include.yml
- name: Print the variable value
ansible.builtin.debug:
msg: welcome {{ firstname }} {{ lastname }}
vars-file.yaml
groupname: deploy
firstname: Bhavya
lastname: sharma
* scope is higher if you define in include file
* value of variable will be value defined in include file
Declare variables using prompt:
- name: To create group deploy
hosts: web
vars_files:
- vars-file.yaml
vars_prompt:
- name: "myname"
prompt: "enter your name?"
private: false
tasks:
- name: to create group deploy
ansible.builtin.group:
name={{ groupname }}
state=present
- name: include default step variables
include_vars: var-include.yml
- name: Print the vars
ansible.builtin.debug:
msg: Enter your name{{ myname }}
vars-file.yaml
groupname: deploy
firstname: Bhavya
lastname: sharma
* scope is higher if you pass from prompt
Declare variables command line :
cmd: ansible-playbook -i inventory creategroup.yaml -e firstname=bhavya -e lastname=sharma
<creategroup.yaml>
- name: To create group deploy
hosts: web
vars_files:
- vars-file.yaml
vars_prompt:
- name: "myname"
prompt: "enter your name?"
private: false
tasks:
- name: to create group deploy
ansible.builtin.group:
name={{ groupname }}
state=present
- name: include default step variables
include_vars: var-include.yml
- name: Print the vars
ansible.builtin.debug:
msg: Enter your name{{ myname }}
vars-file.yaml
groupname: deploy
firstname: Bhavya
lastname: sharma