0

我正在编写 Ansible 剧本,在模板中我需要替换一个变量,该变量是字典列表。

任务文件如下:

vars:
locations:
  - context: "/rest"
    server: "http://locahost:8080;"
  - context: "/api"
    server: "http://localhost:9090;"
tasks:
- name: testing the template
  template:
    src: ./conf.j2
    dest: /tmp/test.conf
  with_items: '{{ locations }}'

我需要替换locations模板中的。所以模板如下:

{% for location in item %}
     location {{ location['context'] }}
     proxy_pass {{ location['server'] }}
{% endfor %} 

我期待的输出如下:

location /rest
proxy_pass http://localhost:8080

location /api
proxy_pass htpp://localhost:9090

但是我很难让替换正确,任何人都可以帮助指出我在哪里犯了错误。

我得到的错误是

failed: [127.0.0.1] (item={u'context': u'/rest', u'server': 
u'http://localhost:9090;'}) => {"failed": true, "item": {"context": 
"/rest", "server": "http://localhost:8080;"}, "msg": 
"AnsibleUndefinedVariable: 'context' is undefined"}
failed: [127.0.0.1] (item={u'context': u'/api', u'server': 
u'http://locahost:8080;'}) => {"failed": true, "item": {"context": 
"/api", "server": "http://locahost:9090;"}, "msg": 
"AnsibleUndefinedVariable: 'context' is undefined"}
4

1 回答 1

1

此时,由于with_items,您正在传递列表的各个元素locations,因此在第一次迭代中,item变为以下字典:

context: "/rest"
server: "http://locahost:8080;"

然后在模板中,您尝试将此字典迭代为列表(使用for)。


您需要决定是要在模板外循环(创建多个文件)还是在模板内循环(创建单个文件)。

你的情况看起来像后者,所以你不需要使用with_items

- name: testing the template 
  template:
    src: ./conf.j2
    dest: /tmp/test.conf 

使用模板:

{% for location in locations %}
  location {{ location['context'] }}
  proxy_pass {{ location['server'] }}
{% endfor %} 

您忽略了我关于预期输出末尾缺少分号的问题,因此请自行处理。

于 2017-06-06T04:41:06.233 回答