---
- name: Apply Terraform
  hosts: localhost
  vars:
    terraform_directory: "../../terraform"
  
  tasks:
    - name: Decrypt secrets from Ansible Vault
      ansible.builtin.include_vars:
        file: "vault.yml"  # Path to your Ansible Vault file
        name: vault_secrets

    - name: Write secrets to a temporary Terraform variables file
      ansible.builtin.template:
        src: terraform_vars.j2
        dest: "{{ terraform_directory }}/terraform.tfvars"
      vars:
        terraform_secrets: "{{ vault_secrets }}"

    - name: Initialize Terraform
      ansible.builtin.command:
        cmd: terraform init
        chdir: "{{ terraform_directory }}"
      register: terraform_init_result
      changed_when: "'Terraform has been successfully initialized!' in terraform_init_result.stdout"

    - name: Apply Terraform configuration
      ansible.builtin.command:
        cmd: terraform apply -auto-approve
        chdir: "{{ terraform_directory }}"
      register: terraform_apply_result
      changed_when: "'Apply complete!' in terraform_apply_result.stdout"

    - name: Clean up temporary files
      ansible.builtin.file:
        path: "{{ terraform_directory }}/terraform.tfvars"
        state: absent