Skip to content

Instantly share code, notes, and snippets.

@ABGEO
Created December 14, 2023 09:40
Show Gist options
  • Save ABGEO/03ec6824cc218e2735459ffe7bb1e197 to your computer and use it in GitHub Desktop.
Save ABGEO/03ec6824cc218e2735459ffe7bb1e197 to your computer and use it in GitHub Desktop.
This shell script simplifies connecting to a PostgreSQL Cluster deployed by Zalando Postgres Operator.

README

This shell script simplifies connecting to a PostgreSQL Cluster deployed by Zalando Postgres Operator.

The script performs the following actions:

  • Retrieves the master pod's name
  • Fetches the password for the specified user
  • Prints port forwarding and connection instructions

Usage

Make sure you have the necessary permissions and configurations set up in your environment before executing the script.

chmod +x pg.sh

Run the script using the following format:

./pg.sh [K8S_NS] [PG_CLUSTER_NAME] [PG_USER] [PG_DATABASE]

Replace the placeholders with the specific values for your environment:

  • K8S_NS: Kubernetes Namespace where the PostgreSQL cluster is deployed.
  • PG_CLUSTER_NAME: Name of the PostgreSQL cluster.
  • PG_USER: Username for connecting to the PostgreSQL cluster.
  • PG_DATABASE: Name of the PostgreSQL database.
./pg.sh acme acme-cluster acme-user acme-db
#!/usr/bin/env sh
set -eu
if [ $# != 4 ]; then
cat <<EOF
Invalid number of arguments has provided!
Usage: pg.sh [K8S_NS] [PG_CLUSTER_NAME] [PG_USER] [PG_DATABASE]
EOF
exit 1
fi
K8S_NS=$1
PG_CLUSTER_NAME=$2
PG_USER=$3
PG_DATABASE=$4
PG_MASTER=$(kubectl -n "$K8S_NS" get pods -o jsonpath="{.items..metadata.name}" -l application="spilo,cluster-name=${PG_CLUSTER_NAME},spilo-role=master")
PG_PASSWORD=$(kubectl -n "$K8S_NS" get secret "${PG_USER}.${PG_CLUSTER_NAME}.credentials.postgresql.acid.zalan.do" -o "jsonpath={.data.password}" | base64 -d)
cat <<EOF
Cluster Name: ${PG_CLUSTER_NAME}
Master Pod: ${PG_MASTER}
Database: ${PG_DATABASE}
User: ${PG_USER}
Password: ${PG_PASSWORD}
Port Forward Command:
kubectl -n ${K8S_NS} port-forward ${PG_MASTER} 5432
psql Command:
psql postgresql://${PG_USER}:${PG_PASSWORD}@127.0.0.1:5432/${PG_DATABASE}
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment