Skip to content

Instantly share code, notes, and snippets.

@tomdavidson
Created June 2, 2022 15:48
Show Gist options
  • Select an option

  • Save tomdavidson/481210690903e6641b7dce77c20b102c to your computer and use it in GitHub Desktop.

Select an option

Save tomdavidson/481210690903e6641b7dce77c20b102c to your computer and use it in GitHub Desktop.
k8s socat service to port fwd db access
#!/usr/bin/env bash
get_kubeconfig() {
mkdir -p "$HOME"/.kube
ssa-pg/scripts/pulumi-run.sh kubecfg > "$HOME"/.kube/config
}
PORT=${PORT:-5432}
SERVICE_NAME="postgres-tunnel"
start_proxy_service() {
local suffix=''
[[ -n "$1" ]] && suffix+="-$1"
kubectl run "${SERVICE_NAME}${suffix}" --image=alpine/socat \
--expose=true --port="${PORT}" \
tcp-listen:"${PORT}",fork,reuseaddr \
tcp-connect:"${ENDPOINT}:${PORT}"
kubectl wait --for=condition=Ready pod "${SERVICE_NAME}${suffix}"
}
start_fwd() {
local suffix=''
[[ -n "$1" ]] && suffix+="-$1"
echo "Forwarding connection to ${ENDPOINT}:${PORT} from 127.0.0.1:${PORT}"
kubectl port-forward service/"${SERVICE_NAME}${suffix}" "${PORT}:${PORT}" &
}
up() {
if [[ $1 == 'prod' ]]; then
ENDPOINT=$(ssa-pg/scripts/pulumi-run.sh db_host prod)
else
ENDPOINT=$(ssa-pg/scripts/pulumi-run.sh db_host main)
fi
start_proxy_service "$@"
start_fwd "$@"
}
destroy() {
local suffix=''
[[ -n "$1" ]] && suffix+="-$1"
pkill kubectl -9
kubectl delete service/"${SERVICE_NAME}${suffix}"
kubectl delete pod/"${SERVICE_NAME}${suffix}"
}
"$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment