---
- hosts: localhost
  connection: local
  gather_facts: yes
  vars:
    image_name: "worker-{{ DATA_BRANCH }}-{{ ansible_date_time.date }}"
  tasks:
    - debug: var=instance_id
    - debug: var=image_name
    - name: create image of current worker instance
      ec2_ami:
        instance_id: "{{ instance_id }}"
        name: "{{ image_name }}"
        region: us-west-2
        tags:
          Name: "{{ image_name }}"
          Environment: production
          Program: dsc
          Service: calisphere
          project: ucldc
          subproject: ingest
      register: image
    - debug: var=image

---
- hosts: localhost
  connection: local
  gather_facts: yes
  vars:
    image_name: "worker-{{ DATA_BRANCH }}-{{ ansible_date_time.date }}"
  tasks:
    - debug: var=instance_id
    - debug: var=image_name
    - name: create image of current worker instance
      ec2_ami:
        instance_id: "{{ instance_id }}"
        name: "{{ image_name }}"
        region: us-west-2
        tags:
          Name: "{{ image_name }}"
          Environment: production
          Program: dsc
          Service: calisphere
          project: ucldc
          subproject: ingest
      register: new_image
    - name: find older AMIs
      shell: "aws ec2 describe-images --filters Name=name,Values=worker-{{ DATA_BRANCH }}* | jq '.Images| sort_by(\"CreationDate\")[:length-1][].ImageId'"
      register: ami_ids
    - debug:
        msg: "Deleting amis : {{ ami_ids }}"
    - ec2_ami:
        region: "{{ region }}"
        image_id: "{{ item }}"
        delete_snapshot: True
        state: absent
      with_items:
        - "{{ ami_ids.stdout_lines | replace('\"', '')}}"
    - debug: var=new_image

Add removal of older AMIs
Add removal of older AMIs
