Script that checks I'm deploying to the correct kubernetes cluster

12/18/2018

I have a script that deploys my application to my kubernetes cluster. However, if my current kubectl context is pointing at the wrong cluster, I can easily end up deploying my application to a cluster that I did not intend to deploy it to. What is a good way to check (from inside a script) that I'm deploying to the right cluster?

I don't really want to hardcode a specific kubectl context name, since different developers on my team have different conventions for how to name their kubectl contexts.

Instead, I'd like something more like if $(kubectl get cluster-name) != "expected-clsuter-name" then error.

-- Alex Flint
kubectl
kubernetes

2 Answers

12/18/2018
#!/bin/bash

if [ $(kubectl config current-context) != "your-cluster-name" ]
then
    echo "Do some error!!!"
    return
fi

echo "Do some kubectl command"

Above script get the cluster name and match with your-desired-cluster name. If mismatch then give error. Otherwise run desire kubectl command.

-- Abu Hanifa
Source: StackOverflow

12/18/2018

For each cluster run kubectl cluster-info once to see what the IP/host for master is - that should be stable for the cluster and not vary with the name in the kubectl context (which developers might be setting differently). Then capture that in the script with export MASTERA=<HOST/IP> where that's the master for cluster A. Then the script can do:

kubectl cluster-info | grep -q $MASTERA && echo 'on MASTERA'

Or use an if-else:

if kubectl cluster-info | grep -q $MASTERA; then
   echo 'on $MASTERA'
else
  exit 1
fi
-- Ryan Dawson
Source: StackOverflow