如何使用Jenkins的Pipeline与Jenkinsfile结合实现自动化部署

来源:互联网 发布:ps4适合女生的游戏知乎 编辑:程序博客网 时间:2024/06/07 04:03

说明

在刚开始使用Jenkins的时候,大部分的使用方式都是采用FreeStyle进行构建自动化部署的配置,但是随着业务的不断增加与变化也要创建N多个Job来进行管理,甚至当服务器环境迁移之类的事情产生之后发现这种管理方式太过于低效,需要手工来维护这些大量的配置信息,并且相关配置一旦改过之后无法追溯到某个版本,还有脚本的灵活度也不高,所以后来研究使用Pipeline的方式创建Job,然后创建Jenkinsfile文件跟随项目仓库存放,这样灵活度与可追溯性大大加强,利于自动化部署更上一层台阶。

注意:此篇文档针对的是Jenkins 2.46.2 版本下进行撰写的,不同的版本可能有些步骤需要举一反三进行处理。

防爬虫专用,作者的主要博客地址:点击这里, 全路径:blog.csdn.net/littlebrain4solving。

Pipeline 示例结构

以下给出了基础结构,在此结构中定义了整个自动构建的流程,以及我们使用agent来指定了在哪个节点运行。

pipeline {    agent any    stages {        stage("Build") {            steps {                sh 'Hello World'            }        }    }    post {        always {            sh 'Hello World'        }    }}

分支checkout

由于我们在配置Pipeline的时候需要指定SCM版本仓库地址,所以在Jenkinfiles中无需再次指定,只需要执行下面这行命令就可以了。

checkout scm

wrap用法

在FreeStyle中,通过Build Environment一系列Checkbox的方式进行管理设置,在Jenkinsfile中我们可以利用wrap进行替代,参考以下片段,注意:插件需要支持继承SimpleBuildWrapper

wrap([$class: 'TestInProgressBuildWrapper']) {    sh '''        mvn test    '''}

自定义此插件注意:继承了SimpleBuildWrapper的插件必须要实现Serializable接口,如果有些无法序列化的则需要在成员变量加transient修饰,如:SocketIO有关的是无法被序列化的,切记!

step用法

在FreeStyle Build过程中,我们利用step来进行执行相关步骤,注意:插件需要支持继承SimpleBuildStep类。

step([$class: 'Publisher', reportFilenamePattern: '**/testng-results.xml'])

环境变量

在Build的时候如何获取变量,这个很简单,只需要通过${}进行获取即可,当然也支持写成$XXX,两种方式皆可,更多变量可以参考文档:点击这里。

sh '${BUILD_ID}'

工具使用

在执行相关命令的时候要先确保是否存在这个命令,这个时候在脚本中需要使用tools来指定预先在全局工具配置与系统配置中配置好的工具名称;预设置位置在:(Manage Jenkins > Global Tool Configuration > JDK)中。

tools {    jdk "8u91"}

完整示例

下列这段示例主要围绕自动化测试展开的配置,利用MAVEN来运行测试用例并查看实时运行状态并把结果信息通过报告界面展示出来。

pipeline {    agent { node { label "agent-2" } }    tools {        jdk "8u91"        maven "3.3.9"    }    stages {        stage("Build") {            steps {                wrap([$class: 'TestInProgressBuildWrapper']) {                    checkout scm                    sh '''                        echo "PATH = ${PATH}"                        echo "M2_HOME = ${M2_HOME}"                        mvn test                    '''                }            }        }    }    post {        always {            step([$class: 'Publisher', reportFilenamePattern: '**/testng-results.xml'])        }   }}

创建Job接口

Jenkins提供了API方便我们利用代码调用来创建Job,地址:http://xxx/createItem?name=$jobname,注意是POST提交。并且’Content-Type’必须是application/xmlBodyXML格式内容,如果创建的Job要在某个View下面就可以利用地址:http://xxx/view/$viewname/createItem?name=$jobname创建就可以了。

提示:这段XML格式可以从Jenkins的目录($JENKINS_HOME/job/xxx)中获取借鉴。

BRANCH_NAME="test" && XML_DATA="<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?> \                <flow-definition plugin=\\"workflow-job@2.11\\"> \                  <description></description> \                  <keepDependencies>false</keepDependencies> \                  <properties> \                    <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty> \                      <triggers/> \                    </org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty> \                  </properties> \                  <definition class=\\"org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition\\" plugin=\\"workflow-cps@2.30\\"> \                    <scm class=\\"hudson.plugins.git.GitSCM\\" plugin=\\"git@3.3.0\\"> \                      <configVersion>2</configVersion> \                      <userRemoteConfigs> \                        <hudson.plugins.git.UserRemoteConfig> \                          <url>https://gitlab.xxxx.com/xxx/autotester.git</url> \                          <credentialsId>049ef8c4-d01c-4304-b1eb-22d26ef26a8e</credentialsId> \                        </hudson.plugins.git.UserRemoteConfig> \                      </userRemoteConfigs> \                      <branches> \                        <hudson.plugins.git.BranchSpec> \                          <name>*/${BRANCH_NAME}</name> \                        </hudson.plugins.git.BranchSpec> \                      </branches> \                      <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations> \                      <submoduleCfg class=\\"list\\"/> \                      <extensions/> \                    </scm> \                    <scriptPath>Jenkinsfile</scriptPath> \                    <lightweight>true</lightweight> \                  </definition> \                  <triggers/> \                  <disabled>false</disabled> \                </flow-definition>" && curl -u username:password -H "Content-Type: application/xml" -XPOST https://jenkins.xxx.com/createItem?name=${BRANCH_NAME} -d "${XML_DATA}"

相关文档

https://jenkins.io/doc/book/pipeline/
https://jenkins.io/doc/pipeline/steps/

阅读全文
0 0
原创粉丝点击