pipeline {
/* insert Declarative Pipeline here */
}
作用域:应用于全局最外层,表明该脚本为声明式pipeline
是否必须:必须
参数:无
pipeline {
agent {
//define agent
}
stages {
stage('阶段名称') {
steps {
//some scripts
}
}
...
}
}
运行在任意的可用节点上。
pipeline {
//运行在任意的可用节点上
agent any
stages {
stage('阶段名称:拉取代码') {
steps("步骤名称:拉取代码"){
echo '打印:拉取代码'
}
}
stage('阶段名称:编译构建') {
steps {
echo '打印:编译构建'
}
}
stage('阶段名称:项目部署') {
steps {
echo '打印:项目部署'
}
}
}
post{
always{
echo "阶段完成后动作"
}
}
}
当在全局声明agent为none时,那么每一个stage都需声明自己的agent。
运行在 指定标签名称节点上
agent {
//运行在 标签名称为my-node1的节点上
label 'my-node1'
}
除此之外label还可以与逻辑符号一同使用
agent {
label 'my-node1' && 'my-node2'
}
agent {
//运行在 标签名称为 my-node1或者my-node2 的节点上
label 'my-node1' || 'my-node2'
}
node声明运行节点,与label功能类似,但是node可以附加选项参数, 如customWorkspace
agent {
node {
label 'my-node1'
}
}
等同于
agent {
label 'my-node1'
}
agent {
node {
label 'my-node1'
// 附加选项参数
customWorkspace '/some/other/path'
}
}
agent {
docker 'maven:3.8.1-adoptopenjdk-11'
}
agent {
docker {
image 'maven:3.8.1-adoptopenjdk-11'
label 'my-defined-label'
args '-v /tmp:/tmp'
registryUrl 'https://myregistry.com/'
registryCredentialsId 'myPredefinedCredentialsInJenkins'
}
}
agent {
dockerfile true
}
agent {
// Equivalent to "docker build -f my_dockerfile --build-arg version=1.0.2 ./build_dir/
dockerfile {
filename 'my_dockerfile'
dir 'build_dir'
label 'my-defined-label'
additionalBuildArgs '--build-arg version=1.0.2'
args '-v /tmp:/tmp'
registryUrl 'https://myregistry.com/'
registryCredentialsId 'myPredefinedCredentialsInJenkins'
}
}
agent {
kubernetes {
label podlabel
yaml """
kind: Pod
metadata:
name: jenkins-agent
spec:
containers:
- name: nginx
image: nginx
"""
}
}
####示例
agent {
node {
label 'my-node1'
customWorkspace '/some/other/path'
}
}
####示例
agent {
// Equivalent to "docker build -f my_dockerfile --build-arg version=1.0.2 ./build_dir/
dockerfile {
filename 'my_dockerfile'
dir 'build_dir'
label 'my-defined-label'
additionalBuildArgs '--build-arg version=1.0.2'
args '-v /tmp:/tmp'
registryUrl 'https://myregistry.com/'
registryCredentialsId 'myPredefinedCredentialsInJenkins'
}
}
不管pipeline或stage的执行结果状态,总会执行的steps。
只有在pipeline或stage的执行结果状态与前一次执行相比发生改变时执行。
当前pipeline或stage执行成功且它的前一次执行结果是failure或unstable时执行。
当前pipeline或stage执行结果是failure,unstable或aborted且它的前一次执行成功时执行。
当前pipeline或stage执行结果是aborted(人工停止pipeline)时执行。
当前pipeline或stage执行结果是失败时执行。
当前pipeline或stage执行结果是成功时执行。
当前pipeline或stage执行结果是unstable时执行。
当前pipeline或stage执行结果不是成功时执行。
在其他所有的post场景脚本都处理完之后执行,不管当前pipeline或stage执行结果是什么。
pipeline {
agent any
stages {
stage('阶段名称:拉取代码') {
steps("步骤名称:拉取代码"){
echo '打印:拉取代码'
}
}
stage('阶段名称:编译构建') {
steps {
echo '打印:编译构建'
}
}
stage('阶段名称:项目部署') {
steps {
echo '打印:项目部署'
}
}
}
post{
always{
echo "阶段完成后动作"
}
}
}


pipeline{
agent any
stages{
stage("阶段1"){
stages{ //嵌套在stage里
stage("阶段1的内部阶段"){
steps{
echo "阶段1的内部阶段"
}
}
}
}
stage("阶段2"){
steps{
echo "阶段2"
}
}
}
}


看下运行结果,发现嵌套的stage也是能够展现在视图里面的
pipeline{
agent any
stages{
stage("阶段1"){
stages{ //嵌套在stage里
stage("阶段1的内部阶段"){
steps{
echo "阶段1的内部阶段"
}
}
}
}
stage("阶段2"){
steps{
echo "阶段2"
}
}
}
}


