【问题标题】:Concat multiple variables and strings in ansible playbook在 ansible playbook 中连接多个变量和字符串
【发布时间】:2018-01-06 03:19:08
【问题描述】:

在为目标部分执行 with_items 时,我正在尝试多重连接。

现在看起来像这样:

- name: create app except+lookup
  copy: content="" dest="{{ dir.comp ~ '/config/con2dd/' ~ item.name ~ 'File.txt' }}" force=no group=devops owner=devops mode: 0755
  with_items:
...

我明白了:

We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they 
start a value. For instance:            

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

尝试了几种方法,但都没有奏效。

是否可以将变量与字符串连接起来?

【问题讨论】:

    标签: ansible concatenation yaml


    【解决方案1】:

    您没有引用与键 copy 关联的值。为此,first 字符必须是双引号(或单引号)。反馈中给出的示例正确地做到了这一点,但没有明确说明。一旦标量以非引号开头(您的以 c 开头,来自 content 标量中的引号将不再具有特殊含义。

    由于 Ansible 使用的解析器中的一个错误,该标量 (mode: 0755) 中的 :(冒号空格)会引起麻烦,您应该对整个标量进行双引号并转义其中出现的双引号:

    copy: "content=\"\" dest=\"{{ dir.comp ~ '/config/con2dd/' ~ item.name ~ 'File.txt' }}\" force=no group=devops owner=devops mode: 0755"
    

    或者使用单引号(有不同的转义规则:

    copy: 'content="" dest="{{ dir.comp ~ ''/config/con2dd/'' ~ item.name ~ ''File.txt'' }}" force=no group=devops owner=devops mode: 0755'
    

    您可以在 this 在线 YAML 解析器上自己测试标量,它与导致 Ansible 无法正确解析您的 YAML 的错误相同。

    This 解析器,正确处理 in 标量 :,并且不会对您的输入产生错误(但它有其他问题)。

    【讨论】:

      【解决方案2】:

      不要将纯 YAML 和 key=value 语法混合用于参数。并且总是对复杂的参数使用 YAML 语法:

      - name: create app except+lookup
        copy:
          content: ""
          dest: "{{ dir.comp }}/config/con2dd/{{ item.name }}File.txt"
          force: no
          group: devops
          owner: devops
          mode: 0755
        with_items:
        ...
      

      【讨论】:

      • 最终使用了这个艰难的两个都是正确的。谢谢:)
      猜你喜欢
      • 2014-07-28
      • 1970-01-01
      • 2018-12-17
      • 2012-03-28
      • 2016-01-28
      • 1970-01-01
      • 2016-11-15
      相关资源
      最近更新 更多