---
- name: Create molecule Windows instance(s)
  google.cloud.gcp_compute_instance:
    state: present
    name: "{{ item.name }}"
    machine_type: "{{ item.machine_type | default('n1-standard-1') }}"
    disks:
      - auto_delete: true
        boot: true
        initialize_params:
          disk_size_gb: "{{ item.disk_size_gb | default(omit) }}"
          source_image: "{{ item.image | default('projects/windows-cloud/global/images/family/windows-2019') }}"
          source_image_encryption_key:
            raw_key: "{{ item.image_encryption_key | default(omit) }}"
    network_interfaces:
      "{{ [ { 'network': my_network.resources.0 | default(omit), 'subnetwork': my_subnetwork.resources.0 | default(omit) } | combine(external_access_config
      | default([])) ] }}"
    zone: "{{ item.zone | default(molecule_yml.driver.region + '-b') }}"
    project: "{{ gcp_project_id }}"
    scopes: "{{ molecule_yml.driver.scopes | default(['https://www.googleapis.com/auth/compute'], True) }}"
    service_account_email: "{{ molecule_yml.driver.service_account_email | default(omit, true) }}"
    service_account_file: "{{ molecule_yml.driver.service_account_file | default(omit, true) }}"
    auth_kind: "{{ molecule_yml.driver.auth_kind | default(omit, true) }}"
  register: async_results
  loop: "{{ molecule_yml.platforms }}"
  async: 7200
  poll: 0

- name: Wait for instance(s) creation to complete
  ansible.builtin.async_status:
    jid: "{{ item.ansible_job_id }}"
  loop: "{{ async_results.results }}"
  register: server
  until: server.finished
  retries: 300
  delay: 10
  notify:
    - Populate instance config dict Windows
    - Convert instance config dict to a list
    - Dump instance config

- name: Wait for WinRM
  ansible.builtin.wait_for:
    port: 5986
    host: "{{ item.networkInterfaces.0.accessConfigs.0.natIP if molecule_yml.driver.external_access else item.networkInterfaces.0.networkIP }}"
    delay: 10
  loop: "{{ server.results }}"

- name: Prepare Windows User
  ansible.builtin.script:
    ./files/windows_auth.py --instance {{ item.name }} --zone {{ item.zone | default(molecule_yml.driver.region + '-b') }} --project {{ gcp_project_id
    }} --username molecule_usr
  args:
    executable: python3
  loop: "{{ molecule_yml.platforms }}"
  changed_when:
    - password.rc == 0
    - password.stdout
  register: password
  retries: 10
  delay: 10

- name: Add password for instances in server list
  ansible.builtin.set_fact:
    win_instances: "{{ win_instances | default([]) + [dict(item[0], password=item[1].stdout_lines | last)] }}"
  loop: "{{ server.results | zip(password.results) | list }}"
  no_log: true
