Having to log into all of your VKS clusters one by one sucks as you either have to export your vSphere Password as an environment variable (which is kinda insecure) or enter the Password for each of your Clusters over and over again.
As we got annoyed with that one of my Customers (Ralf Dahmen) and I decided to fix this by developing a little bash script that automatically detects all clusters in your vSphere Namespaces and logs you in to them, to do so you only ned to enter your Password once.
Prequesits
To run the script you’ll need to have some binaries available, those are sed
, tail
, grep
, jq
and expect
this shouldn’t be a problem for any modern linux distro or MacOS.
Here are some examples on how to get those commands..
Ubuntu/Debian:
apt-get install sed tail grep jq expect
Arch:
pacman -Sy sed grep jq expect
Script
Just save the following script as vks-login.sh
file in your PATH
and chage permissions chmod +x vks-login.sh
afterwards you can login with vks-login.sh
.
#!/bin/bash
# Ralf Dahmen
# Maximilian Marschall <[email protected]>
# https://msta.cc https://marschall.systems
# Requirements:
# apt-get install sed tail grep jq expect
# BEGIN USER SETTINGS
SERVER=svc.marschall.management
USERNAME=[email protected]
# END USER SETTINGS
# DO NOT MODIFY AFTER THIS LINE IF YOU'RE NOT 100% SURE WHAT YOUR DOING
GREEN='\033[032m'
NC='\033[0m' # No Color
unset -v KUBECTL_VSPHERE_PASSWORD
set +o allexport
IFS= read -rsp "Please enter password for $USERNAME: " KUBECTL_VSPHERE_PASSWORD
echo ""
expect - <<EOF
log_user 0
spawn kubectl vsphere login --server=$SERVER --insecure-skip-tls-verify --vsphere-username $USERNAME
expect Password:
send -- "$KUBECTL_VSPHERE_PASSWORD\r"
expect eof
EOF
namespaces=$(kubectl config get-contexts | tr -s " " | sed -e "s/ /,/g" | tail -n +2 | awk -F, '{print $NF}' | grep -v '^$' | sort | uniq)
if [ -z "$namespaces" ]; then
echo "No namespaces found"
exit 1
else
ns_count=$(echo "$namespaces" | wc -l)
echo "$ns_count Namespaces found"
for namespace in $namespaces; do
kubectl config use-context $SERVER > /dev/null 2>&1
tkcs=$(kubectl get cluster -n $namespace -o json | jq -r .items[].metadata.name)
if [ -z "$tkcs" ]; then
echo "no clusters found in $namespace"
else
tkc_count=$(echo "$tkcs" | wc -l)
echo "$tkc_count clusters found in $namespace"
for tkc in $tkcs; do
kubectl config use-context $SERVER > /dev/null 2>&1
echo -e "${GREEN}Login to $tkc in $namespace ${NC}"
expect - <<EOF
log_user 0
spawn kubectl vsphere login --server=$SERVER --insecure-skip-tls-verify --vsphere-username $USERNAME --tanzu-kubernetes-cluster-namespace $namespace --tanzu-kubernetes-cluster-name $tkc
expect Password:
send -- "$KUBECTL_VSPHERE_PASSWORD\r"
expect eof
EOF
done
fi
done
fi