kiros123321
kiros123321

Reputation: 67

Ansible: json filtering

ill have a role playbook which get json from gitlab

---
- name: Make an API call
  uri:
    method: GET
    url: "https://gitlab.example.com/api/v4/projects/***/repository/files/Dev/raw?ref=master"
    headers:
      PRIVATE-TOKEN: **************
  register: json_var

- name: show json
  debug:
    msg: "{{json_var}}"

- name: test
  debug:
    var: json_var.json.plannedrelease
  register: release

- name: debug
  debug:
    msg: "{{ release }}"

but cant get json value to variable, i need only version "1.0" in variable release (from "plannedrelease" : "1.0"), how can i filter it?

Playbook output is:

PLAY [127.0.0.1] ***************************************************************
TASK [Gathering Facts] *********************************************************
ok: [127.0.0.1]
TASK [get_contour_version : Make an API call] **********************************
ok: [127.0.0.1]
TASK [get_contour_version : show json] *****************************************
ok: [127.0.0.1] => {
    "msg": {
        "cache_control": "max-age=0, private, must-revalidate, no-store, no-cache", 
        "changed": false, 
        "connection": "close", 
        "content_disposition": "inline; filename=\"Dev\"; filename*=UTF-8''Dev", 
        "content_length": "402", 
        "content_type": "text/plain; charset=utf-8", 
        "cookies": {}, 
        "cookies_string": "", 
        "date": "Tue, 19 Jan 2021 19:42:33 GMT", 
        "elapsed": 0, 
        "expires": "Fri, 01 Jan 1990 00:00:00 GMT", 
        "failed": false, 
        "json": {
            "Created": "12/06/2020 10:11", 
            "Key": "123", 
            "Updated": "01/12/2020 11:51", 
            "contour": "Dev", 
            "plannedrelease": "1.0", 
            "…
TASK [get_contour_version : test] **********************************************
ok: [127.0.0.1] => {
    "json_var.json.plannedrelease": "1.0"
}
TASK [get_contour_version : debug] *********************************************
ok: [127.0.0.1] => {
    "msg": {
        "changed": false, 
        "failed": false, 
        "json_var.json.plannedrelease": "1.0"
    }
}
PLAY RECAP *********************************************************************
127.0.0.1                  : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

probably i used wrong method for filtering

Upvotes: 1

Views: 52

Answers (1)

Stephan Kulla
Stephan Kulla

Reputation: 5067

Have you tried https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html ? Reading the documentation the following might work:

- name: Save release var
  set_fact:
    release: "{{ json_var.json.plannedrelease }}"

Upvotes: 1

Related Questions