Skip to content
Snippets Groups Projects
Select Git revision
  • d616e1e660a2c0fbdd3b83e7aed9a179d0193595
  • main default protected
  • OZG-7981-anfrage-recipients-anzeigen
  • release
  • OZG-8252-gitlab-pipeline
  • OZG-7774-E2E
  • OZG-5120-PoC-Native-Image
  • 1.11.0
  • 1.10.0
  • 1.9.0
  • 1.8.0
  • 1.7.0
  • 1.6.0
  • 1.5.0
  • 1.4.0
  • 1.3.0
  • 1.2.1
  • 1.2.0
  • 1.1.1
  • 1.1.0
  • 1.0.0
  • 0.8.0
  • 0.7.0
  • 0.6.0
  • 0.5.0
  • 0.4.0
  • 0.3.0
27 results

Jenkinsfile

Blame
  • user avatar
    OZGCloud authored
    d1f00d88
    History
    Jenkinsfile 10.06 KiB
    pipeline {
        agent {
            node {
            label 'ozgcloud-jenkins-build-agent-jdk21'
            }
        }
    
        environment {
            RELEASE_REGEX = /\d+.\d+.\d+/
            SNAPSHOT_REGEX = /\d+.\d+.\d+-SNAPSHOT/
            FAILED_STAGE = ""
            SH_SUCCESS_STATUS_CODE = 0
            IMAGE_TAG = generateImageTag()
            HELM_CHART_VERSION = generateHelmChartVersion()
            BUILD_PROFILE = getBuildProfile()
        }
    
        options {
            timeout(time: 1, unit: 'HOURS')
            disableConcurrentBuilds()
            buildDiscarder(logRotator(numToKeepStr: '5'))
        }
    
        stages {
            stage('Check Version') {
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
                        def version = getPomVersion()
    
                        if(isReleaseBranch()){
                            if ( !(version ==~ RELEASE_REGEX) ) {
                                error("Keine Release Version für Branch ${env.BRANCH_NAME}.")
                            }
                        } else {
                            if ( !(version ==~ SNAPSHOT_REGEX) ) {
                                error("Keine Snapshot Version für Branch ${env.BRANCH_NAME}.")
                            }
                        }
                    }
                }
            }
    
            stage('Build Administration') {
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
                    }
    
                    configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                        sh 'mvn -s $MAVEN_SETTINGS clean install -Dmaven.wagon.http.retryHandler.count=3 -DelasticTests.disabled=true -Dbuild.number=$BUILD_NUMBER'
                    }
                }
            }
            
            stage('Deploy to Nexus'){
                when {
                    anyOf {
                        branch 'master'
                        branch 'release'
                    }
                }
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
                    }
                    configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                        sh 'mvn -s $MAVEN_SETTINGS -DskipTests deploy -Dmaven.wagon.http.retryHandler.count=3'
                    }
                }
            }
    
            stage('Sonar Checks') {
                when {
                    branch 'master'
                }
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
    
                        configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                            try {
                                withSonarQubeEnv('sonarqube-ozg-sh'){
                                    sh 'mvn -s $MAVEN_SETTINGS sonar:sonar'
                                }
                            } catch (Exception e) {
                                unstable("SonarQube failed")
                            }
                        }
                    }
                }
            }
    
            stage ('OWASP Dependency-Check Vulnerabilities') {
                steps {
                    dependencyCheck additionalArguments: ''' 
                        -o "./" 
                        -s "./"
                        -f "ALL" 
                        -d /dependency-check-data
                        --suppression dependency-check-supressions.xml
                        --disableKnownExploited
                        --noupdate
                        --disableArchive
                        --prettyPrint''', odcInstallation: 'dependency-check-owasp'
    
                    dependencyCheckPublisher pattern: 'dependency-check-report.xml'
                }
            }
    
            stage('Build and publish Docker image') {
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
                    }
                    
                    configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {
                            sh 'mvn -s $MAVEN_SETTINGS spring-boot:build-image -DskipTests -Dmaven.wagon.http.retryHandler.count=3 $BUILD_PROFILE -Ddocker.publishRegistry.username=${USER} -Ddocker.publishRegistry.password=${PASSWORD} -Dbuild.number=$BUILD_NUMBER'
                        }
                    }
                }
            }
            
            stage('Test, build and deploy Helm Chart') {
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
                        HELM_CHART_VERSION = generateHelmChartVersion()
    
                        dir('src/main/helm') {
                            sh "helm lint -f ../../test/helm-linter-values.yaml"
    
                            sh "helm unittest -f '../../test/helm/*.yaml' ."
    
                            sh "helm package --version=${HELM_CHART_VERSION} ."
    
                            deployHelmChart(HELM_CHART_VERSION)
                        }
                    }
                }
            }
    
            stage('Trigger Dev rollout') {
                when {
                    branch 'master'
                }
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
                        cloneGitopsRepo()
    
                        setNewDevAdministrationVersion()
    
                        pushDevGitopsRepo()
                    }
                }
            }
        }
        
        post {
            always{
                junit testResults: '**/target/surefire-reports/*.xml', skipPublishingChecks: true
            }
            failure {
                script {
                    if (isMasterBranch() || isReleaseBranch()) {
                        sendFailureMessage()
                    }
                }
            }
        }
    }
    
    
    Void deployHelmChart(String helmChartVersion) {
        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            String fileName = '@administration-' + helmChartVersion + '.tgz'
            result = sh script: '''curl -u $USERNAME:$PASSWORD https://nexus.ozg-sh.de/service/rest/v1/components?repository=''' + getHelmRepository() + ''' -F file=''' + fileName, returnStdout: true
    
            if (result != '') {
                error(result)
            }
        }
    }
    
    String getHelmRepository(){
        if (isReleaseBranch()) {
            return 'ozg-base-apps';
        }
        return 'ozg-base-apps-snapshot';
    }
    
    String generateImageTag() {
        return "${env.BRANCH_NAME}-${getPomVersion()}"
    }
    
    String getPomVersion() {
        def pom = readMavenPom file: 'pom.xml'
    
        return pom.version
    }
    
    String getBuildProfile() {
        if (isMasterBranch()) {
            return "-P dev"
        } else if (isReleaseBranch()) {
            return "-P release"
        } else {
            return ""
        }
    }
    
    
    Void sendFailureMessage() {
        def room = getRoom()
        def data = getFailureData()
    
        sh "curl -XPOST -H 'authorization: Bearer ${getElementAccessToken()}' -d '${data}' https://matrix.ozg-sh.de/_matrix/client/v3/rooms/$room/send/m.room.message"
    }
    
    String getElementAccessToken() {
        withCredentials([string(credentialsId: 'element-login-json', variable: 'LOGIN_JSON')]) {
            return readJSON ( text: sh (script: '''curl -XPOST -d \"$LOGIN_JSON\" https://matrix.ozg-sh.de/_matrix/client/v3/login''', returnStdout: true)).access_token
        }
    }
    
    String getFailureData() {
        return  """{"msgtype":"m.text", \
                        "body":"Administration: Build Failed. Stage: ${FAILED_STAGE} Build-ID: ${env.BUILD_NUMBER}", \
                        "format": "org.matrix.custom.html", \
                        "formatted_body":"Administration: Build Failed. Stage: ${FAILED_STAGE} Build-ID: ${env.BUILD_NUMBER}"}"""
    }
    
    String getRoom() {
        if (isReleaseBranch()) {
            return "!oWZpUGTFsxkJIYNfYg:matrix.ozg-sh.de"
        } else {
            return "!iQPAvQIiRwRpNOszjw:matrix.ozg-sh.de"
        } 
    }
    
    Void configureGit() {
        def email = "jenkins@ozg-sh.de"
        def name = "jenkins"
    
        dir("gitops") {
            sh "git config user.email '${email}'"
            sh "git config user.name '${name}'"
        }
    }
    
    Void cloneGitopsRepo() {
        withCredentials([usernamePassword(credentialsId: 'jenkins-gitea-access-token', passwordVariable: 'TOKEN', usernameVariable: 'USER')]) {
            sh 'git clone https://${USER}:${TOKEN}@git.ozg-sh.de/ozgcloud-devops/gitops.git'
        }
    
        configureGit()
    }
    
    Void setNewDevAdministrationVersion() {
        setNewAdministrationGitopsVersion("dev")
    }
    
    Void setNewTestAdministrationVersion() {
        setNewAdministrationGitopsVersion("test")
    }
    
    Void setNewAdministrationGitopsVersion(String environment) {
        dir("gitops") {
            def envFile = "${environment}/application/values/administration-values.yaml"
    
            def envVersions = readYaml file: envFile
    
            envVersions.administration.image.tag = IMAGE_TAG
            envVersions.administration.helm.version = HELM_CHART_VERSION
    
            writeYaml file: envFile, data: envVersions, overwrite: true
        }
    }
    
    
    Void pushDevGitopsRepo() {
        pushNewGitopsVersion('dev')
    }
    
    Void pushTestGitopsRepo() {
        pushNewGitopsVersion('test')
    }
    
    Void pushNewGitopsVersion(String environment) {
        dir('gitops') {
            if (!hasAdministrationValuesFileChanged(environment)) {
                return
            }
    
            withCredentials([usernamePassword(credentialsId: 'jenkins-gitea-access-token', passwordVariable: 'TOKEN', usernameVariable: 'USER')]) {
                sh "git add ${environment}/application/values/administration-values.yaml"
    
                sh "git commit -m 'jenkins rollout ${environment} administration version ${IMAGE_TAG}'"
                sh 'git push https://${USER}:${TOKEN}@git.ozg-sh.de/ozgcloud-devops/gitops.git'
            }
        }
    }
    
    Boolean hasAdministrationValuesFileChanged(String environment) {
        return sh (script: "git status | grep '${environment}/application/values/administration-values.yaml'", returnStatus: true) == env.SH_SUCCESS_STATUS_CODE as Integer
    }
    
    Boolean isMasterBranch() {
        return env.BRANCH_NAME == 'master'
    }
    
    Boolean isReleaseBranch() {
        return env.BRANCH_NAME == 'release'
    }
    
    String generateHelmChartVersion() {
        def chartVersion = getPomVersion()
    
        if (isMasterBranch()) {
            chartVersion += "-${env.GIT_COMMIT.take(7)}"
        }
        else if (!isReleaseBranch()) {
            chartVersion += "-${env.BRANCH_NAME}"
        }
    
        return chartVersion.replaceAll("_", "-")
    }