过滤器:参数是字符串v / s变量时的不同行为

时间:2018-06-20 13:01:23

标签: ansible

test.yml

---
- name: First playbook
  hosts: all
  vars:
    foo: '/var/tmp'
    t_path: '/var/tmp/foo/bar'

  tasks:
    - name: 'Passing string to relpath filter'
      debug:
        msg: '{{ t_path | relpath("/var/tmp") }}'

    - name: 'Passing variable to relpath filter'
      debug:
      msg: '{{ t_path | relpath("{{ foo }}") }}'

输出:

 < TASK [Passing string to relpath filter] >
 -----------------------------------------

ok: [host1] => {
"msg": "foo/bar"
}

< TASK [Passing variable to relpath filter] >
-------------------------------------------
ok: [host1] => {
 "msg": "../../../../var/tmp/foo/bar"
 }

为什么在第二种情况下变量的解释不同?

将变量传递给ansible过滤器的正确方法应该是什么?

1 个答案:

答案 0 :(得分:1)

因为您要将字符串{{ foo }}传递到relpath过滤器,并且它返回当前目录内名为{{ foo }}的目录的相对路径(即,存储正在执行的临时文件的目录) )。

在Jinja2语句中引用变量值的正确语法是:

- name: 'Passing variable to relpath filter'
  debug:
    msg: '{{ t_path | relpath(foo) }}'