Ansible无法解析JSON以将正确的UUID发送到poweron VM
制作API GET cal时,我会得到以下JSON结构:Ansible无法解析JSON以将正确的UUID发送到poweron VM,json,parsing,ansible,Json,Parsing,Ansible,制作API GET cal时,我会得到以下JSON结构: { "metadata": { "grand_total_entities": 231, "total_entities": 0, "count": 231 }, "entities": [ { "allow_live_migrate": true, "gpus_assigned": false, "ha_priority": 0, "memory_
{
"metadata": {
"grand_total_entities": 231,
"total_entities": 0,
"count": 231
},
"entities": [
{
"allow_live_migrate": true,
"gpus_assigned": false,
"ha_priority": 0,
"memory_mb": 1024,
"name": "test-ansible2",
"num_cores_per_vcpu": 2,
"num_vcpus": 1,
"power_state": "off",
"timezone": "UTC",
"uuid": "e1aff9d4-c834-4515-8c08-235d1674a47b",
"vm_features": {
"AGENT_VM": false
},
"vm_logical_timestamp": 1
},
{
"allow_live_migrate": true,
"gpus_assigned": false,
"ha_priority": 0,
"memory_mb": 1024,
"name": "test-ansible1",
"num_cores_per_vcpu": 1,
"num_vcpus": 1,
"power_state": "off",
"timezone": "UTC",
"uuid": "4b3b315e-f313-43bb-941b-03c298937b4d",
"vm_features": {
"AGENT_VM": false
},
"vm_logical_timestamp": 1
},
{
"allow_live_migrate": true,
"gpus_assigned": false,
"ha_priority": 0,
"memory_mb": 4096,
"name": "test",
"num_cores_per_vcpu": 1,
"num_vcpus": 2,
"power_state": "off",
"timezone": "UTC",
"uuid": "fbe9a1ac-cf45-4efa-9d65-b3257548a9f4",
"vm_features": {
"AGENT_VM": false
},
"vm_logical_timestamp": 17
},
]
}
在Ansible剧本中,我注册了一个包含此内容的变量。
我需要得到test-ansible1和test-ansible2的UUID列表,但我很难找到最好的方法。
请注意,我有另一个变量,其中包含需要查找UUID的名称列表
需要使用这些UUID为对应于特定名称的所有UUID启动poweron命令
你们会怎么做
我已经采取了很多方法,但我似乎无法得到我想要的,所以我更喜欢不受影响的意见
注:这是Nutanix AHV作为所有vms thgough API的一部分返回的内容。在我看来,似乎没有办法只获取特定的VMs JSON信息,而只能获取所有vm
谢谢。这是给你的金甲2魔法:
- debug:
msg: "{{ mynames | map('extract', dict(test_json | json_query('entities[].[name,uuid]'))) | list }}"
vars:
mynames:
- test-ansible1
- test-ansible2
说明:
test|json | json_query'entities[].[name,uuid]'将原始json数据缩减为元素列表,元素列表由两个项组成–name值和uuid值:
[
[
"test-ansible2",
"e1aff9d4-c834-4515-8c08-235d1674a47b"
],
[
"test-ansible1",
"4b3b315e-f313-43bb-941b-03c298937b4d"
],
[
"test",
"fbe9a1ac-cf45-4efa-9d65-b3257548a9f4"
]
]
顺便说一句,您可以使用它来测试查询语句
口述。。。当应用于此类结构时,touples列表将生成一个字典:
{
"test": "fbe9a1ac-cf45-4efa-9d65-b3257548a9f4",
"test-ansible1": "4b3b315e-f313-43bb-941b-03c298937b4d",
"test-ansible2": "e1aff9d4-c834-4515-8c08-235d1674a47b"
}
然后,我们应用提取过滤器作为只提取所需元素:
[
"4b3b315e-f313-43bb-941b-03c298937b4d",
"e1aff9d4-c834-4515-8c08-235d1674a47b"
]
谢谢你,康斯坦丁,这是非常有信息性的,我可以看出我要到达那里是多么困难。在您的帮助下,我可以很容易地获得touple列表,但当我应用提取过滤器时,它会错误地指出任务执行期间发生的异常。要查看完整的回溯,请使用-vvv。错误是:KeyError:u'names'致命:[localhost]:失败!=>{failed:true,msg:module execution期间发生意外故障,.stdout:}我使用的变量被称为names,而不是mynames,但内容与您的一样。