Created
March 17, 2018 00:24
-
-
Save s1113950/79b29d6ae82184b15d538e3cfe6a5439 to your computer and use it in GitHub Desktop.
Patch kubernetes deployment with ssh environment -- ANTIPATTERN (but sometimes desired :) )
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
#!/bin/bash | |
# YOU NEED install_ssh.sh AND export_env_vars.sh FROM HERE: | |
# this script assumes you put them in /tmp | |
# https://gist.github.com/s1113950/0d7cfe3fc88329c4b4ae0cb75750e8aa | |
# https://gist.github.com/s1113950/039b52c35337b377239bc1f7f37724c5 | |
# CALL IT LIKE THIS: `ssh_env.sh {deployment_name}` | |
PUB_KEY="${PUB_KEY:-${HOME}/.ssh/id_rsa.pub}" | |
deployment=$1 | |
pod=$(kubectl get pods | grep "${deployment}" | awk '{print $1}') | |
# copy public ssh key to container | |
kubectl exec -i "${pod}" -- bash -c "mkdir -p /root/.ssh" | |
# NOTE: kubectl cp does not support changing target filename | |
cp "${PUB_KEY}" /tmp/authorized_keys2 | |
kubectl cp /tmp/authorized_keys2 "${pod}":/root/.ssh/authorized_keys2 | |
rm /tmp/authorized_keys2 | |
# Copy known hosts so you can pull from github without having to ask (assuming you have github as a known_host already on your machine) | |
kubectl cp "${HOME}/.ssh/known_hosts" "${pod}":/root/.ssh/known_hosts | |
kubectl cp /tmp/install_ssh.sh "${pod}":/tmp/install_ssh.sh | |
kubectl exec -i "${pod}" -- /tmp/install_ssh.sh | |
pkill kubectl port-forward "${pod}" || true | |
kubectl port-forward "${pod}" "${port}":22 & | |
sleep 2 | |
# copy kubectl env vars to the root user, this ensures that `ssh` will be the same env as `kubectl exec` | |
kubectl cp /tmp/export_env_vars.sh "${pod}":/tmp/export_env_vars.sh | |
kubectl exec -i "${pod}" -- /tmp/export_env_vars.sh | |
echo "pod ${pod} is accessible via:" | |
echo "ssh -A root@127.0.0.1 -p ${port} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -F /dev/null" | |
# CAVEAT: You'll have to periodically rerun your `kubectl port-forward` command (like if you close your computer). | |
# I've noticed that occasionally `kubectl port-forward` will die and need bouncing in this case. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment