Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: how to construct a variable from another variable and then fetch it's value

Tags:

ansible

Here is my problem I need to use one variable 'target_host' and then append '_host' to it's value to get another variable name whose value I need. If you look at my playbook. Task nbr 1,2,3 fetch the value of variable however nbr 4 is not able to do what I expect. Is there any other way to achieve the same in ansible?

   ---     - name: "Play to for dynamic groups"       hosts: local        vars:         - target_host: smtp         - smtp_host: smtp.max.com       tasks:         - name: testing           debug: msg={{ target_host }}         - name: testing           debug: msg={{ smtp_host }}         - name: testing           debug: msg={{ target_host }}_host         - name: testing           debug: msg={{ {{ target_host }}_host }}   Output:  TASK: [testing] ***************************************************************  ok: [127.0.0.1] => {     "msg": "smtp" }  TASK: [testing] ***************************************************************  ok: [127.0.0.1] => {     "msg": "smtp.max.com" }  TASK: [testing] ***************************************************************  ok: [127.0.0.1] => {     "msg": "smtp_host" }  TASK: [testing] ***************************************************************  ok: [127.0.0.1] => {     "msg": "{{{{target_host}}_host}}" } 
like image 467
Max Avatar asked Mar 26 '15 10:03

Max


People also ask

How do you pass external variables in Ansible?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

What is Foo Ansible?

foo: field1: one field2: two. You can then reference a specific field in the dictionary using either bracket notation or dot notation: foo['field1'] foo.field1. These will both reference the same value (“one”).


1 Answers

If you have a variable like

vars: myvar: xxx xxx_var: anothervalue

the working Ansible syntax:

- debug: msg={{ vars[myvar + '_var'] }}

will give you the analogue of:

- debug: msg={{ xxx_var }}

like image 139
Nikita Kazantsev Avatar answered Sep 20 '22 12:09

Nikita Kazantsev