简体   繁体   English

Jenkins Multibranch Jenkinsfile 具有不同的选项

[英]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'))
    }
  ...
}

It's best to define options for buildDiscarder in the multibranch job file, there you can define your options per type of branch.最好在多分支作业文件中定义 buildDiscarder 的选项,您可以在那里定义每种分支类型的选项。 The following link is shows a job file in yaml format, ours were in groovy format, but you'll get the picture:以下链接显示了 yaml 格式的作业文件,我们的是 groovy 格式,但您会看到图片:

Jenkins Specific Build Discarders per branch 每个分支的 Jenkins 特定构建丢弃器

Anything else is declared within the Jenkinsfile, like this example: Jenkinsfile 中声明了其他任何内容,如下例所示:

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}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM