Skip to content

Instantly share code, notes, and snippets.

@drye
Created May 24, 2024 09:13
Show Gist options
  • Save drye/dbe1d6b34533dc0c9bacc79be5236678 to your computer and use it in GitHub Desktop.
Save drye/dbe1d6b34533dc0c9bacc79be5236678 to your computer and use it in GitHub Desktop.
export AWS_PROFILE=470465538235_DEV-API
# Description: This function is used to execute kubectl commands in a specific namespace.
# If the NAMESPACE environment variable is not set, it defaults to "sobi".
# Parameters:
# - $@: The kubectl command and its arguments.
# Usage: k [kubectl command and arguments]
# Example:
# - k get pods
k() {
NAMESPACE=${NAMESPACE:-sobi}
kubectl -n $NAMESPACE $@
}
# Description: Retrieves the names of Kubernetes pods using the 'kubectl get pods' command and filters the results based on a provided regular expression pattern.
# Parameters:
# - $1 (optional): Regular expression pattern to filter the pod names. If not provided, all pod names will be returned.
# Usage: getpods [pattern]
# Example:
# - getpods (gets all pods)
# - getpods customer (gets all pods with the word 'customer' in the name)
getpods() {
k get pods --no-headers -o custom-columns=":metadata.name" | grep ${1:-'.*'}
}
# Retrieves a specific pod from the output of the 'getpods' command.
# Parameters:
# $1 - The argument to be passed to the 'getpods' command.
# $2 - The line number of the pod to retrieve. Defaults to 1 if not provided.
# Returns:
# The specified pod from the output of the 'getpods' command.
# Example:
# - getpod customer (gets the first instance of the customer pod)
# - getpod customer 2 (gets the second instance of the customer pod)
getpod() {
LINE="${2:-1}"
getpods $1 | sed -n "${LINE}p"
}
# Description: This function starts a bash session in a specific pod.
# Parameters:
# - $1: The pod name.
# - $2: The line number of the pod. Default is 1.
# Usage: sshpod <podname> [line_number]
# Example:
# - sshpod customer (logs into the first instance of the customer pod)
# - sshpod customer 2 (logs into the second instance of the customer pod)
sshpod () {
LINE="${2:-1}"
POD=`getpod $1 $LINE`
echo "Starting a bash session in pod number ${LINE}: ${POD}..."
k exec --stdin --tty $POD -- /bin/bash
}
# Description: Function to start a logging follow session in a specific pod. Note that this function uses the 'pino-pretty' package to format the logs.
# The 'pino-pretty' package can be installed using the following command: 'npm install -g pino-pretty'.
# Parameters:
# $1: The pod number
# $2: The line number (optional, default is 1)
# Usage: logpod <podname> [line_number]
# Example:
# - logpod customer 2 (starts a logging follow session in the second instance of the customer pod)
logpod () {
LINE="${2:-1}"
POD=`getpod $1 $LINE`
echo "Starting a logging follow session in pod number ${LINE}: ${POD}..."
k logs $POD --all-containers -f -- | pino-pretty
}
# Description: Function to switch to a Kubernetes context based on the provided pod name.
# Parameters:
# $1 - Part of the name of the cluster.
# Usage: contextpod <cluster_name>
# Example:
# - contextpod dog (switches to the context of dog1-dogfood-usw2-primary)
contextpod () {
CLUSTER_NAME=`k config get-contexts | awk '{if (NR>1) print $1}' | grep $1 -m 1`
kubectl config use-context $CLUSTER_NAME
}
# Description: Copies a file to multiple pods in a Kubernetes cluster.
# Parameters:
# $1 - Name of the pod (can be partial)
# $2 - Source file: The file to be copied.
# $3 - Destination directory: The directory in the pods where the file will be copied.
# $singleRun - Optional parameter: If set to "single", the file will only be copied to the first pod.
# Usage: cppods <podname> <source_file> <destination_directory> [single]
# Example:
# - cppods customer /tmp/file.txt /tmp/ (copies file.txt to the /tmp directory in all customer pods)
# - cppods customer /tmp/file.txt /tmp/ single (copies file.txt to the /tmp directory in the first customer pod)
cppods () {
local singleRun=$3
PODS=`getpods $1`
while IFS= read -r pod; do
echo "Copying ${2} to ${pod}:${3}"
k cp $2 $pod:$3
if [[ $singleRun == "single" ]]; then
break
fi
done <<< "$PODS"
}
# Description: Copies a file to a specific pod in a Kubernetes cluster.
# Parameters:
# $1 - Name of the pod (can be partial)
# $2 - Source file: The file to be copied.
# $3 - Destination directory: The directory in the pod where the file will be copied.
# Usage: cppod <podname> <source_file> <destination_directory>
# Example:
# - cppod customer /tmp/file.txt /tmp/ (copies file.txt to the /tmp directory in the first customer pod)
cppod () {
cppods $1 $2 single
}
# Function to execute a command on multiple pods
# Parameters:
# $1: Name of the pod (can be partial)
# $2: Command to be executed on the pods
# $3: Optional flag to indicate if the command should be executed on a single pod only
# Usage: execpods <podname> <command> [single]
execpods () {
local singleRun=$3
PODS=`getpods $1`
cmd=$2 # store the command as a string, not as an array
while IFS= read -r pod; do
echo "Running ${cmd} on pod ${pod}:"
k exec "$pod" -- /bin/sh -c "${cmd}" # evaluate the command string with /bin/sh
if [[ $singleRun == "single" ]]; then
break
fi
done <<< "$PODS"
}
# Description: This function calls the 'execpods' command with the provided arguments and the 'single' option.
# It is a convenient shortcut for executing a single pod.
# Parameters:
# $1 - Name of the pod (can be partial)
# $2 - Command to be executed on the pod
# Example usage:
# execpod customer du
function execpod() {
execpods $1 $2 single
}
# Function to check the health status of pods
# Usage: healthpods [customer] [status]
# - customer: Optional argument to specify the customer (default is "customer")
# - status: Optional argument to specify whether to display only the status (default is to display the entire response)
# Example usage:
# - healthpods customer: Check the health status of pods for the customer pods
# - healthpods customer status: Check and display only the health status summary (ok or critical)
healthpods () {
port=3000
if [[ $1 == "customer" ]]; then
port=3004
fi
if [[ $2 == "status" ]]; then
execpods $1 "curl -s localhost:$port/health | jq '.status'"
else
execpods $1 "curl -s localhost:$port/health | jq"
fi
}
# Function to retrieve all secrets in Kubernetes secrets for a particular pod
# Parameters:
# - podname: The pod name (can be partial)
# Returns:
# - The values of the matching pod's secrets
secretpod() {
local search_string=$1
local secret_name=$(k get secrets | grep "$search_string" | grep parameter-store | awk '{print $1}' | head -n 1)
if [[ -z "$secret_name" ]]; then
echo "No secret found matching the search criteria."
return 1
fi
k get secrets "$secret_name" -o json | jq -r '.data | map_values(@base64d)' | jq -r 'to_entries|map("\(.key)=\(.value|tostring)")[]'
}
# Function: awsps
# Description: This function retrieves the value of an AWS SSM parameter using the AWS CLI.
# Parameters:
# - $1: The name of the parameter to retrieve.
# Usage: awsps <parameter_name>
# Example:
# - awsps /ci/us-west-2/dev/sobi/uprise-backend/postgres-connection
awsps () {
aws ssm get-parameter --with-decryption --name ${1} --query Parameter.Value --output text
}
# Function: psdb
# Description: This function sets the necessary environment variables and connects to a PostgreSQL database using the provided credentials.
# Parameters:
# - $1: The name of the AWS parameter
# Usage: psdb <parameter_name>
# Example:
# - psdb /ci/us-west-2/dev/sobi/uprise-backend/postgres-connection
psdb () {
export CREDS=`awsps ${1}`; export PGPASSWORD=`echo $CREDS | jq -r .password`; psql -h `echo $CREDS | jq -r .host` -p `echo $CREDS | jq -r .port` -d `echo $CREDS | jq -r .database` -U `echo $CREDS | jq -r '.username // .user'`
}
@mariobm
Copy link

mariobm commented May 24, 2024

@drye an idea to retrieve the port automatically

healthpods () {
  kubepod=`getpod $1`
  port=`k get pod ${kubepod} -o jsonpath='{.spec.containers[*].ports[*].containerPort}'`
  if [[ $2 == "status" ]]; then
    execpods $1 "curl -s localhost:$port/health | jq '.status'"
  else
    execpods $1 "curl -s localhost:$port/health | jq"
  fi
}

It's slow, but it can be added only for non hard-coded ports.

I use this in my script, which only works for one pod:

khealth() {
  pod=$(kgp | grep $1 | head -1 | awk '{ print $1}')
  port=$(k get pod ${pod} -o jsonpath='{.spec.containers[*].ports[*].containerPort}')
  k exec -it ${pod} -- bash -c "curl http://localhost:\$(echo $port)/health | jq"
}

But when I run your script healthpods customer the output is not colored:. My khealth output is colored. Not sure why.

Anyway, it would be nice to create a new helper function that would return only the error message.
Most of the time we do a health check to see if something went wrong, we should return that, only error or multiple of errors.

I would still leave healthpods as is, because we can still see the timeElapsedInMs (customer api) and see if there are any latency issues.

Thank you for this, the script is spotless 💯 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment