如何在 Ansible 变量中使用另一个变量?

How to use another variable in Ansible variable?

如何使这里的echo语句正确?我在使用Ansible时debug模块是可以正确获取到值的,但是在shell模块中却不行

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

一旦你用 {{ 打开一个 Jinja2 表达式,你应该使用裸变量直到它用 }} 终止。引用 FAQ:

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

{{ somevar_{{other_var}} }} 

The above DOES NOT WORK


您可能正在寻找的(因为您仍然没有包括您的预期结果)是:

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

除了不堆叠小胡子之外,您还需要注意类型并将第二个值(从 /data/num 检索)转换为整数。