---
- name: create deployment {{ deployment_name_with_prefix }} config file
  template:
    src: '{{ deployment_config_template }}'
    dest: '{{ deployment_config }}'
  register: deployment_config_from_template

- name: check if deployment {{ deployment_name_with_prefix }} exists
  command: gcloud --project {{ gcloud_project }} deployment-manager deployments describe {{ deployment_name_with_prefix }} --format 'yaml(deployment.operation)'
  register: deployment_exists
  changed_when: false
  ignore_errors: true

- name: delete deployment if it exists in failed state
  include_role:
    name: deployment-delete
  when:
  - deployment_exists | succeeded
  - (deployment_exists.stdout | from_yaml).deployment.operation.error is defined

- name: create deployment {{ deployment_name_with_prefix }}
  command: gcloud --project {{ gcloud_project }} deployment-manager deployments create {{ deployment_name_with_prefix }} --config '{{ deployment_config }}'
  when: deployment_exists | failed or (deployment_exists.stdout | from_yaml).deployment.operation.error is defined

- name: update deployment {{ deployment_name_with_prefix }}
  command: gcloud --project {{ gcloud_project }} deployment-manager deployments update {{ deployment_name_with_prefix }} --config '{{ deployment_config }}'
  when:
  - deployment_exists | succeeded
  - deployment_config_from_template | changed
