4

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
  • 6,040
  • 8
  • 41
  • 80
  • It's not what you asked, but this ps1 script can help you keep your context in mind... https://github.com/jonmosco/kube-ps1 – switchboard.op Dec 18 '18 at 23:05

2 Answers2

3
#!/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
  • 2,857
  • 2
  • 22
  • 38
  • 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. – Alex Flint Dec 18 '18 at 23:12
  • 1
    Then how can you define desire cluster name. pass variable or something? or interactive CLI? – Abu Hanifa Dec 19 '18 at 05:51
1

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
  • 11,832
  • 5
  • 38
  • 61
  • Hmm on GKE there are no hostnames for the master nodes, and the IP addresses aren't very meaningful or easy to remember – Alex Flint Dec 20 '18 at 17:08
  • Yeah presumably this is why you're trying a different approach under https://stackoverflow.com/questions/53842487/stop-kubectl-from-printing-pod-curl-deleted-at-end as that seems to give you a more meaningful name – Ryan Dawson Dec 20 '18 at 17:29
  • With gke another way would be to use `kubectl get nodes` as the cluster name gets used in the node names but that doesn't hold for other clouds. – Ryan Dawson Dec 20 '18 at 18:54