Issue
I created 2 Kubernetes cronjobs. 1 cronjob for backups the Mariradb and the second cronjob backups the PostgreSQL. mariradb
apiVersion: batch/v1
kind: CronJob
metadata:
name: deploy-cron-job-mariadb
spec:
schedule: "0 0 * * *"
jobTemplate:
spec:
template:
metadata:
labels:
cj2job: cronjob
spec:
serviceAccountName: cron-user
volumes:
- name: deploy-script
configMap:
name: deploy-script
containers:
- name: cron-job-mariadb-1
image: bitnami/kubectl
env:
- name: mariadb-user
value: "bla"
- name: mariadb-password
value: "bla"
command: ["bash", "/var/backups/deployScript.sh"]
volumeMounts:
- name: deploy-script
mountPath: /var/backups
restartPolicy: OnFailure
ttlSecondsAfterFinished: 60
apiVersion: batch/v1
kind: CronJob
metadata:
name: deploy-cron-job-postgresql
spec:
schedule: "0 0 * * *"
jobTemplate:
spec:
template:
metadata:
labels:
cj2job: cronjob
spec:
serviceAccountName: cron-user
volumes:
- name: deploy-script
configMap:
name: deploy-script
containers:
- name: cron-job-postgresql-1
image: bitnami/kubectl
env:
- name: postgresql-user
value: "bla"
- name: postgresql-password
value: "bla"
command: ["bash", "/var/backups/deployScript.sh"]
volumeMounts:
- name: deploy-script
mountPath: /var/backups
restartPolicy: OnFailure
ttlSecondsAfterFinished: 60
I have an ansible playbook that deploys these 2 cronjob files : ansible playbook
And just the second deployment is mount to the /var/backups directory, in this case, the PostgreSQL but if the Mariradb was the second one so his backups were in the directory
If I run the kubectl apply command manually on the file it will work, but I want to do it with my ansible playbook automatically.
Solution
Solution:
backups.sh file (backups script):
#!/bin/bash
date=$(date '+%Y-%m-%d')
kubectl exec -it postgres-0 -n blabla -- bash -c "PGPASSWORD="postgres" pg_dump -U postgres -h 127.0.0.1 -p 5432 dealer > /var/backups/postgresql.sql1"
kubectl exec -it postgres-0 -n blabla -- bash -c "mv /var/backups/postgresql.sql1 /var/backups/postgresql-$date.sql1"
kubectl cp postgres-0:/var/backups/postgresql-$date.sql1 /var/backups/postgresql-$date.sql1 -n blabla
kubectl exec -it mariadb-0 -n blabla -- bash -c "mysqldump monitor -u root -p123456 > /var/backups/mysql.dump"
kubectl exec -it mariadb-0 -n blabla -- bash -c "mv /var/backups/mysql.dump /var/backups/mysql-$date.dump"
kubectl cp mariadb-0:/var/backups/mysql-$date.dump /var/backups/mysql-$date.dump -n blabla
cronjobs.sh file (4 last files in the folder):
#!/bin/bash
cd /var/backups
ls -lt | tail -n +6 | awk '{print $9}' | xargs rm -rf
skipper.sh (scheduler):
#!/bin/bash
mv docker-playbook/files/cronjobs.sh /var/
mv docker-playbook/files/backups.sh /var/
cat <<EOF | crontab -
0 0 * * * bash /var/backups.sh
0 1 * * * bash /var/cronjobs.sh
EOF
Answered By - Adi Ben David Answer Checked By - David Marino (WPSolving Volunteer)