在 Ansible 中尝试解析命令的结果时,我遇到了同样的挑战。
所以结果是:
{
"changed": true,
"instance_ids": [
"i-0a243240353e84829"
],
"instances": [
{
"id": "i-0a243240353e84829",
"state": "running",
"hypervisor": "xen",
"tags": {
"Backup": "FES",
"Department": "Research"
},
"tenancy": "default"
}
],
"tagged_instances": [],
"_ansible_no_log": false
}
我想将state 的值解析到ansible playbook 中的result 寄存器中。
我是这样做的:
由于结果是散列数组的散列,即 state 在 instances 数组的索引 (0) 散列中,因此我将我的剧本修改为如下所示:
---
- name: Manage AWS EC2 instance
hosts: localhost
connection: local
# gather_facts: false
tasks:
- name: AWS EC2 Instance Restart
ec2:
instance_ids: '{{ instance_id }}'
region: '{{ aws_region }}'
state: restarted
wait: True
register: result
- name: Show result of task
debug:
var: result.instances.0.state
我使用register 将命令的值保存在名为result 的变量中,然后使用以下方法在变量中获取state 的值:
result.instances.0.state
这次运行命令,我得到的结果是:
TASK [Show result of task] *****************************************************
ok: [localhost] => {
"result.instances.0.state": "running"
}
就是这样。
我希望这会有所帮助