持續集成:Jenkins pipeline全局變量


在編寫Jenkins Pipeline腳本時,需要使用到一些全局變量,比如環境變量jenkins URL、項目地址,保存在env變量中(字符串類型),可以在Jenkins Pipeline或者其它Jenkinsfile中使用這些變量。本文介紹jenkins 中env、params、currentBuild和manager這幾種全局變量。

Jenkins 全局變量

Jenkins平台支持的全局變量可通過地址${JENKINS_URL}/pipeline-syntax/globals 訪問。主要包括以下全局變量:

  • env:在groovy代碼和 Jenkins pipeline中以 env.VARNAME 或直接以 VARNAME 的形式訪問環境變量。
  • params:將構建中定義的所有參數公開為具有不同類型值的只讀映射,通過params來訪問。
  • currentBuild:顧名思義,它處理Jenkins管道當前正在運行的構建。
  • managerGroovy Postbuild插件提供的全局變量。
  • docker:這是為了在一個Groovy腳本的Jenkins管道中提供方便的訪問docker相關函數。

下面來舉例說明如何使用。

下面的示例中,groovy腳本在Pipeline 共享庫中編寫,pipeline腳本直接在pipeline工程的pipeline輸入框中編寫。pipeline共享庫的定義可以參考 持續集成:Jenkins Pipeline共享庫定義和使用

env

查看環境變量

可通過多種方式查看jenkins可使用的環境變量:

  1. 訪問:${JENKINS_URL}/pipeline-syntax/globals
  2. 訪問:${JENKINS_URL}/env-vars.html/
  3. 使用windows bat命令:set
  4. 使用Linux/Unix shell命令:printenv

bat和shell命令可以在pipeline中編寫:

pipeline{
    agent {
        label "master"
        }
    stages{
		stage('Parallel Stage') {
		parallel {
		stage('windows') {
			agent {
				label "win_agent"
			}
			steps {
				bat 'set'  
			}
		}
		stage('linux') {
			agent {
				label "linux_agent"
			}
			steps {
				sh 'printenv' 
			}
		}
	}    
   }
   }
}

由於打印內容較多,這里就不展示結果了。這兩個命令除了返回jenkins平台的環境變量外,還會打印對應代理節點的環境變量。

使用環境變量

可以以 env.VARNAME 或直接以 VARNAME 的形式訪問環境變量。

pipeline腳本:

// @Library('pipelinelibs2@main')   // Github庫 
@Library('pipelinelibs@1.0') _   // SVN庫

import com.hiyongz.MyLib

def mylib = new MyLib();

mylib.getJenkinsHome();

println "${JENKINS_HOME}";
println "${env.JENKINS_HOME}";

MyLib.groovy:

def getJenkinsHome(){
	println "${JENKINS_HOME}";
	println "${env.JENKINS_HOME}";
}

構建結果日志:

[Pipeline] echo
/var/jenkins_home
[Pipeline] echo
/var/jenkins_home
[Pipeline] echo
/var/jenkins_home
[Pipeline] echo
/var/jenkins_home
[Pipeline] End of Pipeline
Finished: SUCCESS

創建環境變量

除了讀取環境變量外,也可以對環境變量進行賦值或者創建新的環境變量。聲明環境變量可以使用以下3種方式:

  1. withEnv(["VARIABLE_NAME=value"]) {} , 腳本式流水線語法,可以覆蓋任何環境變量。
  2. env.VARIABLE_NAME :只能覆蓋以env.VARIABLE_NAME的方式創建的環境變量。
  3. environment { } ,聲明式流水線語法,不能以env.VARIABLE_NAME的方式覆蓋。

pipeline腳本:

// @Library('pipelinelibs2@main')   // Github庫 
@Library('pipelinelibs@1.0') _   // SVN庫

import com.hiyongz.MyLib

def mylib = new MyLib();

env.MY_VERSION = '1.0'
mylib.myEnv();
println "MY_VERSION = ${MY_VERSION}";
println "MY_VERSION = ${env.MY_VERSION}";

pipeline{
    agent {
        label "master"
    }
	environment {
        ENV1 = "env1"
    }
    stages{	
	stage("Env Test") {
		environment {
			ENV1 = "env1_1" // 覆蓋environment{}塊創建的環境變量
			BUILD_NUMBER = "666" // 可以覆蓋以`env.VARIABLE_NAME`方式賦值的環境變量。
			
		}
		steps {
			println "ENV1 = ${env.ENV1}";
			println "BUILD_NUMBER = ${env.BUILD_NUMBER}";
			
			script {
				env.MY_VERSION = "2.0" // env.MY_VERSION會被覆蓋
				env.ENV1 = "env1_2"		// env.ENV1不會被覆蓋
			}
			
			println "ENV1 = ${env.ENV1}";
			println "MY_VERSION = ${env.MY_VERSION}";

			withEnv(["ENV1=env1_3"]) { // env.ENV1會被覆蓋
				echo "ENV1 = ${env.ENV1}"
			}
		}
	}
	}
}

MyLib.groovy:

def myEnv(){
	println "MY_VERSION = ${env.MY_VERSION}";
	println "MY_VERSION = ${MY_VERSION}";
}

構建結果日志:

