Proxmox OIDC integration and terragrunt hooks (Day 36)

Proxmox OIDC integration and terragrunt hooks (Day 36)
Photo by Lucas Chizzali / Unsplash

Turns out the Telmate Proxmox provider doesn't have resource support for creating authentication realms or configuring OIDC.

But since Proxmox has a REST API, I could work around the provider limitations, and so I ended up with:

terraform {
  source = "."

  after_hook "create_realm" {
    commands = ["apply"]
    execute = ["bash", "-c", <<-BASH
        # Proxmox returns a 500 if the user doesn't exist, anyway just check for 200
        STATUS=$(curl -k -s -o /dev/null -w "%%{http_code}" \
        "${local.pm_api_url}/access/domains/authentik" \
        -H "Authorization: PVEAPIToken=${local.pm_api_token_id}=${local.pm_api_token_secret}")
        
        if [ "$STATUS" = "200" ]; then
            echo "Realm 'authentik' already exists"
        else
            echo "Creating realm 'authentik'"
            curl -k -X POST "${local.pm_api_url}/access/domains" \
                -H "Authorization: PVEAPIToken=${local.pm_api_token_id}=${local.pm_api_token_secret}" \
                -H "Content-Type: application/x-www-form-urlencoded" \
                --data-urlencode "realm=authentik" \
                --data-urlencode "type=openid" \
                --data-urlencode "issuer-url=${local.issuerurl}" \
                --data-urlencode "client-id=${dependency.authentik.outputs.client_id["prx-avalon"]}" \
                --data-urlencode "client-key=${dependency.authentik.outputs.client_secret["prx-avalon"]}" \
                --data-urlencode "username-claim=username" \
                --data-urlencode "autocreate=1" \
                --data-urlencode "default=1"
        fi
    BASH
    ]
  }

  before_hook "delete_realm" {
    commands = ["destroy"]
    execute = ["bash", "-c", <<-BASH
      curl -k -X DELETE "${local.pm_api_url}/access/domains/authentik" \
        -H "Authorization: PVEAPIToken=${local.pm_api_token_id}=${local.pm_api_token_secret}"
    BASH
    ]
  }
}

The after_hook runs after apply and creates the OIDC realm in Proxmox if it doesn't exist.

The before_hook cleans it up on destroy. The client ID and secret come from the Authentik module outputs, which keep everything connected.

It's not pretty, but it works.