How to use another variable in Ansible variable?

527 Views Asked by At

How to make the echo statement here correct?When I use Ansible debug module is able to correctly get the value, but not in the shell module.

cat /data/info.txt
a:8080,b:8081,c:8082
cat /data/num
0
 - hosts: dev
   remote_user: root
   gather_facts: false
   tasks:
     - name: get dir path and port info
       shell: cat /data/info.txt
       register: info

     - name: get the last num
       shell: cat /data/num
       register: num

     - name: test
       shell: echo {{ info.stdout.split(',')[{{ num.stdout }}].split(':')[0] }} >>/tmp/test.txt
1

There are 1 best solutions below

1
On BEST ANSWER

Once you open a Jinja2 expression with {{, you should use bare variables until it is terminated with }}. Quoting the FAQ:

Another rule is ‘moustaches don’t stack’. We often see this:

{{ somevar_{{other_var}} }} 

The above DOES NOT WORK


What you might be looking for (because you still didn't include your expected result) is:

shell: echo {{ info.stdout.split(',')[ num.stdout|int ].split(':')[0] }} >>/tmp/test.txt

On top of not stacking the moustaches, you need to pay attention to types and cast the second value (retrieved from /data/num) to integer.