Jenkins Multibranch Jenkinsfile 具有不同的选项
Jenkins Multibranch Jenkinsfile with different options
我正在尝试根据分支名称应用不同的管道配置,主要是使用“丢弃旧版本”选项。有这方面的文件吗?这可以做到吗?我在想这样的事情:
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'))
}
...
}
最好在多分支作业文件中为 buildDiscarder 定义选项,在那里您可以为每种类型的分支定义选项。以下 link 显示的是 yaml 格式的作业文件,我们的是 groovy 格式,但您会得到图片:
Jenkins Specific Build Discarders per branch
在 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}"
我正在尝试根据分支名称应用不同的管道配置,主要是使用“丢弃旧版本”选项。有这方面的文件吗?这可以做到吗?我在想这样的事情:
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'))
}
...
}
最好在多分支作业文件中为 buildDiscarder 定义选项,在那里您可以为每种类型的分支定义选项。以下 link 显示的是 yaml 格式的作业文件,我们的是 groovy 格式,但您会得到图片:
Jenkins Specific Build Discarders per branch
在 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}"