我有以下Ansible任务:
tasks:
- name: ensure instances are running
ec2:
aws_access_key: "{{aws_access_key}}"
aws_secret_key: "{{aws_secret_key}}"
...
user_data: "{{ lookup('template', 'userdata.txt.j2') }}"
register: ec2_result
- debug:
msg: "{{ ec2_result }}"
- set_fact:
win_instance_id: "{{ ec2_result | json_query('tagged_instances[*].id') }}"
输出:
TASK [debug] ***************
ok: [localhost] => {
"msg": {
"changed": false,
"failed": false,
"instance_ids": null,
"instances": [],
"tagged_instances": [
{
"ami_launch_index": "0",
"architecture": "x86_64",
"block_device_mapping": {
"/dev/sda1": {
"delete_on_termination": true,
"status": "attached",
"volume_id": "vol-01f217e489c681211"
}
},
"dns_name": "",
"ebs_optimized": false,
"groups": {
"sg-c63822ac": "WinRM RDP"
},
"hypervisor": "xen",
"id": "i-019c03c3e3929f76e",
"image_id": "ami-3204995d",
...
"tags": {
"Name": "Student01 _ Jumphost"
},
"tenancy": "default",
"virtualization_type": "hvm"
}
]
}
}
TASK [set_fact] ****************
ok: [localhost]
TASK [debug] ******************
ok: [localhost] => {
"msg": "The Windows Instance ID is: [u'i-019c03c3e3929f76e']"
}
如您所见,实例ID是正确的,但格式不正确。有没有办法将此输出转换为"人类可读"输出?或者有没有更好的方法来解析ec2任务输出中的实例ID?
谢谢!
答案 0 :(得分:3)
它不是非人类可读格式,而是Python表示法中的列表对象,因为您查询列表。
如果你想要一个字符串,你应该通过first
过滤器传递它。
win_instance_id: "{{ ec2_result | json_query('tagged_instances[*].id') | first }}"
您也可以直接访问该值而不json_query
([0]
引用列表的第一个元素):
win_instance_id: "{{ ec2_result.tagged_instances[0].id }}"