Skip to content
Snippets Groups Projects
Jenkinsfile 13.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • OZGCloud's avatar
    OZGCloud committed
    pipeline {
    
    OZGCloud's avatar
    OZGCloud committed
        agent {
            node {
    
    OZGCloud's avatar
    OZGCloud committed
                label 'ozgcloud-jenkins-build-agent'
    
    OZGCloud's avatar
    OZGCloud committed
            }
    
    OZGCloud's avatar
    OZGCloud committed
        }
    
    
        environment {
    
            BLUE_OCEAN_URL = "https://jenkins.infra.ozg-cloud.systems/job/alfa/job/${env.BRANCH_NAME}/${env.BUILD_NUMBER}/"
    
            RELEASE_REGEX = /\d+.\d+.\d+/
            SNAPSHOT_REGEX = /\d+.\d+.\d+-SNAPSHOT/
    
    OZGCloud's avatar
    OZGCloud committed
            FAILED_STAGE = ""
    
    OZGCloud's avatar
    OZGCloud committed
            SH_SUCCESS_STATUS_CODE = 0
    
    OZGCloud's avatar
    OZGCloud committed
        options {
            timeout(time: 1, unit: 'HOURS')
            disableConcurrentBuilds()
    
    OZGCloud's avatar
    OZGCloud committed
            buildDiscarder(logRotator(numToKeepStr: '5'))
    
    OZGCloud's avatar
    OZGCloud committed
        }
    
        stages {
    
    OZGCloud's avatar
    OZGCloud committed
            stage('Check Version') {
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
    OZGCloud's avatar
    OZGCloud committed
                        VERSION = getRootPomVersion()
    
                        def serverVersion = getParentPomVersion('alfa-server/pom.xml')
                        def clientVersion = getParentPomVersion('alfa-client/pom.xml')
    
    OZGCloud's avatar
    OZGCloud committed
    
    
    OZGCloud's avatar
    OZGCloud committed
                        if(isReleaseBranch()){
    
    OZGCloud's avatar
    OZGCloud committed
                            if ( !isReleaseVersion([VERSION, serverVersion, clientVersion]) ) {
    
    OZGCloud's avatar
    OZGCloud committed
                                error("Keine Release Version für Branch ${env.BRANCH_NAME}.")
                            }
                        } else {
    
    OZGCloud's avatar
    OZGCloud committed
                            if ( !isSnapshotVersion([VERSION, serverVersion, clientVersion]) ) {
    
    OZGCloud's avatar
    OZGCloud committed
                                error("Keine Snapshot Version für Branch ${env.BRANCH_NAME}.")
                            }
                        }
    
    OZGCloud's avatar
    OZGCloud committed
                        if( !isSameVersion([serverVersion, clientVersion], VERSION) ){
    
                            error("Versionen sind nicht identisch")
    
    OZGCloud's avatar
    OZGCloud committed
                        }
                    }
                }
            }
            stage('Client') {
                steps {
    
    OZGCloud's avatar
    OZGCloud committed
                    script {
                        FAILED_STAGE=env.STAGE_NAME
    
    OZGCloud's avatar
    OZGCloud committed
    
    
    OZGCloud's avatar
    OZGCloud committed
                        sh 'npm --version'
    
                        sh 'node --version'
    
                        dir('alfa-client') {
    
    OZGCloud's avatar
    OZGCloud committed
                            sh 'echo "registry=https://nexus.ozg-sh.de/repository/npm-proxy" >> ~/.npmrc'
    
    OZGCloud's avatar
    OZGCloud committed
                            sh 'echo "//nexus.ozg-sh.de/:_auth=amVua2luczprTSFnNVUhMVQzNDZxWQ==" >> ~/.npmrc'
    
    OZGCloud's avatar
    OZGCloud committed
    
    
    OZGCloud's avatar
    OZGCloud committed
    						sh 'npm cache verify'
    
                            sh 'npm install'
    
    OZGCloud's avatar
    OZGCloud committed
                            if (isReleaseBranch()) {
    
    OZGCloud's avatar
    OZGCloud committed
                                sh 'npm run ci-prodBuild'
                            }
                            else {
                                sh 'npm run ci-build'
                            }
        					try {
    
    OZGCloud's avatar
    OZGCloud committed
    	                        if (isMasterBranch()) {
    
    OZGCloud's avatar
    OZGCloud committed
    	                            withSonarQubeEnv('sonarqube-ozg-sh'){
    	                                sh 'npm run ci-sonar'
    
    OZGCloud's avatar
    OZGCloud committed
    	                            }
    
    	                        } else {
                                    sh 'npm run ci-test'
                                }
    
    OZGCloud's avatar
    OZGCloud committed
                            } catch (Exception e) {
                                unstable("SonarQube failed")
    
    OZGCloud's avatar
    OZGCloud committed
                            }
                        }
                    }
                }
    //            post {
    //                always{
    
    //                    junit testResults: 'alfa-client/test-report.xml', skipPublishingChecks: true
    
    OZGCloud's avatar
    OZGCloud committed
    //                }
    //            }
            }
            stage('Server') {
                steps {
                    script {
                        FAILED_STAGE=env.STAGE_NAME
    
                        IMAGE_TAG = generateImageTag()
    
    OZGCloud's avatar
    OZGCloud committed
    
    
    OZGCloud's avatar
    OZGCloud committed
                        configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
                            sh 'mvn --version'
    
                            sh "mvn -s $MAVEN_SETTINGS -pl -alfa-client clean install spring-boot:build-image -Dspring-boot.build-image.imageName=docker.ozg-sh.de/alfa:${IMAGE_TAG} -Dspring-boot.build-image.publish -Dmaven.wagon.http.retryHandler.count=3"
    
     						if (isMasterBranch()) {
    	                   		try {
    	    	                    dir('alfa-service'){
    	                                withSonarQubeEnv('sonarqube-ozg-sh'){
    	                                    sh 'mvn -s $MAVEN_SETTINGS sonar:sonar'
    	                                }
    	                            }
    	                            dir('alfa-xdomea'){
    	                                withSonarQubeEnv('sonarqube-ozg-sh'){
    	                                    sh 'mvn -s $MAVEN_SETTINGS sonar:sonar'
    	                                }
    	                            }
    	                        }
    	                        catch (Exception e) {
    	                            unstable("SonarQube failed")
    	                        }
    	                    }
    
                post {
                    always{
                        junit testResults: '**/target/surefire-reports/*.xml', skipPublishingChecks: true
                    }
                }
    
    OZGCloud's avatar
    OZGCloud committed
            }
            stage('Deploy Maven Artifacts to Nexus') {
                when {
                    anyOf {
                        branch 'master'
                        branch 'release'
                    }
                }
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
                    }
    
    OZGCloud's avatar
    OZGCloud committed
    
                    configFileProvider([configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
    
                        sh 'mvn -s $MAVEN_SETTINGS -pl -alfa-client -DskipTests deploy'
    
            stage('Tag and Push Docker Image') {
    
    OZGCloud's avatar
    OZGCloud committed
                when {
                    anyOf {
                        branch 'master'
                        branch 'release'
                    }
                }
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
    
    OZGCloud's avatar
    OZGCloud committed
                        if (isMasterBranch()) {
    
                            tagAndPushDockerImage('snapshot-latest')
    
    OZGCloud's avatar
    OZGCloud committed
                        }
    
    OZGCloud's avatar
    OZGCloud committed
                        else if (isReleaseBranch()) {
    
                            tagAndPushDockerImage('latest')
    
            stage('Test, build and deploy Helm Chart') {
                steps {
    
    OZGCloud's avatar
    OZGCloud committed
                    script {
    
                        FAILED_STAGE=env.STAGE_NAME
    
    OZGCloud's avatar
    OZGCloud committed
                        HELM_CHART_VERSION = generateHelmChartVersion()
    
    OZGCloud's avatar
    OZGCloud committed
                        dir('src/main/helm') {
                            sh "helm lint -f test-values.yaml"
    
                            sh "helm unittest -f '../../test/helm/*.yaml' -v '../../test/unit-values.yaml' ."
    
    OZGCloud's avatar
    OZGCloud committed
                            sh "helm package --version=${HELM_CHART_VERSION} ."
    
    OZGCloud's avatar
    OZGCloud committed
                            deployHelmChart(HELM_CHART_VERSION)
    
    OZGCloud's avatar
    OZGCloud committed
                        }
    
            stage('Trigger Dev rollout') {
    
    OZGCloud's avatar
    OZGCloud committed
                when {
    
    OZGCloud's avatar
    OZGCloud committed
                }
                steps {
                    script {
    
    OZGCloud's avatar
    OZGCloud committed
                        FAILED_STAGE = env.STAGE_NAME
    
    OZGCloud's avatar
    OZGCloud committed
                        cloneGitopsRepo()
    
                        setNewDevVersion()
    
    OZGCloud's avatar
    OZGCloud committed
                        pushGitopsRepo()
    
            stage('Trigger Test rollout') {
    
                when {
                    branch 'release'
                }
                steps {
                    script {
                        FAILED_STAGE = env.STAGE_NAME
    
    
    OZGCloud's avatar
    OZGCloud committed
                        cloneGitopsRepo()
    
                        setNewTestVersion()
    
    OZGCloud's avatar
    OZGCloud committed
                        pushGitopsRepo()
    
    OZGCloud's avatar
    OZGCloud committed
    
            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'
                }
            }
    
    OZGCloud's avatar
    OZGCloud committed
        }
        post {
            failure {
                script {
    
    OZGCloud's avatar
    OZGCloud committed
                    if (isMasterBranch() || isReleaseBranch()) {
    
                        sendFailureMessage()
    
    OZGCloud's avatar
    OZGCloud committed
        }
    }
    
    OZGCloud's avatar
    OZGCloud committed
    
    
    Void deployHelmChart(String helmChartVersion) {
    
        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
    
    OZGCloud's avatar
    OZGCloud committed
            if (isReleaseBranch()) {
    
    OZGCloud's avatar
    OZGCloud committed
                result = sh script: '''curl -u $USERNAME:$PASSWORD https://nexus.ozg-sh.de/service/rest/v1/components?repository=ozg-base-apps -F file=@goofy-'''+helmChartVersion+'''.tgz''', returnStdout: true
    
    OZGCloud's avatar
    OZGCloud committed
                result = sh script: '''curl -u $USERNAME:$PASSWORD https://nexus.ozg-sh.de/service/rest/v1/components?repository=ozg-base-apps-snapshot -F file=@goofy-'''+helmChartVersion+'''.tgz''', returnStdout: true
    
    OZGCloud's avatar
    OZGCloud committed
    String generateHelmChartVersion() {
        def chartVersion = "${VERSION}"
    
    OZGCloud's avatar
    OZGCloud committed
        if (isMasterBranch()) {
    
    OZGCloud's avatar
    OZGCloud committed
            chartVersion += "-${env.GIT_COMMIT.take(7)}"
        }
        else if (env.BRANCH_NAME != 'release') {
            chartVersion += "-${env.BRANCH_NAME}"
        }
    
        return chartVersion.replaceAll("_", "-")
    
    Void tagAndPushDockerImage(String newTag){
    
    OZGCloud's avatar
    OZGCloud committed
        withCredentials([usernamePassword(credentialsId: 'jenkins-nexus-login', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {
    
    OZGCloud's avatar
    OZGCloud committed
            sh 'docker login docker.ozg-sh.de -u ${USER} -p ${PASSWORD}'
    
            sh "docker tag docker.ozg-sh.de/alfa:${IMAGE_TAG} docker.ozg-sh.de/alfa:${newTag}"
            sh "docker push docker.ozg-sh.de/alfa:${newTag}"
    
        }
    }
    
    String generateImageTag() {
        def imageTag = "${env.BRANCH_NAME}-${VERSION}"
    
    
    OZGCloud's avatar
    OZGCloud committed
        if (isMasterBranch()) {
    
            imageTag += "-${env.GIT_COMMIT.take(7)}"
        }
    
        return imageTag
    }
    
    
    OZGCloud's avatar
    OZGCloud committed
    Void cloneGitopsRepo() {
    
        withCredentials([usernamePassword(credentialsId: 'jenkins-gitea-access-token', passwordVariable: 'TOKEN', usernameVariable: 'USER')]) {
    
    OZGCloud's avatar
    OZGCloud committed
            sh 'git clone https://${USER}:${TOKEN}@git.ozg-sh.de/mgm/gitops.git'
    
    OZGCloud's avatar
    OZGCloud committed
        configureGit()
    
    OZGCloud's avatar
    OZGCloud committed
    Void pushGitopsRepo() {
    
        withCredentials([usernamePassword(credentialsId: 'jenkins-gitea-access-token', passwordVariable: 'TOKEN', usernameVariable: 'USER')]) {
    
    OZGCloud's avatar
    OZGCloud committed
            dir("gitops") {
    
    OZGCloud's avatar
    OZGCloud committed
                if (hasUnpushedCommits()) {
    
    OZGCloud's avatar
    OZGCloud committed
                    sh 'git push https://${USER}:${TOKEN}@git.ozg-sh.de/mgm/gitops.git'
                }
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean hasUnpushedCommits() {
    
    OZGCloud's avatar
    OZGCloud committed
        return sh (script: "git cherry -v | grep .", returnStatus: true) == env.SH_SUCCESS_STATUS_CODE as Integer
    
    OZGCloud's avatar
    OZGCloud committed
    Void configureGit() {
    
    OZGCloud's avatar
    OZGCloud committed
        final email = "jenkins@ozg-sh.de"
        final name = "jenkins"
    
    
    OZGCloud's avatar
    OZGCloud committed
        dir("gitops") {
    
    OZGCloud's avatar
    OZGCloud committed
            sh "git config user.email '${email}'"
            sh "git config user.name '${name}'"
    
    Void sendFailureMessage() {
        def room = ''
        def data = """{"msgtype":"m.text", \
    
                        "body":"Alfa: Build Failed. Stage: ${FAILED_STAGE} Build-ID: ${env.BUILD_NUMBER} Link: ${BLUE_OCEAN_URL}", \
    
                        "format": "org.matrix.custom.html", \
    
                        "formatted_body":"Alfa: Build Failed. Stage: ${FAILED_STAGE} Build-ID: <a href='${BLUE_OCEAN_URL}'>${env.BUILD_NUMBER}</a>"}"""
    
    OZGCloud's avatar
    OZGCloud committed
        if (isMasterBranch()) {
    
            room = "!iQPAvQIiRwRpNOszjw:matrix.ozg-sh.de"
        }
    
    OZGCloud's avatar
    OZGCloud committed
        else if (isReleaseBranch()) {
    
            room = "!oWZpUGTFsxkJIYNfYg:matrix.ozg-sh.de"
        }
    
        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
        }
    
    Void setNewDevVersion() {
        setNewGitopsVersion("dev")
    
    Void setNewTestVersion() {
        setNewGitopsVersion("test")
    
    Void setNewGitopsVersion(String environment) {
    
    OZGCloud's avatar
    OZGCloud committed
        dir("gitops") {
    
            def envFile = "${environment}/application/values/goofy-values.yaml"//TODO OZG-4591
    
    OZGCloud's avatar
    OZGCloud committed
            def envVersions = readYaml file: envFile
    
    
            envVersions.goofy.image.tag = IMAGE_TAG//TODO OZG-4591
            envVersions.goofy.helm.version = HELM_CHART_VERSION//TODO OZG-4591
    
    OZGCloud's avatar
    OZGCloud committed
    
            writeYaml file: envFile, data: envVersions, overwrite: true
    
    
            if (hasValuesFileChanged(environment)) {
    
    OZGCloud's avatar
    OZGCloud committed
                sh "git add ${envFile}"
    
                sh "git commit -m 'jenkins rollout ${environment} alfa version ${IMAGE_TAG}'"
    
    OZGCloud's avatar
    OZGCloud committed
            }
    
    OZGCloud's avatar
    OZGCloud committed
        }
    
    Boolean hasValuesFileChanged(String environment) {
    
        //TODO OZG-4591
        return sh (script: "git status | grep '${environment}/application/values/goofy-values.yaml'", returnStatus: true) == env.SH_SUCCESS_STATUS_CODE as Integer
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean isReleaseBranch() {
        return env.BRANCH_NAME == 'release'
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean isMasterBranch() {
        return env.BRANCH_NAME == 'master'
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean isReleaseVersion(List versions) {
        return matchRegexVersion(versions, RELEASE_REGEX)
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean isSnapshotVersion(List versions) {
        return matchRegexVersion(versions, SNAPSHOT_REGEX)
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean matchRegexVersion(List versions, String regex) {
        for (version in versions) {
            println version
            if ( !(version ==~ regex) ) {
                return false
            }
        }
    
        return true
    
    OZGCloud's avatar
    OZGCloud committed
    Boolean isSameVersion(List versions, String expectedVersion) {
        for (version in versions) {
            if ( version != expectedVersion ) {
                return false
            }
        }
    
        return true
    
    OZGCloud's avatar
    OZGCloud committed
    String getRootPomVersion() {
        def rootPom = readMavenPom file: 'pom.xml'
        return rootPom.version
    
    OZGCloud's avatar
    OZGCloud committed
    }
    
    
    OZGCloud's avatar
    OZGCloud committed
    String getParentPomVersion(String filePath) {
        def pom = readMavenPom file: filePath
        return pom.parent.version