2

I have following variable structure in Ansible (YAML format):

my_groups:
  - name: g1
    users:
      - name: foo
        param: rock
        junk: whatever

      - name: bar
        param: paper 
        junk: whatever

  - name: g2
    users:
      - name: baz
        param: scissors
        junk: whatever

And I need to transform it to flat array of users that looks like this (note the 1 in each name):

- name: foo1
  param: rock

- name: bar1
  param: paper 

- name: baz1
  param: scissors

I use Jinja filter json_query (which internally use JMESPath query language in Python) like this:

{{ my_groups|json_query( "[*].users[*].{ name: name, param: param }" ) }}

Which returns the array mentioned above but without the 1 in the name of course. Is there some way how to achieve the desired concatenation with a simple string? I tried some variants due to documentation and examples but with no luck i.e.:

{{ my_groups|json_query( "[*].users[*].{ name: name + '1', param: param }" ) }}

Simple Ansible playbook is available at pastebin

Vojta Myslivec
  • 140
  • 1
  • 1
  • 8

1 Answers1

8

JMESPath has join built-in to convert list into string.

- debug:
    msg: "{{ my_groups | json_query(qry) }}"
  vars:
    qry: "[*].users[*][].{ name: join('',[name,'1']), param: param }"

Also note [] after users[*] to flatten the list.

Result:

"msg": [
    {
        "name": "foo1",
        "param": "rock"
    },
    {
        "name": "bar1",
        "param": "paper"
    },
    {
        "name": "baz1",
        "param": "scissors"
    }
]
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Thanks! I have tried `join` function but i missed the trick with _empty join string_. – Vojta Myslivec Oct 04 '17 at 11:33
  • 1
    Anyone please note that there is some [bug](https://github.com/ansible/ansible/issues/27299) in recent Ansible version. You need to use `{{ my_groups | to_json | from_json | json_query(qry) }}` workaround. – Vojta Myslivec Oct 04 '17 at 11:38
  • Confirm Vojta's comment. Just adding `|to_json|from_json|` just before `json_query` fixes the issues with expected types – velis Jan 23 '20 at 07:18