pipeline常用插件用法

pipeline 常用插件语句
1、checkout SCM 可以用来下载git仓代码,还可以支持cherry pick 某个patch

    checkout([$class: 'GitSCM', branches: [[name: '*/master']],
         userRemoteConfigs: [[url: 'http://git-server/user/repository.git']]])
  • url Type: String
  • branch (optional) Type: String
  • changelog (optional) Type: boolean
  • credentialsId (optional) Type: String
  • poll (optional) Type: boolean

用法:https://jenkins.io/doc/pipeline/steps/git/
https://www.jenkins.io/doc/pipeline/steps/workflow-scm-step/

    checkout([$class: 'GitSCM', branches: [[name: "${branch}"]], doGenerateSubmoduleConfigurations: 
    	false, extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${relative_dir}"]], 
    		submoduleCfg: [], userRemoteConfigs: [[url: "${repo_url}"]]])
    checkout([$class: 'GitSCM', branches: [[name: env.GERRIT_BRANCH]], 
    	doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'RelativeTargetDirectory', 
    		relativeTargetDir: "${relative_dir}"], [$class: 'BuildChooserSetting', buildChooser: [$class: 
    			'GerritTriggerBuildChooser']]], submoduleCfg: [], userRemoteConfigs: [[refspec: 
    				env.GERRIT_REFSPEC, url: "${repo_url}"]]])
checkout([$class: 'GitSCM', branches: [[name: '*/${branch}']], doGenerateSubmoduleConfigurations: false,
                            extensions: [[$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false, timeout: 120], [$class: 'CheckoutOption', timeout: 20],[$class: 'RelativeTargetDirectory', relativeTargetDir: '${relative_dir}'], [$class: 'CleanCheckout']], 
                            submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'xxxxx-0fbb-4718-8dcd-23e99cc8ecca', 
                            url: '${repo_url}']]])

2、pipeline启动一个job,build

    build job: 'my_job', parameters: [string(name: 'name', value: liurizhou), string(name: 'age', value: 
    	12)],propagate: false,wait: false

可以获取下游的结果等信息,例如:

                    def bld = build job: "${jobName}", parameters: [ string(name: 'name', value: 'liurizhou')], propagate: false
                    def buildNumber = bld.number
                    def buildUrl = bld.absoluteUrl
                    def buildResult = bld.result
                    echo "jobName: ${jobName}, buildNumber: ${buildNumber}, buildResult: ${buildResult}, buildUrl: ${buildUrl}"

用法:https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

3、发布报告,publishHTML

    publishHTML (target: [
        allowMissing: false,
        alwaysLinkToLastBuild: false,
        keepAll: true,
        reportDir: 'info',
        reportFiles: 'manifest.html, report.html',
        reportName: "Summary Report"
    ])

用法:https://jenkins.io/doc/pipeline/steps/htmlpublisher/

4、withDockerContainer ,pipeline中启动docker镜像运行

    withDockerContainer(args: '-e "http_proxy=xxxxx" -e "https_proxy=yyyyyy" -v "/home/my/workspace:/home/my/workspace"', 
    	image: 'myimages:latest')	 {
    		sh "cd /home/my/workspace && ls -l"
    }

用法:https://jenkins.io/doc/pipeline/steps/docker-workflow/

5、emailext, pipeline中实现邮件发送

    emailext (
    	subject:"标题",
    	body:"""
    	正文
    	""",
    	to:"xxxx@126.com"  
    )

用法:https://jenkins.io/doc/pipeline/steps/email-ext/

6、manager.addBadge,在build history条目中增加标签
在这里插入图片描述

    manager.addBadge(
        "computer.png",
        "${script.env.NODE_NAME}",
        manager.hudson.getRootUrl() + "computer/" + "${nodeName}"
    )

用法:https://jenkins.io/doc/pipeline/steps/badge/
补充:manager有很多用法,例如:
manager.createSummary(“star-gold.gif”).appendText(“test test test”)
addShortText(text, color, background, border, borderColor),addInfoBadge(text)等
参见:https://wiki.jenkins.io/display/JENKINS/Groovy+Postbuild+Plugin

7、cleanWs()或者deleteDir(), 删除工作目录

    cleanWs() //删除${WORKSPACE}目录
    dir("${env.WORKSPACE}@tmp") { //删除${WORKSPACE}@tmp目录
        deleteDir()
    }
    dir("${env.WORKSPACE}@script") { //删除@script目录
        deleteDir()
    }
    dir("${env.WORKSPACE}@script@tmp") { //删除@script@tmp目录
        deleteDir()
    }

