具有Ansible的AWS AMI清理迭代结果数组

时间:2017-09-13 16:04:50

标签: amazon-web-services ansible

我之前的任务是创建每周备份,并使用服务器名称后跟日期/时间标记对其进行标记。这项工作的目标是进入后面并清理旧的AMI备份,只留下最后的3. ec2_ami_find任务正常,但它也可能返回一些服务器的空结果,我想处理该问题的注销任务。

我得到的错误非常通用:

  

致命:[127.0.0.1]:失败! => {       “失败”:是的,       “msg”:“条件检查'item.ec2_ami_find.exists'失败。错误是:评估条件时出错   (item.ec2_ami_find.exists):'dict object'没有属性   'ec2_ami_find'\ n \ n错误似乎已经出现了   '/root/ansible/ec2-backups-purge/roles/first_acct/tasks/main.yml':第25行,   第3列,但可能在文件的其他位置,具体取决于具体情况   语法问题。\ n \ n违规行似乎是:\ n \ n \ n-名称:   取消注册旧备份\ n ^ here \ n“

剧本任务内容如下:

---
- 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"
    },

1 个答案:

答案 0 :(得分:2)

我怀疑你的尝试:

  with_items:
    - "{{ stale_amis.results }}"

因为ec2_ami_find将结果放入自己的results字段中。因此,第一台服务器的第一个AMI将是stale_amis.results[0].results[0].ami_id

我建议将原始stale_amis缩减为必需列表并将其循环。例如,您可以使用json_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') }}"