MY_VERSION = 1.0
MY_VERSION = 1.0
MY_VERSION = 1.0
MY_VERSION = 1.0
ENV1 = env1_1
BUILD_NUMBER = 666
ENV1 = env1_1
MY_VERSION = 2.0
ENV1 = env1_3

新創建的環境變量在groovy也可以通過如下方式獲取:

def myEnv(){
	def jobVariables = currentBuild.getBuildVariables();
	println "${jobVariables.MY_VERSION}";
}

在pipeline script中創建的環境變量只能在當前pipeline工程中生效,如果想要設置全局環境變量,可以在jenkins系統配置中進行配置。

進入【Manage Jenkins】-> 【Configure System】-> 【Global properties】,新增環境變量,這里設置的環境變量是全局生效的。

params

對於參數的讀取可以使用params來訪問,groovy腳本中可以使用params.get()env.getProperty()方法來獲取:

def ParamDemo(){
	def deploy_env = params.get("DEPLOY_ENV") // or: params."${paramName}"
	println "DEPLOY_ENV = ${deploy_env}";
	
	def debug_build = env.getProperty("DEBUG_BUILD")
	println "DEBUG_BUILD = ${debug_build}";
}

pipeline腳本如下:

// @Library('pipelinelibs2@main')   // Github庫 
@Library('pipelinelibs@1.0') _   // SVN庫

import com.hiyongz.MyLib
def mylib = new MyLib();

pipeline{
    agent {
        label "master"
    }
    parameters {
        string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '') 
        text(name: 'DEPLOY_TEXT', defaultValue: 'One\nTwo\nThree\n', description: '') 
        booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '')
        choice(name: 'CHOICES', choices: ['one', 'two', 'three'], description: '')
        password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'A secret password')
    }
    stages{	
	stage("Param Test") {
		steps {
		    script {
			println "DEPLOY_ENV = ${params.DEPLOY_ENV}";
            mylib.ParamDemo();
		    }			
		}
	}
	}
}

構建結果:

DEPLOY_ENV = staging
[Pipeline] echo
DEPLOY_ENV = staging
[Pipeline] echo
DEBUG_BUILD = true

currentBuild

currentBuild變量可以用來獲取當前構建的一些屬性,比如absoluteUrl、projectName、result等,更多支持的屬性方法可以訪問:${JENKINS_URL}/pipeline-syntax/globals

pipeline{
    agent {
        label "master"
    }
    stages{	
	stage("Param Test") {
		steps {
		    script {
			    println "build number: ${currentBuild.number}";
			    println "current result: ${currentBuild.currentResult}";
			    println "build URL: ${currentBuild.absoluteUrl}";
		    }			
		}
	}
	}
}

manager

manager是Groovy Postbuild插件提供的全局變量,用於構建后操作,它是在jenkins JVM 中執行groovy腳本。可用來更改構建結果,顯示構建摘要信息等,下面來舉幾個例子。

1、addShortText方法

語法:addShortText(text, color, background, border, borderColor)

pipeline {
    agent {
        label 'master'
    } 
    stages {
        stage('manager usage') {
            steps {
                script {
                    manager.addShortText("hello world",'black','lightgreen','5px','yellow')
                    currentBuild.description = "Foreground: black\n"
                    currentBuild.description += "Background: lightgreen\n"
                    currentBuild.description += "Border size: 5px\n"
                    currentBuild.description += "Border color: yellow" 
                }
            }
        }
    }
}

效果如下圖:

2、添加徽章圖標

添加刪除圖標相關方法:

  • addBadge(icon, text)
  • addBadge(icon, text, link)
  • addWarningBadge(text)
  • addErrorBadge(text)
  • addHtmlBadge(html)
  • removeBadges()
  • removeBadge(index)

還可以設置構建結果:

  • buildUnstable() - 設置構建結果為 UNSTABLE.
  • buildFailure() -設置構建結果為 FAILURE.
  • buildSuccess() - 設置構建結果為 SUCCESS.

pipeline腳本舉例:

pipeline {
    agent {
        label 'master'
    } 
    stages {
        stage('manager usage') {
            steps {
                script {
                    echo "buildFailure test"
                }
            }
        }
    }
    post {
        always {
            script {
                if(manager.logContains(".*buildFailure.*")) {
                    manager.addWarningBadge("build Failure.")
                    manager.buildFailure()
                }                
                if(manager.build.result.isBetterOrEqualTo(hudson.model.Result.UNSTABLE)) {
                    manager.addBadge("success.gif", "success")
                } else {
                    manager.addBadge("error.gif", "failed")
                }
                manager.addBadge("text.gif", "console output","${currentBuild.absoluteUrl}/console")
            }
        }
            
    }
}

構建效果圖:

注意Groovy Postbuild 在2.0版本以后引入了 Script Security Plugi,對一些非白名單方法(比如上述腳本使用到的logContains、build方法)需要管理員同意,可以進入【Manage Jenkins】 > 【In-process Script Approval】同意相關方法:

參考資料:

  1. https://plugins.jenkins.io/groovy-postbuild/
  2. https://javadoc.jenkins-ci.org/index-core.html
--THE END--

欲忘忘未得,欲去去無由。——唐·白居易 《寄遠》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM