Search code examples
jenkinsjenkins-pipelinemultibranch-pipeline

Jenkins Multibranch Jenkinsfile with different options


I am trying to apply different pipeline configurations depending on the branch name, mainly with the use of the "discard old builds" option. Is there any documentation on this? Can this be done? i am thinking something like this:

pipeline {
  agent any
  options {
    disableConcurrentBuilds()
    if (env.BRANCH_NAME.contains('release-')) {
      buildDiscarder(logRotator(numToKeepStr: '20', daysToKeepStr: '365'))
    } else if (env.BRANCH_NAME == 'master') {
      buildDiscarder(logRotator(numToKeepStr: '20', daysToKeepStr: '90'))
    } else {
      buildDiscarder(logRotator(numToKeepStr: '10', daysToKeepStr: '20'))
    }
  ...
}

Solution

  • It's best to define options for buildDiscarder in the multibranch job file, there you can define your options per type of branch. The following link is shows a job file in yaml format, ours were in groovy format, but you'll get the picture:

    Jenkins Specific Build Discarders per branch

    Anything else is declared within the Jenkinsfile, like this example:

    pipeline {
      agent {
        kubernetes {
            defaultContainer 'app-cicd'
            yamlFile 'app-jenkins/jobs/app-cicd-pipeline/cicd-build-k8s.yaml'
        }
      }
      parameters {
        string(name: 'NAME', defaultValue: 'lodger', description: 'Name for App deployment')
      }
      options {
        ansiColor('xterm')
        gitLabConnection("gitlab")
      }
      environment {
        GOLDEN_AMI_VERSION = "Linux-RHEL8-Golden-AMI*"
        DEPLOY_ENVIRONMENT = "cicd"
        SUPER_ENV = "nonprod"
        DEV_ROLE_ACCOUNT = "098765432109"
        VAULT_ADDR = "https://vault.nonprod.test:8200"
        NAME = "${params.NAME}"
      }
      stages {
        stage('Compile') {
          steps {
            dir('app-web-app-jee7') {
              script {
                pom = readMavenPom file: 'pom.xml'
                env.newVersion = pom.version.substring(0,3) + "." + env.BUILD_NUMBER + "." + env.GIT_COMMIT + ".app-cicd"
    
                sh """
                    echo "Build Version is ${newVersion}"
                    mvn -s /home/jenkins/.m2/settings.xml -f pom.xml versions:set -DnewVersion=\"${newVersion}\"
                    mvn -s /home/jenkins/.m2/settings.xml -f pom.xml -B compile
                """
              }
            }
          }
        }
        stage('Unit Test') {
          steps {
            dir('app-web-app-jee7') {
              lock('unit-test') {
                script {
                    try {
                      sh "mvn -s /home/jenkins/.m2/settings.xml -f pom.xml -B install"
                    } finally {
                        step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
                    }
                      step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
                }
              }
            }
          }
        }
        stage('Publish to Repo') {
          when {
            branch 'develop'
          }
          steps {
            withVault([vaultSecrets: nexus_secret]) {
              dir('app-web-app-jee7') {
                script {
                  sh """
                      mvn -s /home/jenkins/.m2/settings.xml -f pom.xml -B deploy -DskipTests -Dnexus.repo.username=\"${NEXUS_USERNAME}\" -Dnexus.repo.password=\"${NEXUS_PASSWORD}\"
                  """
                }
              }
            }
          }
        }
        stage('Sonar Analysis') {
          steps {
            withSonarQubeEnv('SonarQubeServer') {
              dir('app-web-app-jee7') {
                script {
                  sh """
                      mvn -s /home/jenkins/.m2/settings.xml -f pom.xml sonar:sonar -Dsonar.dependencyCheck.reportPath=target/dependency-check-report.xml -Dsonar.dependencyCheck.htmlReportPath=target/dependency-check-report.html
                  """
                }
              }
            }
          }
        }
        stage('Build Deploy Repo') {
          when {
            branch 'develop'
          }
          steps {
            dir('app-release') {
              script {
                sh """
                    echo \"app_version=${newVersion}\" > gradle.properties
                    sh './bin/build-repository.sh'
                """
              }
            }
          }
        }
        stage('AMI Build') {
          when {
            branch 'develop'
          }
          steps {
            dir('packer') {
              withAWS(role: 'TerraformBuild', roleAccount: '1234567489123', roleSessionName: 'Jenkins') {
                script {
                    env.APP_VERSION = "${newVersion}"
                    env.APP_AMI_VERSION = "APP-AMI-${APP_VERSION}"
                    sh """
                        export JENKINS_PACKER_IP=\$(curl -fs http://100.200.100.000/latest/meta-data/local-ipv4)
                        export APP_AMI_VERSION=${APP_AMI_VERSION}
                        export GOLDEN_AMI_VERSION=${GOLDEN_AMI_VERSION}
                        export APP_VERSION=${APP_VERSION}
                        packer build AppPacker.json
                    """
                }
              }
            }
          }
        }
        stage('Terraform Plan and Apply') {
          when {
            branch 'develop'
          }
          steps {
            withVault([vaultSecrets: awsCredentials]) {
              withVault([vaultSecrets: vault_secret]) {
                dir('terraform') {
                  lock("app-${DEPLOY_ENVIRONMENT}-${params.NAME}-deploy") {
                    withAWS(role: 'WFDeploymentRole', roleAccount: '123456789012', roleSessionName: 'Jenkins') {
                      withCredentials([sshUserPrivateKey(credentialsId: 'gitlab-ssh-jenkins', keyFileVariable: 'keyfile')]) {
                        sh """
                            export GIT_SSH_COMMAND="ssh -i $keyfile -o StrictHostKeyChecking=no"
                            export VAULT_TOKEN=\$(vault login -token-only -method=aws region=eu-west-2)
                            terraform init\
                            -backend-config "key=workflow/app/${DEPLOY_ENVIRONMENT}/${params.NAME}/terraform.tfstate"
                            terraform plan -out terraform-plan -var-file="nonprod-${DEPLOY_ENVIRONMENT}.tfvars" -var-file="lodger/${NAME}.tfvars" -var="app_version=${APP_VERSION}" -var="app_ami_version=${APP_AMI_VERSION}"
                            export VAULT_TOKEN=\$(vault login -token-only -method=aws region=eu-west-2)
                            terraform apply terraform-plan
                        """
                      }
                    }
                  }
                }
              }
            }
          }
        }
        stage('AMI Cleaner') {
          when {
            branch 'develop'
          }
          steps {
            withAWS(role: 'TerraformBuild', roleAccount: '098765432109', roleSessionName: 'Jenkins') {
              // Remove AMIs older than 30 days AND keep last 5
              sh 'export AWS_DEFAULT_REGION=eu-west-2 && amicleaner --mapping-key name --mapping-values app-atos-cicd --full-report --keep-previous 5 --ami-min-days 30 -f'
            }
          }
        }
      }
      post {
        always {
            publishHTML (target: [
                allowMissing:true,
                alwaysLinkToLastBuild: true,
                keepAll: true,
                reportDir: 'app-web-app-jee7/target',
                reportFiles: 'dependency-check-report.html',
                reportName: "Dependency Check Report"
            ])
            cleanWs()
        }
        success {
            updateGitlabCommitStatus name: 'build', state: 'success'
                script{
                    if (currentBuild.previousBuild != null && currentBuild.previousBuild.result == 'FAILURE') {
                        slackSend (channel: '#jenkins-alerts', color: "#00FF00", message: "CICD Branch: ${BRANCH_NAME} build Fixed: " + env.BUILD_URL + " time: " + new Date())
                    } else
                        slackSend (channel: '#jenkins-alerts', color: "#00FF00", message: "CICD Branch: ${BRANCH_NAME} build Success: " + env.BUILD_URL + " time: " + new Date())
                }
        }
        failure {
            updateGitlabCommitStatus name: 'build', state: 'failed'
                script {
                    slackSend (channel: '#jenkins-alerts', color: "#FF0000", message: "CICD Branch: ${BRANCH_NAME} build Failed: " + env.BUILD_URL + " time: " + new Date())
                }
        }
        aborted {
            updateGitlabCommitStatus name: 'build', state: 'canceled'
                script {
                    slackSend (channel: '#jenkins-alerts', color: "#FFFF00", message: "CICD Branch: ${BRANCH_NAME} build Aborted: " + env.BUILD_URL + " time: " + new Date())
                }
        }
      }
    }
    currentBuild.description = "Application version: ${newVersion}"