Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Declarative pipeline to create daily backups for Jenkins on Kubernetes
def configuration = [vaultUrl: "${VAULT_URL}", vaultCredentialId: "vault-app-role", engineVersion: 2]
def secrets = [
[path: 'secret/jenkins/aws', engineVersion: 2, secretValues: [
[envVar: 'AWS_ACCESS_KEY_ID', vaultKey: 'aws_access_key_id'],
[envVar: 'AWS_SECRET_ACCESS_KEY', vaultKey: 'aws_secret_access_key']]],
pipeline {
agent {
kubernetes {
label 'jenkins-backup-job'
defaultContainer 'jnlp'
yamlFile 'build-pod.yaml'
options {
timeout(time: 60, unit: 'MINUTES')
stages {
stage('Backup Jenkins'){
steps {
withVault([configuration: configuration, vaultSecrets: secrets]){
sh '''
echo 'Install kubectl'
curl -LO "\$(curl -s"
chmod +x ./kubectl
mv ./kubectl /usr/local/bin/kubectl
function get_jenkins_pod_id {
kubectl get pods -n jenkins -l -o | grep jenkins-
echo 'Create jenkins backup'
kubectl exec $(get_jenkins_pod_id) -- bash -c 'cd /var; \
rm -rf jenkins_backup; \
mkdir -p jenkins_backup; \
cp -r jenkins_home jenkins_backup/jenkins_home; \
tar -zcvf jenkins_backup/jenkins_backup.tar.gz jenkins_backup/jenkins_home'
cd && kubectl cp jenkins/$(get_jenkins_pod_id):/var/jenkins_backup/jenkins_backup.tar.gz jenkins_backup.tar.gz
echo 'Upload jenkins_backup.tar to S3 bucket'
aws s3 cp jenkins_backup.tar.gz s3://jenkins-backups/$(date +%Y%m%d%H%M)/jenkins_backup.tar.gz
echo 'Remove files after succesful upload to S3'
kubectl exec $(get_jenkins_pod_id) -- bash -c 'rm -rf /var/jenkins_backup'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment