【问题标题】:How can load the Docker section of my Jenkins pipeline (Jenkinsfile) from a file?如何从文件中加载我的 Jenkins 管道 (Jenkinsfile) 的 Docker 部分?
【发布时间】:2018-05-10 23:06:11
【问题描述】:

我有多个使用 Jenkinsfiles 从私有注册表检索 docker 映像的管道。我希望能够将 docker 特定信息从文件加载到管道中,这样当 docker 标签或凭据发生更改时,我就不必修改所有 Jenkinsfiles。我尝试使用下面的示例 jenkinsfile 来做到这一点:

def common

pipeline {
   agent none
   options {
     timestamps()
   }
   stages {
    stage('Image fetch') {
     steps{
        script {
              common = load('/home/jenkins/workspace/common/docker_image')
              common.fetchImage()
        }
     }
  }
}

使用 docker_image 包含:

def fetchImage() {
  agent {
   docker {
    label “target_node ”
    image 'registry-url/image:latest'
    alwaysPull true
    registryUrl 'https://registry-url’
    registryCredentialsId ‘xxxxxxx-xxxxxx-xxxx’
   }
  }
}

执行管道时出现以下错误:

缺少必需的上下文类 hudson.FilePath 也许你忘了 用提供此功能的步骤包围代码,例如: 节点,dockerNode

如何使用声明性管道做到这一点?

【问题讨论】:

    标签: docker groovy jenkins-pipeline


    【解决方案1】:

    这有几个问题:

    1. 您只能在顶层分配node

      pipeline {
        agent ...
      }
      

      或者您可以像这样使用每个阶段的节点分配:

      pipeline {
        agent none
        ....
        stages {
          stage("My stage") {
            agent ...
            steps {
              // run my steps on this agent
            }
          }
        }
      }
      

      您可以查看文档here

    2. steps 应该在分配的节点上执行(或者在某些情况下,它们可以在根本不分配节点的情况下执行)。

    3. Declarative PipelineScripted Pipeline 是两个不同的东西。是的,可以混合使用它们,但scripted pipeline 旨在将一些逻辑抽象为shared library,或者为您提供一种成为“硬核大师忍者”的方法并使用@ 编写您自己的完全自定义管道987654333@ 管道,没有declarative 糖。

    我不确定您的Docker <-> Jenkins 连接是如何设置的,但是如果您安装一个插件并使用agent templates 来提供您需要的代理,您可能会更好。

    如果您有Docker Swarm,您可以安装Docker Swarm Plugin,然后在您的管道中配置pipeline { agent { label 'my-agent-label' } }。这将自动为您的 Jenkins 提供一个容器中的代理,该容器使用您指定的图像。

    如果您已将 /var/run/docker.sock 暴露给您的 Jenkins,那么您可以使用具有相同概念的 Yet Another Docker Plugin

    这样您可以将代理配置删除到agent template 中,并且您的管道将只使用label 来拥有它需要的代理。

    【讨论】:

    • 我根本没有分配节点。我没有分配代理的问题。我的问题是我有很多 Jenkinsfiles 检索相同的 docker 图像。我想从单个文件加载管道的 docker 部分,这样如果我需要添加或删除 Docker 参数,我就不必修改所有 Jenkinsfiles。
    • 您可以通过安装我提到的两个插件之一来做到这一点。然后你用labeldefine 代理模板,你只需用你给它的label 分配节点。
    • 我明白了。不幸的是,我没有 Jenkins 安装的管理员权限,所以我无法创建 Docker 代理模板。
    • 那很不幸。我认为不可能以编程方式执行此操作(即通过 groovy)。您可以尝试在issues.jenkins-ci.org 询问这个问题 - 可能有一些真正隐藏的功能使这成为可能,但根据我的经验,您会碰壁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多