Amazon web services AWS AMI清理w/Ansible遍历结果数组
我有一个以前的任务,创建每周备份,用服务器名称和日期/时间标记对其进行标记。这项工作的目标是深入到它背后,清理旧的AMI备份,只留下最后3个。Amazon web services AWS AMI清理w/Ansible遍历结果数组,amazon-web-services,ansible,Amazon Web Services,Ansible,我有一个以前的任务,创建每周备份,用服务器名称和日期/时间标记对其进行标记。这项工作的目标是深入到它背后,清理旧的AMI备份,只留下最后3个。ec2\u ami\u find任务工作正常,但它也可能为某些服务器返回空结果,我希望注销任务能够处理这个问题 我得到的错误非常普遍: 致命:[127.0.0.1]:失败!=>{ “失败”:对, “msg”:“条件检查”项.ec2\u ami\u find.exists失败。错误为:计算条件时出错 (item.ec2\u ami\u find.exists
ec2\u ami\u find
任务工作正常,但它也可能为某些服务器返回空结果,我希望注销任务能够处理这个问题
我得到的错误非常普遍:
致命:[127.0.0.1]:失败!=>{
“失败”:对,
“msg”:“条件检查”项.ec2\u ami\u find.exists失败。错误为:计算条件时出错
(item.ec2\u ami\u find.exists):“dict对象”没有属性
“ec2\u ami\u find”\n\n错误似乎已出现
“/root/ansible/ec2 backups purge/roles/first_acct/tasks/main.yml”:第25行,
第3列,但可能\n位于文件的其他位置,具体取决于
语法问题。\n\n出现问题的行是:\n\n\n-name:
注销旧备份\n^此处\n“
playbook任务内容如下:
---
- name: Find old backups
tags: always
ec2_ami_find:
owner: self
aws_access_key: "{{ access_key }}"
aws_secret_key: "{{ secret_key }}"
region: "{{ aws_region }}"
ami_tags:
Name: "{{ item }}-weekly-*"
sort: name
sort_order: descending
sort_start: 3
with_items:
- server-01
- server-02
- server-win-01
- downloads
register: stale_amis
- name: Deregister old backups
tags: always
ec2_ami:
aws_access_key: "{{ access_key }}"
aws_secret_key: "{{ secret_key }}"
region: "{{ aws_region }}"
image_id: "{{ item.ami_id }}"
delete_snapshot: True
state: absent
with_items:
- "{{ stale_amis.results }}"
其中一个结果的片段返回:
"results": [
{
"ami_id": "ami-zzzzzzz",
"architecture": "x86_64",
"block_device_mapping": {
"/dev/xvda": {
"delete_on_termination": true,
"encrypted": false,
"size": 200,
"snapshot_id": "snap-xxxxxxxxxxxxx",
"volume_type": "gp2"
}
},
"creationDate": "2017-08-01T15:26:11.000Z",
"description": "Weekly backup via Ansible",
"hypervisor": "xen",
"is_public": false,
"location": "111111111111/server-01.example.com-20170801152611Z",
"name": "server-01.example.com-20170801152611Z",
"owner_id": "111111111111",
"platform": null,
"root_device_name": "/dev/xvda",
"root_device_type": "ebs",
"state": "available",
"tags": {
"Name": "server-01-weekly-20170801152611Z",
"Type": "weekly"
},
"virtualization_type": "hvm"
},
我怀疑你的企图:
with_items:
- "{{ stale_amis.results }}"
因为ec2\u ami\u find
将结果放入自己的results
字段。所以第一台服务器的第一个ami将是stale\u amis.results[0]。results[0]。ami\u id
我建议将原始的stale\u amis
减少到所需列表,并在其上循环。例如,您可以使用json\u query
过滤器:
- ec2_ami:
aws_access_key: "{{ access_key }}"
aws_secret_key: "{{ secret_key }}"
region: "{{ aws_region }}"
image_id: "{{ item }}"
delete_snapshot: True
state: absent
with_items: "{{ stale_amis | json_query('results[].results[].ami_id') }}"
这工作得很好,谢谢!请注意,其他人必须安装程序包
python2 jmespath