Ansible中嵌套变量的语法错误

时间:2019-08-01 07:56:12

标签: variables ansible

我在剧本中包含以下变量文件:

more vars/was_vars.yaml
::::::::::::::
10.9.12.112: "/was/IBM/WebSphere"
10.8.10.28: "/was/IBM/profiles"
10.7.120.129: "/app/tmp"

这是我的剧本:

- name: Configure nodes
  hosts: dest_nodes
  user: "{{ USER }}"
  tasks:
   - name: Construct File Path on "{{ inventory_hostname }}".
     command: "touch {{ BASEPATH }}/{{ ( item | splitext)[1] }}/del.tmp"
     when: "{{ Layer == 'APP' }}"
     file: path="{{ "{{ inventory_hostname }}" }}/{{ App_List }}/{{ Rel_Path }}/del.tmp state=directory mode=u=rwx,g=rw,o=r"
     when: "{{ Layer == 'WAS' }}"

“ {{stock_hostname}}”替换为“ 10.9.12.112”,然后应进一步替换为包含的vars(“ was_vars.yaml”)文件中所述的“/was/IBM/WebSphere"。

我的当前代码出现以下语法错误:

ERROR! conflicting action statements: command, file

The error appears to be in '/app/Ansible/deploy.yml': line 133, column 4, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
   - name: Construct File Path on "{{ inventory_hostname }}".
     ^ here
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的最新版本。

你能建议吗?

3 个答案:

答案 0 :(得分:0)

1) file 模块前面没有破折号。

2)无法进行嵌套扩展(错误:"{{ "{{ inventory_hostname }}" }}")。

3)何时:条件默认为展开。

4)当包含一个变量的扩展名时,整个字符串应加引号。

5)扩展{{ ( item | splitext)[1] }}的索引不起作用。

6)不清楚变量 item 和过滤器 splitext 来自何处。

正确的语法可能是

 tasks:

   - name: "Construct File Path on {{ inventory_hostname }}."
     command: "touch {{ BASEPATH }}/{{ item|splitext|first }}/del.tmp"
     when: Layer == 'APP'

   - file:
       path: "{{ inventory_hostname }}/{{ App_List }}/{{ Rel_Path }}/del.tmp"
       state: directory
       mode: "u=rwx,g=rw,o=r"
     when: Layer == 'WAS'

(未经测试)

答案 1 :(得分:0)

谢谢您的投入,但我们实际上正在寻找的是如何使扩展生效...

也就是说,inventory_hostname将替换为主机ip,例如10.9.12.112 ...但是,我们该如何编码以从包含的变量文件中获取与IP匹配的“ / was / IBM / WebSphere”呢?

答案 2 :(得分:0)

您可以尝试:

"{{vars[inventory_hostname]}}"

或者如果您想再用作一个级别:

"{{vars[vars[inventory_hostname]]}}"