---
- name: create gcp ssh key
  command: ssh-keygen -f '{{ gcp_ssh_key }}' -t rsa -C cloud-user -N '' creates='{{ gcp_ssh_key }}'

- name: read public ssh key
  slurp:
    src: '{{ gcp_ssh_key }}.pub'
  register: public_ssh_key

- block:
  - name: get public keys in ssh agent
    command: ssh-add -L
    register: public_keys_in_agent
    changed_when: false

  - name: add gcp key to the key agent
    command: ssh-add '{{ gcp_ssh_key }}'
    when: public_ssh_key.content | b64decode | regex_replace('ssh-rsa (.*) cloud-user', '\\1') | trim not in public_keys_in_agent.stdout
  when: ansible_env.SSH_AUTH_SOCK is defined

- name: get current ssh keys in the gcp project
  command: gcloud --project {{ gcloud_project }} compute project-info describe --format='value(commonInstanceMetadata.items.key.sshKeys.value)'
  register: project_ssh_keys
  changed_when: false

- block:
  - name: create variable with our public key for gcp metadata, when there are no other public keys
    set_fact:
      ssh_public_key_metadata: 'cloud-user:{{ public_ssh_key.content | b64decode | trim }}'
    when: "'ssh-rsa' not in project_ssh_keys.stdout"

  - name: create variable with our public key for gcp metadata, when there are other public keys
    set_fact:
      ssh_public_key_metadata: "{{ project_ssh_keys.stdout }}\ncloud-user:{{ public_ssh_key.content | b64decode | trim }}"
    when: "'ssh-rsa' in project_ssh_keys.stdout"

  - name: add our ssh key to the project
    command: gcloud --project {{ gcloud_project }} compute project-info add-metadata --metadata='sshKeys={{ ssh_public_key_metadata }}'
  when: public_ssh_key.content | b64decode | regex_replace('ssh-rsa (.*) cloud-user', '\\1') | trim not in project_ssh_keys.stdout
