Skip to content

Instantly share code, notes, and snippets.

@metajiji
Created April 19, 2023 15:58
Show Gist options
  • Save metajiji/e68a9b9ebe0e97360de72f50633d2c6b to your computer and use it in GitHub Desktop.
Save metajiji/e68a9b9ebe0e97360de72f50633d2c6b to your computer and use it in GitHub Desktop.
k8s nsenter script
#!/bin/sh
node=${1}
kube_context=${2:-""}
nodeName=$(kubectl ${kube_context:+--context $kube_context} get node "$node" -o template --template='{{index .metadata.labels "kubernetes.io/hostname"}}')
nodeSelector='"nodeSelector": { "kubernetes.io/hostname": "'${nodeName:?}'" },'
podName=$USER-nsenter-$node
kubectl ${kube_context:+--context $kube_context} run "${podName:?}" --restart=Never -it --rm --image overriden --overrides '
{
"spec": {
"hostPID": true,
"hostNetwork": true,
'"${nodeSelector?}"'
"tolerations": [{
"operator": "Exists"
}],
"containers": [
{
"name": "nsenter",
"image": "alexeiled/nsenter:2.34",
"command": [
"/nsenter", "--all", "--target=1", "--", "su", "-"
],
"stdin": true,
"tty": true,
"securityContext": {
"privileged": true
}
}
]
}
}' --attach "$@"
@metajiji
Copy link
Author

Usage example

$ kubectl --context ctx-xxx get nodes
NAME                        STATUS   ROLES    AGE     VERSION
node-yyy   Ready    <none>   17d    v1.23.6
node-zzz   Ready    <none>   59d     v1.23.6

$ sh nsenter.sh node-yyy ctx-xxx
If you don't see a command prompt, try pressing enter.
root@node-yyy:~# 

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