DEV Community

Aleksandr Korolev
Aleksandr Korolev

Posted on

Tools: quickly connect to pods in your Kubernetes cluster

It seems that almost all companies use or try to use Kubernetes. And you, as a developer, need from time to time connect to your app, but when it is in a Kubernetes cluster, it is not so simple.
How it can look like in your case:

# switch to appropriate context 
kubectl ctx your-context
# get pods
kubectl -n namespace get pods
# connect to the pod
kubectl -n nameapce exec -it pod/#{pod-name-from-previous-step} -- bash 
Enter fullscreen mode Exit fullscreen mode

Do it every time - tedious, isn't it?
In my team, we are using next script:

#!/bin/bash

# how make script executable

# chmod +x k8s.sh

# this is necessary to split the command output on new lines

IFS='

'

show_help () {

  echo "Usage: k8s.sh [environment] [SUBENV] - ssh to a pod from the environment-subenv"

  echo "Example: k8s.sh staging web - connect to the web pod in the staging environment"

  echo "It uses current directory in order to build the pod name"

}




if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then

  show_help

  exit 1

fi




ENVIRONMENT=$1

SUBENV=$2




working_dir=${PWD##*/}

project=$(echo "$working_dir" | tr '[:upper:]' '[:lower:]' )

namespace="$project-$ENVIRONMENT"




kubectl ctx |  grep "$ENVIRONMENT" | tr -d '\n'  | xargs -0 kubectl ctx




output=$(kubectl -n "$namespace" get pods | grep "$SUBENV" | Head -n 1)

podname=${output%% *}; remainder="${remainder#* }"




echo "ssh-ing you into $podname . . ."




kubectl --namespace=${namespace} exec -it pod/${podname} -- bash
Enter fullscreen mode Exit fullscreen mode

It allows easily connect to pods from a specific namespace (a namespace depends on current directory - current project).
Subenv is necessary because we have different types of pods (web, activejobs, migration).

Top comments (0)