我正在学习Jenkins Pipeline,并尝试按照这个Pipeline code进行操作。但是我的Jenkins一直抱怨def
不合法。
我想知道是否缺少任何插件?我已经安装了groovy
,job-dsl
,但还是不起作用。
我正在学习Jenkins Pipeline,并尝试按照这个Pipeline code进行操作。但是我的Jenkins一直抱怨def
不合法。
我想知道是否缺少任何插件?我已经安装了groovy
,job-dsl
,但还是不起作用。
正如@Rob所说,有两种类型的pipeline:scripted
和declarative
。这就像imperative
vs declarative
。在scripted
pipeline中只允许使用def
或包装在script {}
中。
从node
开始,可以使用def
或if
,例如下面的示例。这是传统的方法。
node {
stage('Example') {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
从 pipeline
开始,不允许使用 def
或 if
,除非它被包装在 script {...}
中。声明式管道使很多事情易于编写和阅读。
pipeline {
agent any
triggers {
cron('H 4/* 0 0 1-5')
}
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
pipeline {
agent any
stages {
stage('Example Build') {
steps {
echo 'Hello World'
}
}
stage('Example Deploy') {
when {
branch 'production'
}
steps {
echo 'Deploying'
}
}
}
}
pipeline {
agent any
stages {
stage('Non-Parallel Stage') {
steps {
echo 'This stage will be executed first.'
}
}
stage('Parallel Stage') {
when {
branch 'master'
}
failFast true
parallel {
stage('Branch A') {
agent {
label "for-branch-a"
}
steps {
echo "On Branch A"
}
}
stage('Branch B') {
agent {
label "for-branch-b"
}
steps {
echo "On Branch B"
}
}
}
}
}
}
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
script {
def browsers = ['chrome', 'firefox']
for (int i = 0; i < browsers.size(); ++i) {
echo "Testing the ${browsers[i]} browser"
}
}
}
}
}
}
要阅读更多关于声明式流水线语法的内容,请参考官方文档这里
def agentLabel
if (BRANCH_NAME =~ /^(staging|master)$/) {
agentLabel = "prod"
} else {
agentLabel = "master"
}
pipeline {
agent { node { label agentLabel } }
..
node
来使用def
:
node {
stage('Example') {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
script{..}
。 stage ('jon'){
steps{
script{
def imageLine = 'chiducaff/user_containers:sonnginx'
}
writeFile file: 'anchore_images', text: imageLine
anchore name: 'anchore_images'
}}
script
块内使用变量,否则会出现groovy.lang.MissingPropertyException
的错误。 - okapi
def
在哪里是有效的。 - Rob Halesdef
,该流水线以node {...}
开头;而我的文件以声明式的pipeline
开头,除非被script {...}
包装,否则不允许使用def
。 - Ron