Rotating certificates in Azure Kubernetes Service (AKS)

Today I was given the task to rotate an expired Azure Kubernetes Service (AKS) certificate for a client. As I am still not a Kubernetes ninja I though it would be a fun exercise to write as I learn, so I thought I would share the solution to this problem.

Every once and a while certificates on the Azure Kubernetes Service need to be rotated. If you dont you will receive this error when you try to connect to a cluster:

Unable to connect to the server: x509: certificate has expired or is not yet valid: current time 2021-01-13T14:13:36+01:00 is after 2020-11-29T09:13:56Z

How to read your current credentials expiration date:

Run this commad to get your base64 encoded certificate data.

kubectl config view --raw -o jsonpath="{.clusters[?(@.name == '<NAME OF YOUR CLUSTER>')].cluster.certificate-authority-data}"

Copy the base64 certificate data and decode it using: https://www.base64decode.org. What you'll get is your actual certificate which looks something like this:

-----BEGIN CERTIFICATE-----
MIIE6DCCAtCgAwIBAgIQQnfmwJLP3QTBNiwZ26tikzANBgkqhkiG9w0BAQsFADAN
MQswCQYDVQQDEwJjYT.....
-----END CERTIFICATE-----

Now use a Certificate Decoder such as https://www.sslshopper.com/certificate-decoder.html to get the human readable certificate information. This will look something like this:

Certificate Information:
Common Name: ca
Valid From: January 15, 2021
Valid To: January 15, 2051
Serial Number: ....

Rotating your cluster certificate:

Once you've established that you need to rotate your certificate make sure you are running Azure CLI version 2.0.77 or later otherwise these commands wont work:

First run this command to sign in to your AKS cluster:

az aks get-credentials -g <NAME OF RESOURCE> -n <NAME OF CLUSTER>

Then rotate the cluster using:

az aks rotate-certs -g <NAME OF RESOURCE> -n <NAME OF CLUSTER>

Now update the certificate used by kubectl using this command:

az aks get-credentials -g <NAME OF RESOURCE> -n <NAME OF CLUSTER> --overwrite-existing

Now run any command to make sure you've successfully rotated your cluster certificate and that you can access your cluster, for instance using this command:

kubectl get pods

And that´s it!

Note that this is a stripped version of the microsoft documentation for rotating Azure Kubernetes Service. If you want the full documentation for every step please visit: https://docs.microsoft.com/sv-se/azure/aks/certificate-rotation