我想从 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”。我怎么做?我尝试使用正则表达式,但到目前为止运气不好。
最佳答案
如果这个 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
关于json - 在ansible中提取json对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39844374/