2017-08-29 62 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'