---
- name: Launch instance(s)
  gce:
    instance_names: "{{ instances|join(',') }}"
    machine_type: "{{ gce_machine_type | default(deployment_vars[deployment_type].machine_type, true) }}"
    image: "{{ gce_machine_image | default(deployment_vars[deployment_type].image, true) }}"
    service_account_email: "{{ lookup('env', 'gce_service_account_email_address') }}"
    pem_file: "{{ lookup('env', 'gce_service_account_pem_file_path') }}"
    project_id: "{{ lookup('env', 'gce_project_id') }}"
    zone: "{{ lookup('env', 'zone') }}"
    network: "{{ lookup('env', 'network') }}"
    subnetwork: "{{ lookup('env', 'subnetwork') | default(omit, True) }}"
    # unsupported in 1.9.+
    #service_account_permissions: "datastore,logging-write"
    tags:
      - created-by-{{ lookup('env', 'LOGNAME') | regex_replace('[^a-z0-9]+', '') | default(cluster, true) }}
      - environment-{{ cluster_env }}
      - clusterid-{{ cluster_id }}
      - host-type-{{ type }}
      - sub-host-type-{{ g_sub_host_type }}
    metadata:
      startup-script: |
        #!/bin/bash
        echo "Defaults:{{ deployment_vars[deployment_type].ssh_user }} !requiretty" > /etc/sudoers.d/99-{{ deployment_vars[deployment_type].ssh_user }}

  when: instances |length > 0
  register: gce

- set_fact:
    node_label:
      # There doesn't seem to be a way to get the region directly, so parse it out of the zone.
      region: "{{ gce.zone | regex_replace('^(.*)-.*$', '\\\\1') }}"
      type: "{{ g_sub_host_type }}"
  when: instances |length > 0 and type == "node"

- set_fact:
    node_label:
      # There doesn't seem to be a way to get the region directly, so parse it out of the zone.
      region: "{{ gce.zone | regex_replace('^(.*)-.*$', '\\\\1') }}"
      type: "{{ type }}"
  when: instances |length > 0 and type != "node"

- name: Add new instances to groups and set variables needed
  add_host:
    hostname: "{{ item.name }}"
    ansible_ssh_host: "{{ item.public_ip }}"
    ansible_ssh_user: "{{ deployment_vars[deployment_type].ssh_user }}"
    ansible_become: "{{ deployment_vars[deployment_type].become }}"
    groups: "{{ item.tags | oo_prepend_strings_in_list('tag_') | join(',') }}"
    gce_public_ip: "{{ item.public_ip }}"
    gce_private_ip: "{{ item.private_ip }}"
    openshift_node_labels: "{{ node_label }}"
  with_items: "{{ gce.instance_data | default([], true) }}"

- name: Wait for ssh
  wait_for: port=22 host={{ item.public_ip }}
  with_items: "{{ gce.instance_data | default([], true) }}"

- name: Wait for user setup
  command: "ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ConnectTimeout=10 -o UserKnownHostsFile=/dev/null {{ hostvars[item.name].ansible_ssh_user }}@{{ item.public_ip }} echo {{ hostvars[item.name].ansible_ssh_user }} user is setup"
  register: result
  until: result.rc == 0
  retries: 30
  delay: 5
  with_items: "{{ gce.instance_data | default([], true) }}"
