From 3b175085e292f3792452db2bdf04bee5c380c39e Mon Sep 17 00:00:00 2001 From: Leo Huang Date: Thu, 21 Nov 2024 14:47:20 -0800 Subject: [PATCH] Create mongo-reset.yaml cronjob in k8 infra --- infra/base/templates/mongo-reset.yaml | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 infra/base/templates/mongo-reset.yaml diff --git a/infra/base/templates/mongo-reset.yaml b/infra/base/templates/mongo-reset.yaml new file mode 100644 index 000000000..93c6ce63b --- /dev/null +++ b/infra/base/templates/mongo-reset.yaml @@ -0,0 +1,46 @@ +apiVersion: batch/v1 +kind: CronJob +metadata: + name: reset-dev-mongo + namespace: bt +spec: + schedule: "0 0 * * *" # Daily at 12 AM + jobTemplate: + spec: + template: + spec: + containers: + - name: reset-mongo + image: alpine/k8s + command: + - sh + - -c + - | + set -e # Exit immediately if a command fails + + # Find stage and dev MongoDB pods + stage_pod=$(kubectl get pods -n bt | grep 'bt-stage-mongo' | grep -o '^[^ ]*') + dev_pod=$(kubectl get pods -n bt | grep 'bt-dev-mongo' | grep -o '^[^ ]*') + + # Dump staging MongoDB state + echo "Dumping staging MongoDB state..." + kubectl exec --namespace=bt \ + "$stage_pod" -- mongodump --archive=/tmp/stage_backup.gz --gzip + kubectl cp --namespace=bt \ + "$stage_pod:/tmp/stage_backup.gz" /tmp/stage_backup.gz + kubectl exec --namespace=bt \ + "$stage_pod" -- rm /tmp/stage_backup.gz + + # Restore dump into dev MongoDB + echo "Restoring dump into dev MongoDB..." + kubectl cp --namespace=bt \ + /tmp/stage_backup.gz "$dev_pod:/tmp/stage_backup.gz" + kubectl exec --namespace=bt \ + "$dev_pod" -- mongorestore --archive=/tmp/stage_backup.gz --gzip --drop + kubectl exec --namespace=bt \ + "$dev_pod" -- rm /tmp/stage_backup.gz + + # Cleanup local files + rm /tmp/stage_backup.gz + echo "MongoDB reset completed successfully!" + restartPolicy: Never