Terraform, Kubernetes and Github Container Registry Oh My

After much muttering and searching and and then some help from the lovely people on the rands slack, I ended up with a snippet for authenticating my kubernetes cluster to the Github Container Registry using terraform configuration.

tl;dr: create a dockerconfigjson-type secret and use it in the image_pull_secrets field

Create a secret with the authentication details:

resource "kubernetes_secret" "ghcr_auth" {
  metadata {
    name = "ghcr-auth"
  }
  type = "kubernetes.io/dockerconfigjson"
  data = {
    ".dockerconfigjson" = jsonencode({
      "auths" = {
        "https://ghcr.io" = {
          "auth" :  base64encode("${var.github_username}:${var.github_pat}")
        }
      }
    })
  }
}

The github_pat variable has a Personal Access Token with access to read:packages. It’s not actually a variable in my config, because I’m way more secure than that, but… it’s an example.

And using it in a deployment:

resource "kubernetes_deployment" "kanidmd" {
  metadata {
    name = "kanidmd"
    labels = {
      "app" = "kanidmd"
    }
  }
  wait_for_rollout = false
  spec {
    selector {
      match_labels ={
        app = "kanidmd"
      }
    }
    template {
      metadata {
        labels = {
          app = "kanidmd"
        }
      }
      spec {
        image_pull_secrets {
            name = kubernetes_secret.ghcr_auth.metadata[0].name
        }
        container {
          image = "ghcr.io/kanidm/kanidmd:devel"
          name  = "kanidmd"
          resources {
            limits = {
              cpu    = "0.5"
              memory = "512Mi"
            }
            requests = {
              cpu    = "250m"
              memory = "50Mi"
            }
          }
        }
      }
    }
  }
}

The key bit is:

image_pull_secrets {
	name = kubernetes_secret.ghcr_auth.metadata[0].name
}

Rad. Cool. Hopefully searching in future will help people find it. Ugggghhhhh…



#k8s #kubernetes #terraform #github #howto