README
¶
Kubernetes MongoDB Primary Pod Labeler
This sidecar detects the current MongoDB replica set primary and labels Kubernetes pods so services can target the writable node.
How it works
At startup and on a 5-second timer, the sidecar:
- Queries MongoDB's
hellocommand atMONGO_ADDRESS(defaultlocalhost:27017). - Detects the primary pod name.
- Lists pods in
NAMESPACEmatchingLABEL_SELECTOR. - Patches labels:
- primary pod:
primary=true - other pods:
primary=falsewhenLABEL_ALL=true - other pods: removes
primarylabel whenLABEL_ALL=false
- primary pod:
It patches changed labels only, demoting other pods before promoting the primary.
Member hostnames must start with their pod name, for example mongo-0.mongo-cluster:27017.
Service selector example
apiVersion: v1
kind: Service
metadata:
name: mongo
spec:
selector:
role: mongo
primary: "true"
ports:
- name: mongo
port: 27017
Configuration
When running inside Kubernetes, in-cluster config is used automatically.
When running outside a cluster, kubeconfig defaults to ~/.kube/config and can be overridden with --kubeconfig.
Environment variables:
| Variable | Required | Default | Description |
|---|---|---|---|
LABEL_SELECTOR |
yes | none | Selector for all pods in one replica set (for example role=mongo). |
NAMESPACE |
no | default |
Namespace where pods are listed and patched. |
MONGO_ADDRESS |
no | localhost:27017 |
Single MongoDB endpoint, optionally prefixed with mongodb://. URI credentials and connection options are supported. SRV and multiple hosts are unsupported because the sidecar connects directly to its local member. |
MONGO_USERNAME |
no | unset | MongoDB username, supplied together with MONGO_PASSWORD. |
MONGO_PASSWORD |
no | unset | MongoDB password, supplied together with MONGO_USERNAME. Both values must be nonempty and are passed literally; do not URL-encode them. |
MONGO_AUTH_SOURCE |
no | URI source/database, then admin |
Database where the user account was created. Requires the environment credential pair. Overrides URI authSource, which otherwise takes precedence over the URI database. |
K8S_REQUEST_TIMEOUT |
no | 10s |
Timeout for Kubernetes list/patch API requests (Go duration format, for example 5s, 1m). |
LABEL_ALL |
no | false |
Boolean. If true, non-primary pods get primary=false; if false, the label is removed. |
DEBUG |
no | false |
Boolean. If true, enables debug logging. |
LABEL_ALL and DEBUG are parsed as booleans. K8S_REQUEST_TIMEOUT is parsed as a Go duration. Invalid values fail startup.
Supply MONGO_USERNAME and MONGO_PASSWORD from Kubernetes Secrets using
valueFrom.secretKeyRef; the deployment example includes commented entries.
Alternatively, supply the entire MONGO_ADDRESS from a Secret, with URI-encoded
credentials. The two inputs are mutually exclusive: when any of the three
authentication variables is set, a MONGO_ADDRESS that carries user info,
authMechanism, or authMechanismProperties fails startup, as does an
explicitly empty MONGO_AUTH_SOURCE.
Environment credentials always use the MongoDB driver's default SCRAM
negotiation; pin a mechanism through URI credentials instead. Restart the sidecar
after rotating credentials or changing Secret-backed environment variables.
MongoDB users are provisioned separately; the sidecar only runs ping and
hello, which require no database roles. Those commands are also available
without authentication, so successful primary detection alone does not prove that
credentials were configured.
Logs never carry credentials: startup reports the MongoDB host/port and whether
authentication is configured, failures report an operation, a fixed category, and
any server code, and driver logging through MONGODB_LOG_* stays suppressed even
when DEBUG=true.
Published image
Container images are published to GHCR at:
ghcr.io/combor/k8s-mongo-labeler-sidecar, for linux/amd64 and linux/arm64.
docker pull ghcr.io/combor/k8s-mongo-labeler-sidecar:0.8.5
Deployment
deployment-example.yaml provides a three-member replica-set example using MongoDB 9.0.8.
Demo only: MongoDB has no authentication or TLS;
emptyDirdata is lost when pods are removed. Configure authentication, TLS, and persistent storage for production. The NetworkPolicy limits ingress to same-namespace traffic on port 27017 only when enforced by the CNI.
Integration test (kind)
The repository includes an end-to-end test environment in test/integration.
The checked-in Kustomize overlays in test/integration/fixtures define each
scenario and share the deployment example as their base.
Prerequisites:
Use a disposable CLUSTER_NAME and dedicated KUBECONFIG; the script deletes its named cluster.
./test/integration/run.sh
Optional overrides:
CLUSTER_NAME(defaultkind-mongo-labeler)LABELER_IMAGE(defaultmongo-labeler:local)USE_PREBUILT_IMAGE(defaultfalse) — use an existing localLABELER_IMAGE; a missing image fails the testMONGO_AUTH_MODE(defaultnone) —none,env,uri, orinvalid(wrong password)MONGO_GLIBC_TUNABLES(default unset) — optionalGLIBC_TUNABLESoverride for MongoDB test containers onlyTIMEOUT(default240s) — rollout timeout; labels have a separate 180-second timeoutKEEP_CLUSTER=true(keep cluster for debugging)
The script creates a temporary kind cluster, deploys the locally built sidecar
image in a 3-pod Mongo StatefulSet, and verifies primary labels and Service
routing via EndpointSlice. It refuses to delete a pre-existing cluster with the
chosen name. When KUBECONFIG is unset, it uses a temporary kubeconfig.
The env and uri scenarios enforce MongoDB authentication using a generated
replica-set keyfile and test user, then test the respective credential inputs.
The invalid scenario starts fresh, unlabeled pods with the wrong password and
checks that every sidecar repeatedly fails authentication without patching any
labels. All scenarios run the sidecar with debug logging enabled. Sidecar logs
are scanned for the generated credentials before any diagnostics are printed;
MongoDB server logs are only matched, never printed, because they contain
usernames.
CI runs all four scenarios against the current source on pull requests and
before releases. To run an authenticated scenario locally, use
MONGO_AUTH_MODE=env CLUSTER_NAME=mongo-labeler-auth-env ./test/integration/run.sh.
Some MongoDB builds can refuse to start on newer Linux kernels due to their TCMalloc/rseq
compatibility check. On an affected host, pass the workaround the Docker image
maintainers describe, MONGO_GLIBC_TUNABLES=glibc.pthread.rseq=1, which
applies only to the test containers. See the
upstream discussion.
Run CI locally with act
The repository uses a single workflow for GitHub and local runs: .github/workflows/ci-release.yml.
Prerequisites:
Run the full workflow locally:
act -W .github/workflows/ci-release.yml
Documentation
¶
There is no documentation for this package.