1

I have below registered variable output. And I am trying to get the unique tagIds from this output.

Ansible Version: 2.9.6

   "results": [
        {
            "json": [
                {
                    "tags": [
                        {
                            "tagId": 123
                        },
                        {
                            "tagId": 1014
                        }
                    ]
                }
            ]
        },
        {
            "json": [
                {
                    "adp_release": "xxxxxx",
                    "tags": [
                        {
                            "tagId": 111
                        },
                        {
                            "tagId": 1014
                        }
                    ]
                }
            ]
        }
    ]

Trying with the below code: This is only retuning the last element tags from the results list. Incremental update for loop in set_fact not working.

          - name: get all tags
            set_fact: alltags={{ item.json[0]['tags'] | map(attribute='tagId') | list |unique }}
            with_items: "{{ results }}"

          - debug: var=alltags

How to get a combined list of values?

SNR
  • 460
  • 5
  • 20

1 Answers1

1

Q: "Get the unique tagId(s)."

A: For example, use json_query

alltags: "{{ results|json_query('[].json[].tags[].tagId')|unique }}"

gives

alltags:
  - 123
  - 1014
  - 111

The next option is the mapping of the attributes. For example, the expression below gives the same result

alltags: "{{ results|map(attribute='json')|flatten|
                     map(attribute='tags')|flatten|
                     map(attribute='tagId')|list|unique }}"

Example of a complete playbook

- hosts: localhost

  vars:

    results:
      - json:
        - tags:
            - tagId: 123
            - tagId: 1014
      - json:
        - adp_release: xxxxxx
          tags:
            - tagId: 111
            - tagId: 1014

    alltags: "{{ results|json_query('[].json[].tags[].tagId')|unique }}"

  tasks:

    - debug:
        var: alltags
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Is there a way to do the same without `json_query`? I cant install `jamespath` module. – SNR Jul 26 '22 at 13:25
  • Yes. You can map attributes. I added the example. – Vladimir Botka Jul 26 '22 at 13:32
  • getting error with mapping `failure using method (v2_runner_on_ok) in callback plugin (): Object of type set is not JSON serializable` – SNR Jul 26 '22 at 14:35
  • `{{ results|map(attribute='json')|flatten|map(attribute='tags')|flatten|map(attribute='tagId')|list|unique }}` adding `list` at end worked. Thanks a lot. – SNR Jul 26 '22 at 14:47