SSF
SSF

Reputation: 983

Creating AMI using ec2_ami with Ansible

I am trying to create an AMI from an EC2. However, before doing so I would like to check if the AMI with the same name exists. If it does, I would like to deregister it before attempting to create the AMI with the given name.

Issue1: How do I run AMI deregister ONLY if the AMI already exists. Issue2: When the deregister call has been madem, how do I wait for before creating the AMI with the same name?

Here is what I have so far

- 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

EDIT: I am able to deregister the AMI when the state is 'available' and wait for a few minutes before attempting to create the new AMI (which has the same name). However, sometimes I get the following response. In which case I would like to continue with creating AMI.

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

Upvotes: 1

Views: 2099

Answers (2)

helloV
helloV

Reputation: 52393

First check if the result is not empty and then check the state.

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

Upvotes: 2

SSF
SSF

Reputation: 983

Thanks to the comment above, I managed to add the following to the Deregister task and managed to deal with the empty response.

- 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'

Upvotes: 0

Related Questions