将变量传递给 jenkins yaml podTemplate

时间:2021-03-19 09:51:42

标签: jenkins kubernetes

我使用 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

你知道我如何实现类似的行为吗?

1 个答案:

答案 0 :(得分:0)

感谢 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/

相关问题