Alagesan Palani
Alagesan Palani

Reputation: 2014

Extracting json object value in ansible

I want to extract a value from the following json object in Ansible:

"msg": {
       "NatGateway": {
           "CreateTime": "2016-10-03T17:46:07.548Z",
           "NatGatewayAddresses": [
               {
                   "AllocationId": "eipalloc-a22b9bc5"
               }
           ],
           "NatGatewayId": "nat-0d3b5a556c8a1c261",
           "State": "pending",
           "SubnetId": "subnet-5d353039",
           "VpcId": "vpc-eee3fe8a"
       }
   }
}

From the above json, I would like to extract only the value "0d3b5a556c8a1c261". How do I do that? I tried with regex, but so far no luck.

Upvotes: 3

Views: 10748

Answers (1)

Artem Gromov
Artem Gromov

Reputation: 124

If this json object was returned to you from a module, then you could use "register". There is an example using setup module:

- hosts: myhost
  gather_facts: false  # turn off automatic setup invocation for this example
  tasks:
    - name: my setup
      setup:
      register: myvar  # register setup module json output to variable

    - name: getting inside json structure for a string
      debug: msg="{{ myvar.ansible_facts.ansible_kernel }}"

    - name: using substring replacement
      debug: msg="{{ myvar.ansible_facts.ansible_kernel|replace('3.13.0-', '') }}"

    - name: using string slicing
      debug: msg="{{ myvar.ansible_facts.ansible_kernel[7:] }}"

The output would be:

[admin@agromov test]$ ansible-playbook book.yml 

PLAY [myhost] ******************************************************************

TASK [my setup] ****************************************************************
ok: [myhost]

TASK [getting inside json structure for a string] ******************************
ok: [myhost] => {
    "msg": "3.13.0-96-generic"
}

TASK [using substring replacement] *********************************************
ok: [myhost] => {
    "msg": "96-generic"
}

TASK [using string slicing] ****************************************************
ok: [myhost] => {
    "msg": "96-generic"
}

PLAY RECAP *********************************************************************
myhost                     : ok=4    changed=0    unreachable=0    failed=0   

Upvotes: 6

Related Questions