看下运行结果,发现嵌套的stage也是能够展现在视图里面的
该环境变量的值将会被设置为Secret Text的内容。
该环境变量的值将会被设置为临时创建的文件路径。
该环境变量的值将会被设置为username:password,并且还会自动创建两个环境变量
该环境变量的值将会被设置为临时创建的ssh key文件路径,并且还会自动创建两个环境变量
pipeline{
agent any
//声明一个全局变量或者步骤内部的局部变量
environment {
P1="参数1"
}
stages{
stage("阶段1"){
environment {
P2="参数2"
}
steps{
echo "打印P1变量:$P1"
echo "打印P2变量:$P2"
}
}
}
}

pipeline {
agent any
environment {
CC = 'clang'
}
stages {
stage('Example') {
environment {
AN_ACCESS_KEY = credentials('my-predefined-secret-text')
}
steps {
sh 'printenv'
}
}
}
}
pipeline {
agent any
stages {
stage('Example Username/Password') {
environment {
SERVICE_CREDS = credentials('my-predefined-username-password')
}
steps {
sh 'echo "Service user is $SERVICE_CREDS_USR"'
sh 'echo "Service password is $SERVICE_CREDS_PSW"'
sh 'curl -u $SERVICE_CREDS https://myservice.example.com'
}
}
stage('Example SSH Username with private key') {
environment {
SSH_CREDS = credentials('my-predefined-ssh-creds')
}
steps {
sh 'echo "SSH private key is located at $SSH_CREDS"'
sh 'echo "SSH user is $SSH_CREDS_USR"'
sh 'echo "SSH passphrase is $SSH_CREDS_PSW"'
}
}
}
}
指定build history与console的保存数量。
//只保存最近一次构建日志
options {
buildDiscarder(logRotator(numToKeepStr: '1'))
}
将源码拉取到工作空间指定的子目录下。
options {
checkoutToSubdirectory('foo')
}
不允许同时构建。
options {
disableConcurrentBuilds()
}
不允许控制器重新开始。
options {
disableResume()
}
与docker或dockerfile代理一起使用,表示每个stage都将在同一个节点里启动新容器运行而不是在同一个容器中运行。
options {
newContainerPerStage()
}
options {
overrideIndexTriggers(true)
}
当stage重新开始时,保存最近构建。
//保存最近一次完成的构建
options {
preserveStashes()
}
//保存最近5次完成的构建
options {
preserveStashes(buildCount: 5)
}
options {
quietPeriod(30)
}
失败重试次数。
options {
retry(3)
}
跳过默认代码拉取。
options {
skipDefaultCheckout()
}
当构建状态出现unstable时跳过其他stages。
options {
skipStagesAfterUnstable()
}
设置构建超时时间,超时后自动终止执行。
pipeline {
agent any
options {
timeout(time: 1, unit: 'HOURS')
}
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
设置日志输出时间戳。
options {
timestamps()
}
将所有并行stage的failfast设置为true。
options {
parallelsAlwaysFailFast()
}
pipeline{
agent any
options {
//设置日志输出时间戳
timestamps()
//不允许同时构建
disableConcurrentBuilds()
}
stages{
stage("stage1"){
options {
//设置构建超时时间,超过1分钟后自动终止执行
timeout(time:1,unit:'MINUTES')
//设置retry作用域范围的重试次数为3次
retry(2)
}
steps{
echo "====================options测试===================="
}
}
}
}

string
text
booleanParam
choice
password
pipeline{
agent any
//提供pipeline运行的参数
parameters {
//定义字符串参数,名称:P1,默认值:hello world,参数说明:打个招呼
string(name: 'P1', defaultValue: 'hello world', description: '打个招呼')
booleanParam(name: 'P2', defaultValue: true, description: 'P2')
}
stages{
stage("stage1"){
steps{
echo "打印参数P1:$P1"
echo "打印参数P2:$P2"
}
}
}
}
####自动生成的构建参数


pipeline {
agent any
parameters {
string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
text(name: 'BIOGRAPHY', defaultValue: '', description: 'Enter some information about the person')
booleanParam(name: 'TOGGLE', defaultValue: true, description: 'Toggle this value')
choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'Enter a password')
}
stages {
stage('Example') {
steps {
echo "Hello ${params.PERSON}"
echo "Biography: ${params.BIOGRAPHY}"
echo "Toggle: ${params.TOGGLE}"
echo "Choice: ${params.CHOICE}"
echo "Password: ${params.PASSWORD}"
}
}
}
}

定时器触发。
//每隔4小时构建一次
triggers {
cron('H */4 * * 1-5')
}
定时检查源码变更触发。jenkins定时检查源码是否变更,如果发生变更则触发构建。
//每隔4小时检查一次
triggers {
pollSCM('H */4 * * 1-5')
}
triggers {
upstream(upstreamProjects: 'job1,job2', threshold: hudson.model.Result.SUCCESS)
}
pipeline{
agent any
//说明:当上游Job,test_8或者test_7 运行成功的时候,自动触发
triggers { upstream(upstreamProjects: 'test_8,test_7', threshold: hudson.model.Result.SUCCESS) }
stages{
stage("stage1"){
steps{
echo "hello"
}
}
}
}
系统管理–>全局工具配置

