2017-08-29 137 views
0

我试图从EC2创建AMI。但是,在这样做之前,我想检查是否存在具有相同名称的AMI。如果是这样,我想在尝试创建名称为AMI的AMI之前取消注册。用Ansible使用ec2_ami创建AMI

问题1:如果AMI已经存在,如何运行AMI取消注册。 问题2:取消注册呼叫时,如何在创建具有相同名称的AMI之前等待?

这里是我迄今为止

- name: Check if AMI with the same name exists 
    ec2_ami_find: 
    name: "{{ ami_name }}" 
    register: ami_find 

- name: Deregister AMI if it exists 
    ec2_ami: 
    image_id: "{{ ami_find.results[0].ami_id }}" 
    state: absent 
    when: ami_find.results[0].state == 'available' 

- pause: 
    minutes: 5 

- name: Creating the AMI from of the instance 
    ec2_ami: 
    instance_id: "{{ item.id }}" 
    wait: yes 
    name: "{{ ami_name }}" 
    delegate_to: 127.0.0.1 
    with_items: "{{ ec2.instances }}" 
    register: image 

编辑: 我试图创建新的AMI之前,我能够注销AMI时的状态为“可用”,等待几分钟(具有相同的名称)。但是,有时我会得到以下回应。在这种情况下,我想继续创建AMI。

TASK [createAMI : Check if AMI with the same name exists] ********************** 
ok: [local] => {"changed": false, "results": []} 
+1

你可以试试:'when:ami_find.results |长度和ami_find.results [0] .state =='available'' – helloV

+0

发布它作为答案。 – helloV

+0

谢谢。标记为有效的答案。谢谢你的帮助 – SSF

回答

1

首先检查结果是否为空,然后检查状态。

when: ami_find.results | length and ami_find.results[0].state == 'available' 
0

多亏了上述评论,我设法添加以下到注销任务和管理,以应对空响应。

- name: Check if AMI with the same name exists 
    ec2_ami_find: 
    name: "{{ ami_name }}" 
    register: ami_find 

- name: Deregister AMI if it exists 
    ec2_ami: 
    image_id: "{{ ami_find.results[0].ami_id }}" 
    state: absent 
    when: ami_find.results | length and ami_find.results[0].state == 'available'