Jinja2字符串追加?

时间:2018-08-10 12:03:14

标签: ansible jinja2

以下连接了三个字符串的列表:

> Template('Hello {{ my_list | join(", ") }}!').render(my_list=['a', 'b', 'c'])
'Hello a, b, c!'

以下内容不起作用,但说明了我想做什么:

Template('Hello {{ my_list | append(":8080") | join(", ") }}!').render(my_list=['a', 'b', 'c'])

这是我想做的Python等效项:

", ".join([x + ":8080" for x in ['a', 'b', 'c']])

虽然最简单的方法是在Python中测试Jinja2表达式,但我最终还是需要我的Jinja2表达式才能在Ansible剧本中正常工作,例如以下Ansible片段:

  - name: "join without append"
    debug: msg="test={{ item | join(',') }}"
    with_items:
      - ["a", "b", "c"]

  - name: "this doesn't work"
    debug: msg="test={{ (item + ':8080') | join(',') }}"
    with_items:
      - ["a", "b", "c"]

1 个答案:

答案 0 :(得分:0)

您必须这样做

- hosts: localhost
  gather_facts: no
  tasks:
      - name: "this does work"
        debug:
          msg: "test={{ (item | join(',')) + ':8000'  }}"
        with_items:
          - ["a", "b", "c"]

首先,您加入,然后使用字符串concat

这给您期望的结果

PLAY [localhost] ******************************************************

TASK [this does work] *************************************************
ok: [localhost] => (item=None) => {
    "msg": "test=a:8000"
}
ok: [localhost] => (item=None) => {
    "msg": "test=b:8000"
}
ok: [localhost] => (item=None) => {
    "msg": "test=c:8000"
}