目录
8、从外部SCM加载代码--安装插件Pipeline Remote Loader
1、可信库和不可信库
可信库:可以调用使用的java中的任意方法,jenkins的API,jenkins插件,Groovy语言等。
不可信库:被调用和使用限制的代码。运行在Groovy中。
2、内部库和外部库(共享库,全局上下文范围的流水线库)
内部库:jenkins2中包含一个Git仓库,可用于存储内部库或测试目的。放置在此库中的任何内容对于所有脚本都是可信的。有一个特定的名称:workflowLibs.git.。可以通过ssh或者http访问与git一起工作。
ssh访问:1、开启SSH端口,配置全局安全中指定SSHD端口号。
2、http:// <jenkins-url>/user/<user-id>/configure 中配置用户的公钥。填的是你要下载的服务器的公钥。然后通过git clone ssh://jenkins2@localhost:22222/workflowLibs.git下载。
外部库:存储在与jenkins分开的代码仓库中。参考“在流水线脚本中使用库”
从代码仓库获取库 :Modern SCM 和 Legacy SCM 参考官网:https://www.jenkins.io/doc/book/pipeline/shared-libraries/#legacy-scm
3、在流水线脚本中使用库
加载库到脚本中使用@Library注解,在声明式pipeline或者node脚本式路流水线的开头添加。@Library('linname[@<version>]')_ [import statement]
①如果不指定import语句,则必须在注解在;
②import未指定将导入所有的方法;
③未指定import必须在注解的末尾加上_
④ 版本可以是代码仓库的标签、分支名或者其他规范
@Library('myLib')_ // 加载库的默认版本
@Library('yourLib@2.0')_ // 指定一个库的版本
@Library('myLib@2.0') import static org.demo.Utilities.*
@Library(['my-shared-library', 'otherlib@abc1234']) _
声明流水线脚本引用库:
pipeline {
agent any
libraries {
lib("mylib@master")
lib("alib")
}
stages {
……
4、jenkins项目中的库范围
5、共享库代码结构
共享库功能有一个预定义的结构。从最高层来讲,一个共享库有三个子树:src、vars、resources。
5.1 src
此目录旨在使用标准的java目录结构的Groovy文件进行设置(即src/org/foo/bar.groovy)。当执行流水线时,它将被添加到类路中。任何groovy代码均可在此使用。
A、不包含在类中的简单方法。
// org.demo.buildUtils
package org.demo
def timedGradleBuild(tasks) {
timestamps {
sh "${tool 'gradle3.2'}/bin/gradle ${tasks}"
}
}
def myUtils = new org.demo.buildUtils()
git "<gradle project to clone>"
myUtils.timedGradleBuild("clean build")
B、创建一个封闭类(以便定义超类)
// org.demo.buildUtils
package org.demo
class buildUtils implements Serializable {
def steps
buildUtils(steps) { this.steps = steps}
def timedGradleBuild(tasks) {
// steps.tool 引用全局工具配置的gradle,后面的参数是你定义的name
def gradleHome = steps.tool 'gradle3.2'
steps.timestamps {
steps.sh "${gradleHome}/bin/gradle ${tasks}"
}
}
}
@Library('bldtools') import org.conf.buildUtils.*
def bldtools = new buildUtils(steps)
node {
git "<gradle project to clone>"
bldtools.timedGradleBuild 'clean build'
}
C、传入script对象,该对象已经可以访问所有的内容。
// org.demo.buildUtils
package org.demo
class buildUtils {
static def timedGradleBuild(script,tasks) {
def gradleHome = script.tool 'gradle3.2'
script.sh "echo Building for ${script.env.BUILD_TAG}"
script.timestamps {
script.sh "${gradleHome}/bin/gradle ${tasks}"
}
}
}
@Library('<library-name>') import static org.demo.buildUtils.*
node {
git "<gradle project to clone>"
timedGradleBuild this, 'clean build'
}
5.2 vars
此部分用来托管脚本,这些脚本定义了变量并关联了你想要在流水线中使用的方法。
创建一个包含一些方法的脚本:
// vars/timedCommand.groovy
def setCommand(commandToRun) {
cmd = commandToRun
}
def getCommand() {
cmd
}
def runCommand() {
timestamps {
cmdOut = sh (script:"${cmd}", returnStdout:true).trim()
}
}
def getOutput() {
cmdOut
}
// cmd 和 cmdOut不是字段,这些是按需创建的对象。
node {
timedCommand.cmd = 'ls -la'
echo timedCommand.cmd
timedCommand.runCommand()
echo timedCommand.getOutput()
}
// vars/timedCommand2
def call (String cmd, String logFilePath) {
timestamps {
cmdOutput = sh (script:"${cmd}", returnStdout:true).trim()
}
echo cmdOutput
writeFile file: "${logFilePath}", text: "${cmdOutput}"
}
// 调用
timedCommand2 'ls -la', 'listing.log'
传递的参数是映射的处理方法
// vars/timedCommand4.groovy
def call(body) {
// 收集赋值并传送到我们的映射中
def settings = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = settings
body()
// 现在给命令添加时间
timestamps {
cmdOutput = echo sh (script:"${settings.cmd}", returnStdout:true).trim()
}
echo cmdOutput
writeFile file: '${settings.logFilePath}', text: '${cmdOutput}'
}
node {
timedCommand4 {
cmd = 'sleep 5'
logfilePath = 'log.out'
}
}
5.3 resources
非Groovy文件可以存储在此目录中,他们可以通过数据库中的libraryResource步骤来加载。
使用方法:def detaFile = libraryResource 'org/conf/data/lib/dataFile.ext'
映射库步骤调用到src和vars
node ('worker_node1') {
stage('Source') {
git url: 'http://github.com/brentlaster/greetings.git', branch: 'demo'
}
stage('Compile') {
// 运行Gradle
library('Utilities').org.demo.BuildUtils3.timedGradleBuild this, 'clean build'
}
}
7、使用第三方库
共享库还可以通过@Grab注解来使用第三方库。允许从Maven仓库中提取任何依赖项。下面是使用ApacheCommon依赖来计算命令执行的时间。
// vars/timedCommand5
@Grab('org.apache.commons:commons-lang3:3.4+')
import org.apache.commons.lang.time.StopWatch
def call(String cmdToRun) {
def sw = new StopWatch()
def proc = "$cmdToRun".execute()
sw.start()
proc.waitFor()
sw.stop()
println( "The process took ${(sw.getTime()/1000).toString()} seconds.\n")
}
node {
timedCommand5("sleep 10")
}
8、从外部SCM加载代码--安装插件Pipeline Remote Loader
Loading a single Groovy file from Git:
stage 'Load a file from GitHub'
def helloworld = fileLoader.fromGit('examples/fileLoader/helloworld',
'https://github.com/jenkinsci/workflow-remote-loader-plugin.git', 'master', null, '')
stage 'Run method from the loaded file'
helloworld.printHello()
Loading multiple files from Git:
stage 'Load files from GitHub'
def environment, helloworld
fileLoader.withGit('https://github.com/jenkinsci/workflow-remote-loader-plugin.git', 'master', null, '') {
helloworld = fileLoader.load('examples/fileLoader/helloworld');
environment = fileLoader.load('examples/fileLoader/environment');
}
stage 'Run methods from the loaded content'
helloworld.printHello()
environment.dumpEnvVars()
9、回放外部代码和库
node {
def timestampProc = fileLoader.fromGit('jenkins/pipeline/timedCommand','https://github.com/brentlaster/utilities.git', 'master', null, '')
timestampProc.timedCommand("ls -la","command.log")
}
public timedCommand(String cmd, String logFilePath) {
timestamps {
cmdOutput = sh (script:"${cmd}", returnStdout:true).trim()
}
echo cmdOutput
writeFile file: "${logFilePath}", text: "${cmdOutput}"
}
return this;
10、深入研究可信和不可信代码
参考:https://www.jenkins.io/doc/book/pipeline/shared-libraries/#legacy-scm 讲解的很详细