---
- 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: Capture Terraform output
      ansible.builtin.command:
        cmd: terraform output -json
        chdir: "{{ terraform_directory }}"
      register: terraform_output_result
      changed_when: false

    - name: Parse Terraform output for IP addresses
      set_fact:
        terraform_ips: "{{ terraform_output_result.stdout | from_json | dict2items | selectattr('key', 'match', '.*_ip') | map(attribute='value.value') | list }}"

    - name: Add Terraform IPs to inventory
      add_host:
        name: "{{ item }}"
        groups: terraform_hosts
      loop: "{{ terraform_ips }}"

    - name: Display the dynamic inventory
      debug:
        msg: "Added the following IPs to the 'terraform_hosts' group: {{ terraform_ips }}"

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