【问题标题】:Value substitution in Ansible templateAnsible 模板中的值替换
【发布时间】:2017-06-06 03:15:13
【问题描述】:

我正在编写 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"}

【问题讨论】:

  • 你在标题和第一段中提到的“替代”到底在哪里?我在这里看不到任何替代品。另外,您会得到什么结果以及预期结果中的分号发生了什么?
  • 很抱歉造成混淆,替换在模板中。我期待问题中提到的输出,在多次调整代码后我没有得到正确的输出。要么我在执行中遇到错误,要么值没有在模板中被替换
  • 根据 SO 规则,您应该发布确切的错误消息或描述。在这种形式下,问题应该被关闭。
  • 我已经更新了问题,但出现了错误。

标签: ansible ansible-2.x ansible-template


【解决方案1】:

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

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

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


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

你的case好像是后者,所以不用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 %} 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 2021-07-11
    • 2022-11-04
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2018-01-16
    相关资源
    最近更新 更多