2

I need to convert the following yaml dictionary into comma-separated list of key=value pairs

nodes:
  node1: 192.168.56.11
  node2: 192.168.56.12

so it becomes

node1=192.168.56.11,node2=192.168.56.12

In Python I would do it with a simple list comprehension and then join the list:

','.join([ k+'='+v for k,v in nodes.items()])

I cannot figure out how to do it elegantly in an Ansible template, though. I can do it with for loop, of course, but it leaves the trailing comma. My best shot so far:

{% for k,v in nodes.items() %}{{k}}={{v}}{% if not loop.last %},{% endif %}{% endfor %}

Am I overlooking something?

badbishop
  • 1,281
  • 2
  • 18
  • 38

1 Answers1

5

The Ansible equivalent would be the below chaining of items() and joins. I added a second approach if you want them sorted by keys:

---
- hosts: localhost
  gather_facts: false
  vars:
    nodes:
      node3: 192.168.56.13
      node1: 192.168.56.11
      node4: 192.168.56.14
      node2: 192.168.56.12

  tasks:
  - name: print var
    debug:
      var: nodes.items()|map('join', '=')|join(',')

  - name: print var (items sorted)
    debug:
      var: nodes|dictsort|map('join', '=')|join(',')

Or, in a template:

{{nodes.items()|map("join", "=")|join(",")}}
badbishop
  • 1,281
  • 2
  • 18
  • 38
ilias-sp
  • 6,135
  • 4
  • 28
  • 41