SREERAJ.DEV // PERSONAL SITE EDITION 2026-08 · BRUTALIST --:--:-- UTC SCR 000%
SREERAJ.DEV/

Backend engineering & Himalayan treks — plain HTML, served statically

Adding Basic Authentication via NGINX in Kubernetes

Basic Auth via NGINX in kubernetes

date
2022-10-26
updated
2022-11-01
author
Sreeraj Rajan
read time
1 min
tags
[aws][kubernetes][tech][nginx][k8s][devops][shorts]
Adding Basic Authentication via NGINX in Kubernetes
FIG. 01 — Adding Basic Authentication via NGINX in Kubernetes

1. Generate the htpasswd file

htpasswd -c auth sree
New password:
Re-type new password:
Adding password for user sree

2. Create a kubernetes secret with the auth file as the source.

resource "kubernetes_secret" "service-secret" {
  metadata {
    name      = "basic-auth"
    namespace = "production"
  }

  data = {
    "auth" = file("${path.cwd}/auth")
  }
}

3. Reference the secret in the ingress annotations.

resource "kubernetes_ingress" "service_ingress" {
  metadata {
    name      = "service-ingress"
    namespace = "production"
    annotations = {
      "kubernetes.io/ingress.class"             = "nginx"
      "cert-manager.io/cluster-issuer" = "cert-manager"
      "nginx.ingress.kubernetes.io/auth-type"   = "basic"
      "nginx.ingress.kubernetes.io/auth-secret" = "basic-auth"
      "nginx.ingress.kubernetes.io/auth-realm"  = "Authentication Required - sree"
    }
  }

Terraform (HCL)

Voila, the service will ask you for the username and password to login whenever you access the service.

Extremely useful if you are dealing with internal/private dashboards and quickly want to add a layer of authentication without dealing with the internal application code.