Creating a kubeconfig file for a service

When deploying a service outside Kubernetes that uses the Kubernetes API as a service account, it's generally required to use a kubeconfig file. Instructions that I've found elsewhere involve copying the user's ~/.kube/config file but that contains potentially many cluster configurations and also provides the credentials of the admin user.

I wrote a small shell script that will generate a new kubeconfig file for a service account on a Kubernetes cluster. It takes the certificate authority from the user's current config, and retrieves the service account's authentication token.

For example, to create a kubeconfig file for a service account user named spinnaker, in a kubernetes cluster called cluster-1:

$ ./build_kubeconfig.sh "spinnaker" "cluster-1" > kubeconfig
Retrieving token for the spinnaker user
Retrieving certificate authority for the cluster-1 cluster

$ cat kubeconfig
apiVersion: v1
kind: Config
users:
- name: spinnaker
  user:
    token: <REDACTED>
clusters:
- cluster:
    certificate-authority-data: <REDACTED>
    server: <REDACTED>
  name: cluster-1
contexts:
- context:
    cluster: cluster-1
    user: spinnaker
  name: cluster-1
current-context: cluster-1

Download the shell script here.