---
- name: check for service account
  command: gcloud --project {{ gcloud_project }} iam service-accounts list --filter {{ service_account }}
  register: service_account_output
  changed_when: false

- name: create new service account
  command: gcloud --project {{ gcloud_project }} iam service-accounts create {{ service_account }} --display-name '{{ service_account_name }}'
  register: service_account_created
  when: service_account not in service_account_output.stdout

- name: create service account key
  command: gcloud --project {{ gcloud_project }} iam service-accounts keys create {{ inventory_dir }}/gce/hosts/project.json --iam-account {{ service_account_id }} creates={{ inventory_dir }}/gce/hosts/project.json

- name: grant service account access to the gcp project
  command: gcloud --project {{ gcloud_project }} projects add-iam-policy-binding {{ gcloud_project }} --member serviceAccount:{{ service_account_id }} --role roles/editor
  when: service_account_created | changed

- name: create secrets file
  copy:
    dest: '{{ inventory_dir }}/gce/hosts/secrets.py'
    content: |
      GCE_PARAMS = ('{{ service_account_id }}', '{{ inventory_dir }}/gce/hosts/project.json')
      GCE_KEYWORD_PARAMS = {'project': '{{ gcloud_project }}', 'datacenter': '{{ gcloud_region }}'}
