Jenkins声明式管道包含文件



我正在尝试为Jenkins管道单独保存文件变量,这是因为它将被多个管道使用。但我似乎找不到合适的方式来包含它?或者有没有办法把它包括进去?

MapA:

def MapA = [
ItemA: [
Environment: 'envA',
Name: 'ItemA',
Version: '1.0.0.2',
],
ItemB: [
Environment: 'envB',
Name: 'ItemB',
Version: '2.0.0.1',
]
]
return this;

MainScript:

def NodeLabel = 'windows'
def CustomWorkSpace = "C:/Workspace"
// Tried loading it here (Location 1)
load 'MapA'
pipeline {
agent {
node {
// Restrict Project Execution
label NodeLabel
// Use Custom Workspace
customWorkspace CustomWorkSpace
// Tried loading it here (Location 2)
load 'MapA'
}
}
stages {
// Solution
stage('Solution') {
steps {
script {
// Using it here
MapA.each { Solution ->
stage("Stage A") {
...
}
stage("Stage B") {
...
}
// Extract Commit Solution
stage("Stage C") {
...
echo "${Solution.value.Environment}"
echo "${Solution.value.Name}"
echo "${Solution.value.Version}"
}
}
}
}
}
}
}
  • 在管道和节点部分之外的位置1上:它给出了以下错误
org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
  • 在Location 2的node section中:它给出了下面的错误
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 7: Expected to find ‘someKey "someValue"’ @ line 7, column 14.
load 'MapA'
node {
^

您可以通过两种方式实现您的场景:

# 1

如果你愿意,你可以在同一个Jenkins文件中硬编码变量,并在你的管道中使用它,如下所示:

Jenkinsfile内容

def MapA = [
ItemA: [
Environment: 'envA',
Name: 'ItemA',
Version: '1.0.0.2',
],
ItemB: [
Environment: 'envB',
Name: 'ItemB',
Version: '2.0.0.1',
]
]
pipeline {
agent any;
stages {
stage('debug') {
steps {
script {
MapA.each { k, v ->
stage(k) {
v.each { k1,v1 ->
// do your actual task by accessing the map value like below 
echo "${k} , ${k1} value is : ${v1}"
}
}

}
}
}
}
}
}

# 2

如果你想把这个变量保存在一个单独的groovy文件中,就像在

下面Git Repo文件和文件夹结构

.
├── Jenkinsfile
├── README.md
└── var.groovy

var.groovy

def mapA() {
return [
ItemA: [
Environment: 'envA',
Name: 'ItemA',
Version: '1.0.0.2',
],
ItemB: [
Environment: 'envB',
Name: 'ItemB',
Version: '2.0.0.1',
]
]
} 
def helloWorld(){
println "Hello World!"
}
return this;

Jenkinsfile

pipeline {
agent any 
stages {
stage("iterate") {
steps {
sh """
ls -al
"""
script {
def x = load "${env.WORKSPACE}/var.groovy"
x.helloWorld()

x.mapA().each { k, v ->
stage(k) {
v.each { k1,v1 ->
echo "for ${k} value of ${k1} is ${v1}"
}
} //stage
} //each
} //script
} //steps
} // stage 
}
}

最新更新