---
- name: Provision DigitalOcean cloud
  hosts: localhost
  vars:
    terraform_backend: "postgres://{{ skylab_tfstate_backend.username }}:{{ skylab_tfstate_backend.password }}@{{ skylab_tfstate_backend.hostname }}:{{ skylab_tfstate_backend.port }}/{{ skylab_tfstate_backend.schema }}"
  tasks:
  - name: Deploy terraform config
    block:
    - name: Create temp plan file
      changed_when: false
      ansible.builtin.tempfile:
        state: file
        prefix: skylab
        suffix: tfplan
      register: _tfplan_tempfile

    # Generating a plan file before yeeting a deployment into the
    # wind helps to ensure that the syntax is correct, backend and
    # state are valid, and all the plumbing is working as expected.
    # We don't want errors when we deploy, so it's better to
    # generate the plan first
    - name: Initialize terraform backend and generate plan file
      community.general.terraform:
        state: planned
        project_path: terraform/
        backend_config:
          conn_str: "{{ terraform_backend }}"
        force_init: true
        init_reconfigure: true
        plan_file: "{{ _tfplan_tempfile.path }}"

    # TODO: update to take DO token from invocation args rather than
    # implicit env var
    - name: Apply terraform plan
      community.general.terraform:
        state: present
        project_path: terraform/
        backend_config:
          conn_str: "{{ terraform_backend }}"
        plan_file: "{{ _tfplan_tempfile.path }}"
    always:
    - name: Remove temp plan file
      changed_when: false
      ansible.builtin.file:
        path: "{{ _tfplan_tempfile.path }}"
        state: absent
