- name: Create infrastructure
  hosts: localhost
  gather_facts: false

  vars_files:
    - vars/main.yml

  environment:
    GOOGLE_PROJECT: "{{ gcp_project }}"
    GOOGLE_REGION: "us-east-1"
    GOOGLE_CREDENTIALS: "{{ gcp_cred_file }}"

  tasks:
    # Create The storage bucket acting as Terraform remote backend
    - name: Create a Storage bucket
      google.cloud.gcp_storage_bucket:
        name: "{{ gcp_storage_bucket_name }}"
        storage_class: STANDARD
        project: "{{ gcp_project }}"
        auth_kind: "{{ gcp_cred_kind }}"
        service_account_file: "{{ gcp_cred_file }}"

    # Create GCP instance
    - block:
        - name: Create temporary dir
          ansible.builtin.tempfile:
            state: directory
          register: terraform_dir

        - name: Generate Terraform configuration
          ansible.builtin.template:
            src: main.tf.j2
            dest: "{{ terraform_dir.path }}/main.tf"

        - name: Create infrastructure using Terraform configuration
          cloud.terraform.terraform:
            project_path: "{{ terraform_dir.path }}"
            force_init: true
            variables:
              instance_name: "{{ gcp_instance_name }}"

      always:
        - name: Delete temporary directory
          ansible.builtin.file:
            state: absent
            path: "{{ terraform_dir.path }}"

    # Generate inventory file
    - name: Generate inventory file
      ansible.builtin.template:
        src: inventory.yml.j2
        dest: "{{ inventory_file_path }}"

    # Generate credentials file
    - name: Generate GCP credentials file
      ansible.builtin.template:
        src: gcp_credentials.sh.j2
        dest: gcp_credentials.sh
