OAuth for kubectl (and Keycloak)

Recently, I've setup an internal Keycloak (an open source Identity and Access Management) instance to manage user (and application) access to K8s cluster. One could certainly create users in K8s directly, but it's rather tedious process involving creation of certificate/key pairs for every user managed that way (see Bitnami's How-To Configure RBAC in K8s). Then there's dealing with access / certificate revocation, rotation, etc..
With self-registration, group management, Keycloak is a safer, more robust, and simply better way of managing user and application access to Kube-API server via OAuth.

I highly recommend Bob Killen's article titled "Kubernetes Day 2 Operations: AuthN/AuthZ with OIDC and a Little Help From Keycloak"

Inspired by above-mentioned article, and login.sh script from Bob's oidckube project, I've made somewhat modified version of the script to support easier login in multi-cluster environment.

My version - k8s-oidc-login, uses YAML config, allowing to configure global or per-cluster OIDC endpoints, username, password, etc.

If you save the script as "kubectl-login" and place it in your exec PATH, it can be used as kubectl plugin.
Usage would look like kubectl login [--kubeconfig=kubectl-config-file] [--context=kubectl-context]

Example config:

  oidc_server: keycloak-server1.hostname.com
  oidc_username: [email protected]
  oidc_password: bad-idea-to-keep-password-here-it-is-known
  oidc_client_id: kubernetes
    oidc_server: keycloak-server1.hostname.com
    oidc_username: [email protected]
    oidc_password: bad-idea-to-keep-password-here
    oidc_auth_realm: cluster-name-1-realm
    oidc_client_secret: 33f12b49-faf9-498f-996a-c6cfe5d46d29
    oidc_auth_realm: cluster-name-2-realm
    oidc_client_secret: b1e512f9-02f0-442b-a1a0-b5c728c7254c
    oidc_auth_realm: cluster-name-3-realm
    oidc_client_secret: 1091a5fb-7dbe-41fd-9251-8131ab2ec25d

Naturally, standard disclosures apply, YMMV.. Hopefully, this might come handy for those using Keycloak, or other OAuth providers for Kubernetes RBAC.