Hi all,
I’m testing Pecona mongodb installed via operator in a k8s environment.
I would like to know if it’s possible and how to do it, set a script to be executed only one time when volume is created at its first time.
In docker-compose I do in this way:
volumes:
- type: bind
source: ${BASE_DOCKER}/db-init/mongodb/init.js
target: /docker-entrypoint-initdb.d/init.js
- mongodb_data:/data/db
Thanks in advance
Hi @r.gambelli and welcome to our community!
Unfortunately, in Percona Operator for MongoDB, you cannot replicate the docker-compose volumes mount in the same way. However, you can achieve the same result with an additional Kubernetes job.
-
Store the script in a ConfigMap:
kubectl create configmap my-mongo-init-script --from-file=init.js
-
Create a Job that will spin up a pod, mount the ConfigMap, and use the mongo shell to connect to your new cluster and execute the script.
apiVersion: batch/v1
kind: Job
metadata:
name: my-mongo-init-job
spec:
template:
spec:
containers:
- name: mongo-init
# Use a compatible mongo shell image
image: mongo:6.0
command:
- "/bin/sh"
- "-c"
- |
echo "Waiting for MongoDB to be ready..."
# Wait for the service to be resolvable
sleep 15
echo "Running init script..."
# Get credentials from the operator-created secret
MONGO_ROOT_USER=$(cat /etc/mongo-creds/MONGODB_ROOT_USERNAME)
MONGO_ROOT_PASSWORD=$(cat /etc/mongo-creds/MONGODB_ROOT_PASSWORD)
# Connect and run the script
# Assumes your service is named 'my-cluster-rs0'
mongosh "mongodb://${MONGO_ROOT_USER}:${MONGO_ROOT_PASSWORD}@my-cluster-rs0.myns.svc.cluster.local:27017/admin?replicaSet=rs0" < /scripts/init.js
echo "Script execution finished."
volumeMounts:
- name: script-volume
mountPath: /scripts
- name: mongo-creds-volume
mountPath: /etc/mongo-creds
readOnly: true
volumes:
- name: script-volume
configMap:
name: my-mongo-init-script
- name: mongo-creds-volume
secret:
secretName: my-cluster-secrets # <-- The secret created by the Percona operator
restartPolicy: OnFailure
backoffLimit: 4
Or something similar
Hope that helps to start. Alternatively, you could build your custom dockerimage based on Percona’s official ones - but that might be tricky to maintain that.
1 Like