pipeline {
agent any
tools {
//引用的工具,通过名称引用
maven 'maven-3.3.9'
}
stages {
stage('阶段1') {
steps {
sh 'mvn --version'
}
}
}
}
结果

提示信息
按钮名称。
设置submitter的环境变量名称。
配置需要输入的参数。
pipeline {
agent any
stages {
stage('阶段1') {
//暂时中断pipeline执行,等待用户登录,完成打卡
input {
message "你好,请输入登录用户"
ok "确认"
submitter "alice,bob"
//提供pipeline运行的参数
parameters {
string(name: 'PERSON', defaultValue: '张三', description: '请输入公司账号')
}
}
steps {
echo "你好, ${PERSON}, 打卡成功"
}
}
}
}
效果


pipeline {
agent none
stages {
stage('阶段1') {
steps {
echo 'Hello World'
}
}
stage('阶段2') {
agent {
//定义标签
label "la-app"
}
when {
//设置先对条件进行判断,符合预期才进入steps
beforeAgent true
branch 'prod'
}
steps {
echo '部署'
}
}
}
}
when {
branch 'master'
}
when {
branch pattern: "release-\\d+", comparator: "REGEXP"
}
当构建一个版本标签时为true。
when {
buildingTag()
}
当SCM的变更日志匹配给定的正则表达式时为true。
when {
changelog '.*^\\[DEPENDENCY\\] .+$'
}
当SCM变更集包含一个或以上文件匹配给定的文件路径表达式时为true。
when {
changeset "**/*.js"
}
when {
changeset pattern: ".TEST\\.java", comparator: "REGEXP"
}
通过caseSensitive参数设置是否区分大小写。
when {
changeset pattern: "*/*TEST.java", caseSensitive: true
}
when {
changeRequest()
}
when {
changeRequest target: 'master'
}
when {
changeRequest authorEmail: "[\\w_-.]+@example.com", comparator: 'REGEXP'
}
当某个环境变量值等于给定值时为true。
hen {
environment name: 'DEPLOY_TO', value: 'production'
}
当实际值等于期望值时为true。
when {
equals expected: 2, actual: currentBuild.number
}
when {
expression {
return params.DEBUG_BUILD
}
}
when {
tag "release-*"
}
when {
tag pattern: "release-\\d+", comparator: "REGEXP"
}
当条件为false时。
when {
not {
branch 'master'
}
}
当所有条件都为true时。
when {
allOf {
branch 'master';
environment name: 'DEPLOY_TO', value: 'production'
}
}
判断是否有一个条件为真。
when {
anyOf {
branch 'master'; branch 'staging'
}
}
当构建由给定触发时为true。
when { triggeredBy 'SCMTrigger' }
when { triggeredBy 'TimerTrigger' }
when { triggeredBy 'UpstreamCause' }
when { triggeredBy cause: "UserIdCause", detail: "vlinde" }
pipeline {
agent any
stages {
stage('非并行阶段') {
steps {
echo '非并行阶段'
}
}
stage('并行阶段') {
failFast true
parallel {
stage('并行阶段1') {
steps {
echo "并行阶段1"
}
}
stage('并行阶段2') {
steps {
echo "并行阶段2"
}
}
}
}
}
}


每一个axes必需包含一个或以上axis
agent
environment
input
options
post
tools
when
pipeline {
parameters {
choice(name: '操作系统', choices: ['all', 'linux', 'windows'], description: '请选择操作系统')
}
agent any
stages {
stage('构建和测试') {
matrix {
when {
anyOf {
expression { params.操作系统 == 'all' }
expression { params.操作系统 == env.PLATFORM }
}
}
axes {
axis {
name 'PLATFORM'
values 'linux', 'windows'
}
axis {
name 'BROWSER'
values '火狐浏览器', '谷歌浏览器', '苹果浏览器', '微软浏览器'
}
}
excludes {
exclude {
axis {
name 'PLATFORM'
values 'linux'
}
axis {
name 'BROWSER'
values '苹果浏览器'
}
}
exclude {
axis {
name 'PLATFORM'
notValues 'windows'
}
axis {
name 'BROWSER'
values '微软浏览器'
}
}
}
stages {
stage('构建') {
steps {
echo "Do Build for ${PLATFORM} - ${BROWSER}"
}
}
stage('测试') {
steps {
echo "Do Test for ${PLATFORM} - ${BROWSER}"
}
}
}
}
}
}
}



pipeline提供了一个脚本环境入口:script{},通过使用script来包裹脚本语句,即可使用脚本语法
pipeline {
agent any
stages {
stage('阶段1') {
steps {
//使用脚本
script{
if ( "1" =="1" ) {
echo "1 ==1"
}else {
echo "1 !=1"
}
}
}
}
}
}

pipeline {
agent any
stages {
stage('阶段1') {
steps {
script{
try {
sh 'exit 1'
}
catch (exc) {
echo '执行失败'
}
}
}
}
}
}
