Complex string concatenation in jinja / ansible template

I have ansible dict that looks like this:

servers:
  - name: foo
    port: 1000
  - name: bar
    port: 2000

I want to create ansible / jinja2 template for this:

result=pre-foo-1000,pre-bar-1000

So far, I have something like:

result={{ servers | json_query('[*].name') | join(',') }}

but only outputs:

result=foo,bar

I tried something like json_query('[*].name-[*].port')without success - it gives errors regarding an invalid literal -. I cannot find many documents in json_query, but is there more there that I can do? Or the best option to slip into the filter?

+4
source share
1 answer

You can do a simple loop first and then collect the results:

- hosts: all
  connection: local
  vars:
    servers:
      - name: foo
        port: 1000
      - name: bar
        port: 2000
  tasks:
    - set_fact:
        result_item: '{{ item.name }}-{{ item.port }}'
      with_items:
        - '{{ servers }}'
      register: result_list

    - set_fact:
        result: '{{ result_list.results | map(attribute="ansible_facts.result_item") | join(",") }}'

    - debug:
        var: result

Alternatively try some jinja built-in loops:

- hosts: all
  connection: local
  vars:
    servers:
      - name: foo
        port: 1000
      - name: bar
        port: 2000
  tasks:
    - set_fact:
        result: "{% for item in servers %}{{item.name}}-{{item.port}}{{ '' if loop.last else ',' }}{% endfor %}"

    - debug:
        var: result

This should also work from the template file:

result={% for item in servers %}{{item.name}}-{{item.port}}{{ '' if loop.last else ',' }}{% endfor %}
+5

Source: https://habr.com/ru/post/1671899/


All Articles