Skip to content

Instantly share code, notes, and snippets.

@diasjorge
Created March 4, 2019 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diasjorge/4385f6ce90f45920e43b605dbdf9b691 to your computer and use it in GitHub Desktop.
Save diasjorge/4385f6ce90f45920e43b605dbdf9b691 to your computer and use it in GitHub Desktop.
Kube-exec
#!/usr/bin/env bash
NAMESPACE=${1}
POD=${2}
COMMAND=${3:-sh}
USER=${4:-root}
KUBECTL=kubectl
NEW_POD_NAME=exec-user-${POD}
NEW_POD_NAME=${NEW_POD_NAME:0:63} # max len allowed
NODENAME=$( $KUBECTL --namespace ${NAMESPACE} get pod ${POD} -o go-template='{{.spec.nodeName}}' )
if [[ -n ${CONTAINER} ]]; then
DOCKER_CONTAINERID=$( eval $KUBECTL --namespace ${NAMESPACE} get pod ${POD} -o go-template="'{{ range .status.containerStatuses }}{{ if eq .name \"${CONTAINER}\" }}{{ .containerID }}{{ end }}{{ end }}'" )
else
DOCKER_CONTAINERID=$( $KUBECTL --namespace ${NAMESPACE} get pod ${POD} -o go-template='{{ (index .status.containerStatuses 0).containerID }}' )
fi
CONTAINERID=${DOCKER_CONTAINERID#*//}
read -r -d '' OVERRIDES <<EOF
{
"apiVersion": "v1",
"spec": {
"containers": [
{
"image": "docker",
"name": "docker",
"stdin": true,
"stdinOnce": true,
"tty": true,
"restartPolicy": "Never",
"args": [
"exec",
"-it",
"-u",
"${USER}",
"${CONTAINERID}",
"${COMMAND}"
],
"volumeMounts": [
{
"mountPath": "/var/run/docker.sock",
"name": "docker"
}
]
}
],
"nodeSelector": {
"kubernetes.io/hostname": "${NODENAME}"
},
"volumes": [
{
"name": "docker",
"hostPath": {
"path": "/var/run/docker.sock",
"type": "File"
}
}
]
}
}
EOF
eval kubectl run --namespace=${NAMESPACE} -it --rm --restart=Never --image=docker --overrides="'${OVERRIDES}'" ${NEW_POD_NAME}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment