【问题标题】:Using tilde in ansible "when" statements to build file names from variables在 ansible “when” 语句中使用波浪号从变量构建文件名
【发布时间】:2019-04-04 20:18:57
【问题描述】:

~ 在 ansible "when" 语句中的行为令人费解。例如,如果 LIB 是一个事实,由 set_fact 设置,值为“lib64”,我希望以下语句在 /usr/lib64/cernlib/2006 存在时为真,否则为假:

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

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

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

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

我可以很容易地想象一个错字会导致“何时”给我一个“假”的结果,但我对这总是给我“真”的事实感到困惑。

我是不是做错了什么?

【问题讨论】:

    标签: ansible ansible-facts


    【解决方案1】:

    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
    

    显示:

    致命:[本地主机]:失败! => {"msg": "条件检查'/scratch/test-83.yml is exists'失败。错误是:模板字符串时模板错误:意外'/'。

    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]
    

    【讨论】:

    • 很公平。但我很好奇:有没有办法正确地进行我尝试的连接?另外,为什么当我尝试它时“when”返回“true”,而不是“false”?
    • 语法“变量是 test_name”是强制性的。我已经更新了答案。可能“当”返回任何非零作为“真”。
    • > 可能“when”返回任何非零作为“true”。但是,如果我编写不带变量的“when”,例如:when:“'/scratch/lib64/cernlib/2006' is exists”,则测试的行为符合预期。 (如果路径存在,则为 true,否则为 false。)也许这是一些早期版本的 ansible 的意外保留?
    • 是的。这种特定的组合有效。我已经更新了答案。
    • 是的,这与我发现的相符(如果交换单引号和双引号也可以)。但是,如果我在测试中的任何地方使用波浪号,无论是像我上面所做的那样,或者甚至像 '/usr'~'' 这样简单,测试总是返回“true”,无论路径是否实际存在。
    猜你喜欢
    • 2019-06-25
    • 2019-10-05
    • 2020-10-10
    • 2017-07-06
    • 2019-05-03
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2013-07-25
    相关资源
    最近更新 更多