8、获取shell 命令的返回值和状态

    //获取标准输出
    //第一种
    result = sh returnStdout: true ,script: "<shell command>"
    result = result.trim()
    //第二种
    result = sh(script: "<shell command>", returnStdout: true).trim()
    //第三种
    sh "<shell command> > commandResult"
    result = readFile('commandResult').trim()
    
    //获取执行状态
    //第一种
    result = sh returnStatus: true ,script: "<shell command>"
    result = result.trim()
    //第二种
    result = sh(script: "<shell command>", returnStatus: true).trim()
    //第三种
    sh '<shell command>; echo $? > status'
    def r = readFile('status').trim()

9、归档工件 archiveArtifacts

    archiveArtifacts '*report.html'

效果同freestyle类型中Archive the artifacts 插件
https://blog.csdn.net/liqiangeastsun/article/details/79062806:
在这里插入图片描述
用法:
https://jenkins.io/doc/pipeline/steps/core/

10、withCredentials ,pipeline中避免使用密码明文

    steps{
        withCredentials([usernamePassword(credentialsId: 'user_for_openshift', passwordVariable: 'password', usernameVariable: 'username')]) {
        sh 'docker login -u $username -p $password registory.ctiwifi.cn:5000
        }
    }

用法:https://jenkins.io/doc/pipeline/steps/credentials-binding/

11、Artifactory 插件用来上传下载等操作

rtServer (
    id: "Artifactory-1",
    url: "https://XXXXXXXXXXX/artifactory",
    // If you're using username and password:
    username: "username",
    password: "password"
)
rtDownload (
    serverId: "Artifactory-1",
    spec: 
    """{
        "files": [
        {
            "pattern": "project1/temp/1.txt",
            "target": "${WORKSPACE}/dependencies/",
            "flat": "true"
        }
    ]
    }"""
)

用法:https://jenkins.io/doc/pipeline/steps/artifactory/#artifactorygradlebuild-run-artifactory-gradle
示例:
https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins
https://github.com/jfrog/project-examples/tree/master/jenkins-examples/pipeline-examples
另外还可以使用脚本试的写法:

def deps_download(list){
    def server_url="https://xxxxxxxx/artifactory"
    def server = Artifactory.newServer url: "${server_url}", username: 'username', password: 'passwd'
    server.bypassProxy = true
    for(dep_path in list){
        if(dep_path.contains(server_url)){
            dep_path = dep_path.split(server_url)[-1]
        }
        def downloadSpec = """{
                        "files": [
                        {
                            "pattern": "${dep_path}",
                            "target": "${WORKSPACE}/dependencies/",
                            "flat": "true"
                        }
                        ]
                    }"""
        server.download(downloadSpec)
    }
}

12、findFiles,readJSON等
用法:https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/

13、常用pipeline step
用法:https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#retry-retry-the-body-up-to-n-times

Table of Contents
Pipeline: Basic Steps
catchError: Catch error and set build result to failure
deleteDir: Recursively delete the current directory from the workspace
dir: Change current directory
echo: Print Message
error: Error signal
fileExists: Verify if file exists in workspace
isUnix: Checks if running on a Unix-like node
mail: Mail
pwd: Determine current directory
readFile: Read file from workspace
retry: Retry the body up to N times
sleep: Sleep
stash: Stash some files to be used later in the build
step: General Build Step
timeout: Enforce time limit
tool: Use a tool from a predefined Tool Installation
unstable: Set stage result to unstable
unstash: Restore files previously stashed
waitUntil: Wait for condition
warnError: Catch error and set build and stage result to unstable
withEnv: Set environment variables
wrap: General Build Wrapper
writeFile: Write file to workspace
archive: Archive artifacts
getContext: Get contextual object from internal APIs
unarchive: Copy archived artifacts into the workspace
withContext: Use contextual object from internal APIs within a block
  1. 设置job丢弃
    options {
        timeout(time: 60, unit: 'MINUTES')
        buildDiscarder logRotator(artifactDaysToKeepStr: '30', artifactNumToKeepStr: '100', daysToKeepStr: '30', numToKeepStr: '100')
    }
  1. d
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值