【问题标题】:Passing variable to jenkins yaml podTemplate将变量传递给jenkins yaml podTemplate
【发布时间】:2021-03-22 17:22:21
【问题描述】:

我正在使用 Jenkins 和 kubernetes 插件来运行我的作业,我需要运行一个管道:

  1. 构建 docker 镜像
  2. 提交到注册表
  3. 在以下步骤中使用相同的图像来执行测试。
Container(image:A): build image B 
Container(image:B) : test image B

所以我想使用变量并在 kubernetes podtemplate 中替换它们,如下所示:

pipeline {
  agent none
  stages {
    stage("Build image"){
        // some script that builds the image
        steps{
            script{
                def image_name = "busybox"
            }
        }
    }
    stage('Run tests') {
      environment {
        image = "$image_name"
      }
      agent {
        kubernetes {
          yaml """\
        apiVersion: v1
        kind: Pod
        metadata:
          labels:
            some-label: some-label-value
        spec:
          containers:
          - name: busybox
            image: "${env.image}"
            command:
            - cat
            tty: true
        """.stripIndent()
        }
      }
      steps {
        container('busybox') {
          sh 'echo "I am alive!!"'
        }
      }
    }
  }
}

但我得到的变量是空的:

[Normal][ci/test-10-g91lr-xtc20-s1ng1][Pulling] Pulling image "null"
[Warning][ci/test-10-g91lr-xtc20-s1ng1][Failed] Error: ErrImagePull
[Warning][ci/test-10-g91lr-xtc20-s1ng1][Failed] Failed to pull image "null": rpc error: code = Unknown desc = Error response from daemon: pull access denied for null, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

你知道我怎样才能实现类似的行为吗?

【问题讨论】:

  • 注意:我已经看到,如果我将 environment {} 添加为 pipeline{} 的子级,它可以工作,但这不是我想要实现的,因为我希望图像是从上一步生成的,而不是在管道中硬编码
  • 尝试在“build image”阶段直接设置env.image = 'busybox',并从“run tests”中移除environment块。

标签: jenkins kubernetes


【解决方案1】:

感谢 zett42 的回答,有了您的建议,我的目标得以实现。

基本上解决方案是在构建阶段设置一个全局环境变量。我在这里发布了完整的解决方案,以帮助其他人解决同样的问题:

pipeline {
  agent none
  stages {
    stage("Build image"){
        // some script that builds the image
        steps{
            script{
                env.image_name = "busybox"
            }
        }
    }
    stage('Run tests') {
      agent {
        kubernetes {
          yaml """\
        apiVersion: v1
        kind: Pod
        metadata:
          labels:
            some-label: some-label-value
        spec:
          containers:
          - name: busybox
            image: "${env.image_name}"
            command:
            - cat
            tty: true
        """.stripIndent()
        }
      }
      steps {
        container('busybox') {
          sh 'echo "I am alive!!"'
        }
      }
    }
  }
}

为了更好地理解它,阅读这篇文章很有用:

https://e.printstacktrace.blog/jenkins-pipeline-environment-variables-the-definitive-guide/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2021-02-18
    • 2016-11-04
    • 2014-01-16
    相关资源
    最近更新 更多