Created
March 4, 2019 17:06
-
-
Save diasjorge/4385f6ce90f45920e43b605dbdf9b691 to your computer and use it in GitHub Desktop.
Kube-exec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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