Ansible get unique value in loop for register

Viewed 196

Hi friend below is my sample output from a regsiter name dataInfo

ok: [123.23.44.123] => {
    "msg": [ 
        {
            "changed": true,  
            "item": [
                {
                    "artifactName": "helloWorld.jar", 
                    "status": "false" 
                }, 
                "myGroup1"
            ], 
            "rc": 0,
            "stderr_lines": [], 
            "stdout": "ok", 
            "stdout_lines": [
                "ok"
            ]
        },
        {
            "changed": true,  
            "item": [
                {
                    "artifactName": "helloWorld.jar", 
                    "status": "false" 
                }, 
                "myGroup2"
            ], 
            "rc": 0,
            "stderr_lines": [], 
            "stdout": "ok", 
            "stdout_lines": [
                "ok"
            ]
        }

Below is my code

- name: My ArtifactName Name
  debug:
    msg: "artifactName = {{ item.item[0].artifactName }}"
  loop: "{{ dataInfo.results }}"
  when: item.changed | bool == true and item.stdout == "ok"

How can i only display as below

artifactName = helloWorld.jar

rather than

artifactName = helloWorld.jar
artifactName = helloWorld.jar

I have shared my code as shown above. Please advice

1 Answers

As you are looping with dataInfo.results, the debug message will repeat for each "item". If you only want unique artifactName, then you can save it to a variable using json_query and choose to display only unique ones.

Something like this:

    # Save list of artifactName found in dataInfo.results even with duplicates
    - name: save artifact names
      set_fact:
        artifact_names: "{{ artifact_names | default([]) + [ item | json_query('item[].artifactName') ] }}"
      loop: "{{ dataInfo.results }}"
    # Show each item of artifact_names using unique filter to eliminate duplicates
    - name: show unique artifact names
      debug:
        var: item
      loop: "{{ artifact_names | flatten | unique }}"

Update:

Below set_fact:

artifact_names: "{{ artifact_names | default([]) + [ item.item[0].artifactName ] }}"

... will work if you get only 1 hash in item like this:

            "item": [
                {
                    "artifactName": "helloWorld.jar", 
                    "status": "false" 
                }, 
            ], 

But if it may have multiple hashes like below, it won't work:

            "item": [
                {
                    "artifactName": "helloWorld.jar", 
                    "status": "false" 
                }, 
                {
                    "artifactName": "someother.jar", 
                    "status": "false" 
                },
                ...
            ], 

If this is a possibility, then json_query should be used. It can be used exactly like the jq command.

Related