feat: manage Grafana Authentik SSO
Homelab Main / validate (push) Successful in 15s Details
Homelab Main / running-update (push) Successful in 7s Details
Homelab Main / debian-ops (push) Successful in 1m13s Details

This commit is contained in:
juvenal.diaz 2026-09-29 08:26:31 -06:00
parent d08b633a9e
commit 76594f3f1e
8 changed files with 314 additions and 0 deletions

View File

@ -1987,6 +1987,29 @@ resource "helm_release" "prometheus_stack" {
}
grafana = {
nodeSelector = local.prometheus_stack_node_selector
envValueFrom = var.grafana_authentik_sso_enabled ? {
GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET = {
secretKeyRef = {
name = var.grafana_authentik_secret_name
key = "GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET"
}
}
} : {}
"grafana.ini" = var.grafana_authentik_sso_enabled ? {
"auth.generic_oauth" = {
enabled = true
name = "Authentik"
allow_sign_up = true
auto_login = false
client_id = "grafana"
scopes = "openid profile email"
auth_url = "${trimsuffix(var.grafana_authentik_url, "/")}/application/o/grafana/authorize/"
token_url = "${trimsuffix(var.grafana_authentik_url, "/")}/application/o/grafana/token/"
api_url = "${trimsuffix(var.grafana_authentik_url, "/")}/application/o/grafana/userinfo/"
login_attribute_path = "sub"
role_attribute_path = "contains(groups[*], 'grafana-admins') && 'Admin' || 'Viewer'"
}
} : {}
sidecar = {
resources = {
requests = {

View File

@ -257,6 +257,34 @@ variable "prometheus_stack_node_selector" {
}
}
variable "grafana_authentik_sso_enabled" {
description = "Enable Grafana Generic OAuth when the SSO stack's client-secret exists."
type = bool
default = false
}
variable "grafana_authentik_url" {
description = "Public Authentik URL used by Grafana's OIDC client."
type = string
default = ""
}
variable "grafana_public_url" {
description = "Public Grafana URL used for its OIDC redirect URI."
type = string
default = ""
}
variable "grafana_namespace" {
type = string
default = "monitoring"
}
variable "grafana_authentik_secret_name" {
type = string
default = "grafana-authentik-oauth"
}
variable "extra_helm_releases" {
type = map(object({
repository = string

View File

@ -0,0 +1,24 @@
# Grafana SSO
This OpenTofu stack creates the Authentik OIDC provider/application for Grafana,
the `grafana-users` and `grafana-admins` access groups, and the Kubernetes
Secret consumed by the Grafana Helm chart.
Run it from the Debian homelab server:
```bash
./jeannie sso-grafana plan
./jeannie sso-grafana apply
```
Jeannie reads `AUTHENTIK_BOOTSTRAP_TOKEN` from the existing SOPS-encrypted
Authentik secret. Authentik creates this as an API token for `akadmin` on its
first startup, so the same encrypted bootstrap secret can recreate this stack
after an Authentik database destroy/recreate cycle. Add your login account to
`grafana-users`; add it to `grafana-admins` only if it needs Grafana
administrator access.
The OAuth client secret is not committed. It is generated by OpenTofu and
written to the `monitoring/grafana-authentik-oauth` Kubernetes Secret.
OpenTofu state contains this secret, so keep the state directory and its
backups owner-readable only.

View File

@ -0,0 +1,102 @@
terraform {
required_version = ">= 1.0"
required_providers {
authentik = {
source = "goauthentik/authentik"
version = "= 2026.8.0"
}
kubernetes = {
source = "hashicorp/kubernetes"
version = "~> 2.26"
}
random = {
source = "hashicorp/random"
version = "~> 3.7"
}
}
}
provider "authentik" {
url = var.authentik_url
token = var.authentik_token
}
provider "kubernetes" {
config_path = var.kubeconfig_path
}
data "authentik_flow" "authorization" {
slug = "default-provider-authorization-implicit-consent"
}
data "authentik_flow" "invalidation" {
slug = "default-provider-invalidation-flow"
}
data "authentik_property_mapping_provider_scope" "grafana" {
managed_list = [
"goauthentik.io/providers/oauth2/scope-openid",
"goauthentik.io/providers/oauth2/scope-profile",
"goauthentik.io/providers/oauth2/scope-email",
]
}
resource "random_password" "grafana_client_secret" {
length = 48
special = false
}
resource "authentik_group" "grafana_users" {
name = "grafana-users"
}
resource "authentik_group" "grafana_admins" {
name = "grafana-admins"
}
resource "authentik_provider_oauth2" "grafana" {
name = "Grafana"
client_id = "grafana"
client_secret = random_password.grafana_client_secret.result
authorization_flow = data.authentik_flow.authorization.id
invalidation_flow = data.authentik_flow.invalidation.id
property_mappings = data.authentik_property_mapping_provider_scope.grafana.ids
allowed_redirect_uris = [{
matching_mode = "strict"
url = "${trimsuffix(var.grafana_public_url, "/")}/login/generic_oauth"
}]
}
resource "authentik_application" "grafana" {
name = "Grafana"
slug = "grafana"
meta_launch_url = trimsuffix(var.grafana_public_url, "/")
protocol_provider = authentik_provider_oauth2.grafana.id
}
resource "authentik_policy_binding" "grafana_users" {
target = authentik_application.grafana.uuid
group = authentik_group.grafana_users.id
order = 0
}
resource "authentik_policy_binding" "grafana_admins" {
target = authentik_application.grafana.uuid
group = authentik_group.grafana_admins.id
order = 1
}
resource "kubernetes_secret_v1" "grafana_authentik_oauth" {
metadata {
name = var.grafana_secret_name
namespace = var.grafana_namespace
}
data = {
GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET = random_password.grafana_client_secret.result
}
type = "Opaque"
}

View File

@ -0,0 +1,46 @@
variable "authentik_url" {
description = "Public Authentik URL. Defaults from homelab.yml through Jeannie."
type = string
default = ""
validation {
condition = can(regex("^https://", var.authentik_url))
error_message = "authentik_url must be an HTTPS URL."
}
}
variable "authentik_token" {
description = "Scoped Authentik API token, normally supplied as AUTHENTIK_TOKEN."
type = string
sensitive = true
default = ""
validation {
condition = length(var.authentik_token) > 0
error_message = "Set AUTHENTIK_TOKEN to a scoped Authentik API token."
}
}
variable "kubeconfig_path" {
type = string
}
variable "grafana_public_url" {
type = string
default = ""
validation {
condition = can(regex("^https://", var.grafana_public_url))
error_message = "grafana_public_url must be an HTTPS URL."
}
}
variable "grafana_namespace" {
type = string
default = "monitoring"
}
variable "grafana_secret_name" {
type = string
default = "grafana-authentik-oauth"
}

View File

@ -101,6 +101,7 @@ Operator View And Reports
Observability And GitOps
grafana-dashboards {list|apply} List or apply repo-managed Grafana dashboards.
sso-grafana {plan|apply} Provision Authentik OIDC and enable Grafana SSO.
authentik-secret {ensure|file} Generate/check SOPS-encrypted Authentik bootstrap secrets.
gitops-status Print focused Argo CD health and sync status.
platform Deploy platform stack only.
@ -306,6 +307,9 @@ case "${1:-}" in
grafana-dashboards)
grafana_dashboards "$@"
;;
sso-grafana)
grafana_sso "${2:-plan}"
;;
authentik-secret)
authentik_secret "${2:-ensure}"
;;

View File

@ -191,6 +191,8 @@ export_homelab_inventory_tf_vars() {
export_if_unset TF_VAR_homepage_backend_port "${LAB_HOMEPAGE_HTTP_PORT:-}"
export_if_unset TF_VAR_authentik_backend_host "${LAB_AUTHENTIK_BACKEND_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}}"
export_if_unset TF_VAR_authentik_backend_port "${LAB_AUTHENTIK_HTTP_PORT:-}"
export_if_unset TF_VAR_grafana_authentik_url "${LAB_AUTHENTIK_PUBLIC_URL:-}"
export_if_unset TF_VAR_grafana_public_url "https://grafana.${LAB_DOMAIN:-}"
export_if_unset TF_VAR_jellyfin_backend_host "${LAB_JELLYFIN_BACKEND_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}}"
export_if_unset TF_VAR_jellyfin_backend_port "${LAB_JELLYFIN_HTTP_PORT:-}"
export_if_unset TF_VAR_gitops_repo_url "${LAB_GITOPS_REPO_URL:-}"
@ -199,6 +201,18 @@ export_homelab_inventory_tf_vars() {
export_if_unset TF_VAR_worker_tailscale_pod_egress_snat "${LAB_PIMOX_WORKER_TAILSCALE_POD_EGRESS_SNAT:-}"
}
configure_platform_grafana_sso() {
local namespace="${TF_VAR_grafana_namespace:-monitoring}"
local secret_name="${TF_VAR_grafana_authentik_secret_name:-grafana-authentik-oauth}"
if command -v kubectl >/dev/null 2>&1 &&
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get secret "${secret_name}" >/dev/null 2>&1; then
export TF_VAR_grafana_authentik_sso_enabled=true
else
export TF_VAR_grafana_authentik_sso_enabled=false
fi
}
require_debian_server() {
local command_name="$1"
local os_id=""
@ -519,6 +533,10 @@ run_tofu_stack() {
apply_args+=("-var-file=${LAB_CLUSTER_VAR_FILE}")
fi
if [[ "${stack}" == "bootstrap/platform" ]]; then
configure_platform_grafana_sso
fi
tofu -chdir="${REPO_ROOT}/${stack}" init
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
if [[ "${stack}" == "bootstrap/platform" ]]; then
@ -546,10 +564,42 @@ run_tofu_plan_stack() {
plan_args+=("-var-file=${LAB_CLUSTER_VAR_FILE}")
fi
if [[ "${stack}" == "bootstrap/platform" ]]; then
configure_platform_grafana_sso
fi
tofu -chdir="${REPO_ROOT}/${stack}" init
tofu -chdir="${REPO_ROOT}/${stack}" plan "${plan_args[@]}"
}
grafana_sso() {
local action="${1:-plan}"
local stack="bootstrap/sso-grafana"
local bootstrap_token
require_debian_server "sso-grafana"
# Authentik creates this API token for akadmin on its first startup. Using
# the SOPS-encrypted bootstrap value makes the identity stack reproducible
# after an Authentik database destroy/recreate cycle.
bootstrap_token="$(authentik_bootstrap_api_token)" || return 1
export TF_VAR_authentik_token="${bootstrap_token}"
case "${action}" in
plan)
run_tofu_plan_stack "${stack}"
;;
apply)
run_tofu_stack "${stack}"
run_tofu_stack "bootstrap/platform"
;;
*)
echo "Usage: ./jeannie sso-grafana {plan|apply}" >&2
return 2
;;
esac
}
backup_tofu_state() {
local backup_dir="${HOMELAB_TOFU_STATE_BACKUP_DIR:-${HOMELAB_STATE_DIR}/tofu-state-backups}"
local timestamp
@ -568,6 +618,8 @@ backup_tofu_state() {
bootstrap/cluster/terraform.tfstate.backup \
bootstrap/platform/terraform.tfstate \
bootstrap/platform/terraform.tfstate.backup \
bootstrap/sso-grafana/terraform.tfstate \
bootstrap/sso-grafana/terraform.tfstate.backup \
bootstrap/apps/terraform.tfstate \
bootstrap/apps/terraform.tfstate.backup \
bootstrap/edge/terraform.tfstate \

View File

@ -275,6 +275,41 @@ ensure_authentik_secret() {
echo "Authentik bootstrap secret file is present."
}
authentik_bootstrap_api_token() {
local secret_file
local key_file
local decrypted_text
ensure_authentik_secret_file
secret_file="$(authentik_secret_file)"
key_file="$(sops_age_key_file)"
if [[ -s "${key_file}" ]]; then
decrypted_text="$(SOPS_AGE_KEY_FILE="${key_file}" sops -d "${secret_file}")" || return 1
else
decrypted_text="$(sops -d "${secret_file}")" || return 1
fi
SECRET_TEXT="${decrypted_text}" python3 - <<'PY'
import os
import sys
try:
import yaml
except Exception as exc:
print(f"PyYAML is required to parse the Authentik secret: {exc}", file=sys.stderr)
sys.exit(1)
document = yaml.safe_load(os.environ.get("SECRET_TEXT", "")) or {}
values = document.get("stringData") or document.get("data") or {}
token = str(values.get("AUTHENTIK_BOOTSTRAP_TOKEN", ""))
if not token or "\n" in token or "\r" in token:
print("AUTHENTIK_BOOTSTRAP_TOKEN is missing or invalid.", file=sys.stderr)
sys.exit(1)
print(token)
PY
}
authentik_secret() {
local action="${1:-ensure}"