jenkins - 如何在cps脚本jenkins中获取变量?
问题描述
我有 .yaml 文件,其中包含以下变量(请注意这是一个片段),我在其中调用 CPS 脚本中的变量。当我在 Jenkins 上运行它时,出现以下错误:
java.lang.NullPointerException:无法在空对象上调用方法startsWith()
请注意,当我调用 _agent_label 时,它能够解析它,而 env._branch_name 返回“null”。如何在我的 CPS groovy 脚本之外调用变量?
apiVersion: v1
data:
jobs.yaml: |-
jobs:
- script: |
.
.
.
.
.
_agent_label = flex_job.get('agent_label', 'agent')
workspace_dir = flex_job.get('jenkins_pipeline')
jenkinsfile = 'Jenkinsfile'
_branch_name = flex_job.get('branch_name', 'refs/heads/master')
再往下,我有以下 Jenkins Groovy CPS 代码
definition {
cps {
script("""
* Prepare branch reference and name.
*/
def branch_ref() {
echo "---------------- Prepare variable names ----------------"
regex_prefix = ~"^refs/heads/"
echo env.branch_name <----- returns nulls
echo "Before the if "
if (env._branch_name.startsWith('refs/')) {
echo "Inside the if statement"
remote_branch_ref = env._branch_name
echo "Remote Branch Ref: $remote_branch_ref"
} else {
echo "inside the else statement"
remote_branch_ref = 'refs/heads/' + env._branch_name
echo "Remote Branch Ref: $remote_branch_ref"
}
echo "otherwise something else"
// For example refs/heads/master - refs/heads/ -> master
local_branch_name = env._branch_name - env.regex_prefix
echo "Local branch name: $local_branch_name"
}
node(env._agent_label) {
stage("Git scripted scm") {
echo "monkey"
branch_ref()
}
}
""".stripIndent())
}
}
解决方案
推荐阅读
- python - 在 Tkinter.Text 区域显示用户输入
- sinch - 如何使用 sinch sdk 使视频静音
- amazon-dynamodb - 检索不同计数 DynamoDB
- ruby-on-rails - 如何获取当前请求的日志输出副本?
- angular - 服务器端 Ionic 上的指纹认证
- perl - 编写一个 Perl 脚本,列出用户指定的目录的目录内容
- javascript - MariaDB 与 Sequelize 的连接
- java - RabbitMq connectionFactory 初始化时的 java.io.IOException
- python - 迭代图像并选择给定色调范围内的亮度/饱和度值,而不使用嵌套的 for 循环
- android - 添加 Room 编译器后找不到 GlideApp