Home > Mobile >  Ansible playbook get values from dict
Ansible playbook get values from dict

Time:10-14

I want to retrieve the id from a json dict based on a certain name. In this case I would like to get the ID from the "WebLogic" and store it into a variable to use the ID in a next task.

The playbook:

- name: Get Tags 
  uri:
      url: "https://xx.xx-xx.xx{{ uat_env }}api/config/v1/autoTags"
      method: GET
      headers:
        Content-Type: application/json; charset=utf-8
        Authorization: xxx
      return_content: yes  
  register: data
            
- name: Print returned json dictionary
  debug:
    var: data.json
       - debug:
    msg: "{{ data.json['values'] | json_query(query) }}"
  vars:
    name: 'WebLogic'
    query: "[?name=='{{ name }}'].id"
- name: TEST
  set_fact:
    test: "{{ data.json['values'] | json_query([?name=='WebLogic'].id) }}"
    

  

Test run:

PLAY [TEST] ********************************************************************
TASK [Get all UAT autoTags] ****************************************************
ok: [localhost]
TASK [Print returned json dictionary] ******************************************
ok: [localhost] => {
    "data.json": {
        "values": [
            {
                "id": "5c3849a4-a044-4a98-a67a-c1ea42d652ca",
                "name": "Apache"
            },
             
            {
                "id": "b37511f4-d4e8-4c77-a628-841dba5c65d8",
                "name": "WebLogic"
            }
        ]
    }
}
TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "b37511f4-d4e8-4c77-a628-841dba5c65d8"
    ]
}


TASK [TEST] ********************************************************************
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: unexpected char '?' at 37. String: {{ data.json['values'] | json_query([?name=='WebLogic'].id) }}"}


PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

The message returns empty.

CodePudding user response:

the problem is at the data.json.values syntax, please replace with data.json["values"]

the two tasks to show the difference:

  - debug:
      msg: "{{ data.json.values | json_query(query) }}"
    vars:
      name: 'WebLogic'
      query: "[?name=='{{ name }}'].id"

  - debug:
      msg: "{{ data.json['values'] | json_query(query) }}"
    vars:
      name: 'WebLogic'
      query: "[?name=='{{ name }}'].id"

update:

To assign the value to a variable, below task should do it:

  - set_fact:
      my_var: "{{ data.json['values'] | json_query(query) }}"
    vars:
      name: 'WebLogic'
      query: "[?name=='{{ name }}'].id"

  - debug:
      var: my_var
  • Related