在无用的“ when”语句中使用波浪号从变量构建文件名

时间:2019-04-04 20:18:57

标签: ansible ansible-facts

〜在“ when”语句中〜的行为令人困惑。例如,如果LIB是由set_fact设置的值“ lib64”的事实,则我希望如果/ usr / lib64 / cernlib / 2006存在,则以下语句为true,否则为false:

  when: '"/usr/" ~ LIB ~ "/cernlib/2006" is exists'

不过,我发现条件始终为真。

如果我省略对LIB的引用而只写:

  when: '"/usr/lib64/cernlib/2006" is exists'

我很容易想到会导致“ when”给我“假”结果的错别字,但令我感到困惑的是,它总是给我“ true”。

我是在做错什么吗?

1 个答案:

答案 0 :(得分:0)

Test syntax说:

  

使用Jinja测试的语法如下:

     

变量为test_name

- set_fact:
    my_path: "/scratch/{{ LIB }}/cernlib/2006"
- debug:
    msg: "{{ mypath }} exists"
  when: my_path is exists

1)使用字符串而不是变量会导致错误。

- debug:
    msg: "/scratch/test-83.yml exists"
  when: /scratch/test-83.yml is exists

显示:

  

致命:[localhost]:失败! => {“ msg”:“条件检查'/scratch/test-83.yml存在'。失败。错误是:模板字符串出错时模板错误:'/'。

2)字符串的引用无济于事

- debug:
    msg: "/scratch/test-83.yml exists"
  when: "/scratch/test-83.yml" is exists

显示:

ERROR! Syntax Error while loading YAML.
  did not find expected key
...
The offending line appears to be:

    msg: "/scratch/test-83.yml exists"
  when: "/scratch/test-83.yml" is exists
                               ^ here
This one looks easy to fix.  It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote.  For instance:
  when: "ok" in result.stdout
Could be written as:
  when: '"ok" in result.stdout'
Or equivalently:
   when: "'ok' in result.stdout"

3)仅此特定的单引号和双引号组合有效

- debug:
    msg: "/scratch/test-83.yml exists"
  when: "'/scratch/test-83.yml' is exists"

经过测试

> ansible --version
ansible 2.7.9
python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]