---
- name: Require openshift_gcp_image
  fail:
    msg: "A source image name or family is required for image publishing.  Please ensure `openshift_gcp_image` is defined."
  when: openshift_gcp_image is undefined

- name: Require openshift_gcp_target_image
  fail:
    msg: "A target image name or family is required for image publishing.  Please ensure `openshift_gcp_target_image` is defined."
  when: openshift_gcp_target_image is undefined

- block:
  - name: Retrieve images in the {{ openshift_gcp_target_image }} family
    command: >
      gcloud --project "{{ openshift_gcp_project }}" compute images list
        "--filter=family={{ openshift_gcp_target_image }}"
        --format=json --sort-by ~creationTimestamp
    register: images
  - name: Prune oldest images
    command: >
      gcloud --project "{{ openshift_gcp_project }}" compute images delete "{{ item['name'] }}"
    with_items: "{{ (images.stdout | default('[]') | from_json )[( openshift_gcp_keep_images | int ):] }}"
  when: openshift_gcp_keep_images is defined

- name: Copy the latest image in the family {{ openshift_gcp_image }} to {{ openshift_gcp_target_image }}
  command: >
    gcloud --project "{{ openshift_gcp_target_project | default(openshift_gcp_project) }}"
      beta compute images create
      "{{ openshift_gcp_target_image_name | default(openshift_gcp_target_image + '-' + lookup('pipe','date +%Y%m%d-%H%M%S')) }}"
      --family "{{ openshift_gcp_target_image }}"
      --source-image-family "{{ openshift_gcp_image }}"
      --source-image-project "{{ openshift_gcp_project }}"
