在ansible中提取json对象值

时间:2016-10-04 04:51:34

标签: json ansible

我想从Ansible中的以下json对象中提取一个值:

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

从上面的json中,我想只提取值“0d3b5a556c8a1c261”。我怎么做?我尝试使用正则表达式,但到目前为止还没有运气。

1 个答案:

答案 0 :(得分:4)

如果这个json对象是从模块返回给你的,那么你可以使用“register”。有一个使用安装模块的例子:

- 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:] }}"

输出结果为:

[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   
相关问题