Skip to content

Instantly share code, notes, and snippets.

@bsnux
Last active October 8, 2021 00:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsnux/26bb3661aec97056419e9f788417f9d0 to your computer and use it in GitHub Desktop.
Save bsnux/26bb3661aec97056419e9f788417f9d0 to your computer and use it in GitHub Desktop.
Runs commands in K8s pods when those are not installed there but they're in the worker node
#!/bin/bash
#------------------------------------------------------------------------
# run-cmd-pod.sh
#
# Runs commands in K8s pods when those are not installed there
# but they're in the worker node.
#
# Motivation: You want to run a command in a pod without
# installing anything in the pod. If that command exists
# in the worker node running the pod, then you can use
# this script
#
# We're assuming here the pod is just running one container
#
# Example:
# ./run-cmd-pod.sh pod-6d7d497f4d-6h65k "dig +short www.google.com"
#
#------------------------------------------------------------------------
set -euo pipefail
pod_name=$1
command=$2
container_id=$(kubectl get po ${pod_name} -o jsonpath='{.status.containerStatuses[0].containerID}' | cut -c 10-21)
node=$(kubectl get po ${pod_name} -o jsonpath='{.spec.nodeName}')
pid=$(ssh -o StrictHostKeyChecking=no ${node} "sudo docker inspect --format '{{ .State.Pid }}' ${container_id}")
ssh -o StrictHostKeyChecking=no ${node} "sudo nsenter -t ${pid} -n ${command}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment