【问题标题】:Multiple Jenkinsfiles, One Agent Label多个 Jenkinsfiles,一个代理标签
【发布时间】:2018-10-15 18:16:44
【问题描述】:

我有一个项目,它有多个构建管道,允许针对它进行不同类型的构建(不,我没有能力用它构建一个;这超出了我的控制范围)。

这些管道中的每一个都由项目 repo 中的 Jenkinsfile 表示,并且每个管道都必须使用相同的构建代理标签(它们也需要共享其他配置,但当前问题是构建代理标签)。我正在尝试将标签放入项目 repo 中的某种配置文件中,以便所有 Jenkinsfiles 都可以读取它。

我希望这很简单,因为在您已签出源副本以读取 Jenkinsfile 之前,您不需要此配置数据。据我所知,这是不可能的。

在我看来,在项目完成其 SCM 步骤之前,Jenkinsfile 无法从 SCM 读取文件。但是,为时已晚:agent{label} 的参数在任何阶段运行之前都已读取。

这是一个最小的例子:

final def config
pipeline {
    agent none
    stages {
        stage('Configure') {
            agent {
                label 'master'
            }
            steps {
                checkout scm // we don't need all the submodules here
                echo "Reading configuration JSON"
                script { config = readJSON file: 'buildjobs/buildjob-config.json' }
                echo "Read configuration JSON"
            }
        }
        stage('Build and Deploy') {
            agent {
                label config.agent_label
            }
            steps {
                echo 'Got into Stage 2'
            }
        }
    }
}

当我运行它时,我得到: java.lang.NullPointerException: Cannot get property 'agent_label' on null object我没有从“配置”阶段得到任何回声。

如果我将“构建和部署”阶段的标签更改为“主”,构建成功并打印出所有三个回显语句。

在需要设置代理标签之前,有什么方法可以从 Git 工作区读取文件?

【问题讨论】:

  • 如果您只运行第一阶段(完全删除第二阶段)并回显 config.agent_label,会发生什么情况。输出正确吗?

标签: jenkins jenkins-pipeline


【解决方案1】:

请参阅https://stackoverflow.com/a/52807254/7983309。我认为您遇到了这个问题。 label 无法将 config.agent_label 解析为其更新后的值。第一行中设置的任何内容都将发送到您的第二阶段。

EDIT1:

env.agentName = ''
pipeline {
    agent none
    stages {
        stage('Configure') {
            agent {
                label 'master'
            }
            steps {
                script {
                    env.agentName = 'slave'
                    echo env.agentName
                }    
            }
        }
        stage('Finish') {
            steps {
                node (agentName as String) { println env.agentName }
                script {
                    echo agentName
                }
            }
        }
    }
}

来源 - In a declarative jenkins pipeline - can I set the agent label dynamically?

【讨论】:

  • 不是我要找的答案,但它看起来是正确的答案。换句话说,似乎不可能做我想做的事。谢谢。
  • 在另一个线程上找到了有趣的解决方案。经过测试,它可以工作。将在上面的答案部分中发布脚本,因为我无法在此处对其进行格式化。看看你是否可以在你的用例中使用它
猜你喜欢
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
相关资源
最近更新 更多