2

The following joins a list of three strings:

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

The following doesn't work but illustrates what I want to do:

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

Here is the Python equivalent of what I want to do:

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

While it's easiest to test Jinja2 expressions in Python, I ultimately need my Jinja2 expression to work within an Ansible playbook, like the following Ansible snippets:

  - 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"]
clay
  • 18,138
  • 28
  • 107
  • 192

1 Answers1

0

You have to do this way

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

First, you join then you concat with the string

This give the result you expect

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"
}
Baptiste Mille-Mathias
  • 2,144
  • 4
  • 31
  • 37