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!

Enroll Now
Declare variables with vars:

- name: To create group deploy
  hosts: web
  vars:
    groupname: deploy    
    firstname: Monika
    lastname: GM

  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: Monika
lastname: GM

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: Monika
lastname: GM

* 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: Monika
lastname: GM

* scope is higher if you pass from prompt

Declare variables command line	:
cmd: ansible-playbook -i inventory creategroup.yaml -e firstname=monika -e lastname=gm

<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: Monika
lastname: GM