---
- name: Check if the encrypted image already exist
  ec2_ami_facts:
    aws_access_key: "{{ access_key }}"
    aws_secret_key: "{{ secret_key }}"
    owners: self
    region: "{{ algo_region }}"
    filters:
      state: available
      "tag:Algo": encrypted
  register: search_crypt

- name: Copy to an encrypted image
  ec2_ami_copy:
    aws_access_key: "{{ access_key }}"
    aws_secret_key: "{{ secret_key }}"
    encrypted: yes
    name: algo
    kms_key_id: "{{ kms_key_id | default(omit) }}"
    region: "{{ algo_region }}"
    source_image_id: "{{ (ami_search.images | sort(attribute='creation_date') | last)['image_id'] }}"
    source_region: "{{ algo_region }}"
    wait: true
    tags:
      Algo: "encrypted"
  register: ami_search_encrypted
  when: search_crypt.images|length|int == 0
