All about Ansible Variables

How to pass multiple extra vars in ansible-playbook command

Extra-vars always have the highest precedence for variables when compared to default and role variables.

To pass one variable in extra-vars, execute the below command.

ansible-playbook --extra-vars="var1=a" playbook.yml 

To pass multiple variables in extra-vars, execute the below command.

ansible-playbook --extra-vars="var1=a var2=b var3=c" playbook.yml 

How to access a variable inside another variable(dynamic variable)

Let's see how to concatenate two variable names. As per Ansible rules, Moustaches don’t stack. Suppose you want to concatenate two variables first_var and second_var. The below syntax doesn't work for variable concatenation.

{{ first_var{{second_var}} }}

In Ansible, concatenation is done using + symbol. The correct syntax for concatenating two variables is as below:

{{ vars[first_var + second_var]}}

If you need to append something (say '_user' ) to the first_var,  the syntax will be as below, i.e '_user' should be in quotes.

{{ vars[first_var + '_user']}}

Example playbook

---
- hosts: localhost
  become: yes
  vars:
    a_user: user1
    b_user: user2
    c_user: user3
    auser1: app1
    buser2: app2
    cuser3: app3

  tasks:
    - name: Dynamic variable test1
      set_fact:
       name: "{{vars[ first_var + '_user']}}"
    - name: print
      debug:
       msg: "{{name}}"
    - name: Dynamic variable test2
      set_fact:
       name: "{{vars[ first_var + second_var]}}"
    - name: print
      debug:
       msg: "{{name}}"

Run using the below command:

ansible-playbook --extra-vars="first_var=a second_var=user1" new.yml 

Output:

ok: [localhost]
TASK [Dynamic variable test1] 
TASK [print] 
ok: [localhost] => {
    "msg": "user1"
}

TASK [Dynamic variable test2] 
TASK [print] 
ok: [localhost] => {
    "msg": "app1"
}

Access the register variable of a loop

To access the register variable of a loop, we need to use the variable.results in loop and then access using item

tasks:
- name: List the files and directories
  shell: cat {{item}} 
  loop: "{{paths}}"
  register: op
- name: print
  debug:
   msg: "{{item.stdout_lines}}"
  loop: "{{op.results}}"

if-else condition in variables

Instead of repeating the task twice with two when conditions, we can use if-else conditions in variables. Below are few examples.

vars:
 path: C:\version{{ '32' if ansible_architecture == 'x86' else ''}}\Microsoft
 result: "{{'FAIL' if 'FAIL' in log_result else 'PASS'}}"
Admin

Admin