Last active
April 10, 2022 21:01
-
-
Save J-Swift/fe1f30a5fd58efc0b881f36f59815984 to your computer and use it in GitHub Desktop.
Convenience script to intelligently connect to a kubernetes pod/node given the API name
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 | |
set -eu | |
readonly mode="${1:-}" | |
readonly target="${2:-}" | |
readonly ssh_key_path="path_to_kops_ssh_key" | |
die() { | |
local -r msg="${1:-}" | |
echo "${msg}" | |
exit 1 | |
} | |
if [ "pod" != "${mode}" ] && [ "node" != "${mode}" ]; then | |
die "ERROR: unknown mode [${mode}] must be one of [pod, node]" | |
fi | |
if [ -z "${target}" ]; then | |
die 'ERROR: must provide a target' | |
fi | |
target_looks_like_a_node() { | |
echo "${target}" | grep -Eq "\.ec2\.internal" | |
} | |
get_node_from_pod() { | |
local -r pod="${1}" | |
kubectl get pod/"${pod}" -o go-template="{{.spec.nodeName}}" 2>/dev/null || echo '' | |
} | |
get_external_ip_from_node() { | |
local -r node="${1}" | |
kubectl get node/"${node}" -o go-template='{{range .status.addresses}}{{if eq .type "ExternalIP"}}{{.address}}{{end}}{{end}}' 2>/dev/null || echo '' | |
} | |
verify_is_node() { | |
local -r node="${1}" | |
(kubectl get nodes -o custom-columns=NAME:.metadata.name | grep -q "${node}") || die "ERROR: not a valid node [${node}]" | |
} | |
verify_is_pod() { | |
local -r pod="${1}" | |
(kubectl get pods -o custom-columns=NAME:.metadata.name | grep -q "${pod}") || die "ERROR: not a valid pod [${pod}]" | |
} | |
connect_to_node() { | |
local -r target_node="${1}" | |
verify_is_node "${target_node}" | |
local -r node_ip="$( get_external_ip_from_node "${target_node}" )" | |
echo "> ssh'ing to node [${node_ip}]" | |
ssh -i "${ssh_key_path}" admin@"${node_ip}" | |
} | |
connect_to_pod() { | |
local -r target_pod="${1}" | |
verify_is_pod "${target_pod}" | |
echo "> connecting to pod [${target_pod}]" | |
kubectl exec -it "${target_pod}" --container server -- /bin/sh | |
} | |
main() { | |
if [ "pod" == "${mode}" ]; then | |
target_looks_like_a_node && die "It appears you provided a node [${target}]" | |
connect_to_pod "${target}" | |
elif [ "node" == "${mode}" ]; then | |
local node="${target}" | |
if ! target_looks_like_a_node; then | |
node="$( get_node_from_pod "${target}" )" | |
if [ -z "${node}" ]; then | |
die "ERROR: unable to resolve node for target [${target}]" | |
fi | |
fi | |
connect_to_node "${node}" | |
fi | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment