Skip to content

Instantly share code, notes, and snippets.

@nikneroz
Last active August 27, 2024 13:20
Show Gist options
  • Save nikneroz/498a527237dcc1d653b7f8dbb794bd6d to your computer and use it in GitHub Desktop.
Save nikneroz/498a527237dcc1d653b7f8dbb794bd6d to your computer and use it in GitHub Desktop.
Rails Jenkins Kubernetes Database Migration
apiVersion: batch/v1
kind: Job
metadata:
  name: app-api-migrate-job
  namespace: app
spec:
  template:
    spec:
      containers:
      - name: main
        image: dev4cozy/app:api
        command: ["/bin/sh", "-c"]
        args: ["bin/rails db:migrate"]
        env:
        - name: RAILS_ENV
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: RAILS_ENV
        - name: RAILS_MASTER_KEY
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: RAILS_MASTER_KEY
        - name: POSTGRES_HOST
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: POSTGRES_HOST
        - name: POSTGRES_DB
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: POSTGRES_DB
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: POSTGRES_USER
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: POSTGRES_PASSWORD
      restartPolicy: Never
        stage('Run Database Migrations') {
            steps {
                container('kubectl') {
                    withCredentials([file(credentialsId: 'k8s-config', variable: 'KUBECONFIG')]) {
                        script {
                            // Ensure the job doesn't already exist
                            sh 'kubectl delete job squadefi-api-migrate-job --ignore-not-found=true -n squadefi'
                            // Apply the job definition
                            sh 'kubectl apply -f .helmcharts/k8s/squadefi-api-migrate-job.yaml'
                            // Wait for the job to complete
                            sh 'kubectl wait --for=condition=complete job/squadefi-api-migrate-job -n squadefi'
                            // Clean up the job after completion
                            sh 'kubectl delete job squadefi-api-migrate-job -n squadefi'
                        }
                    }
                }
            }
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment