繁体   English   中英

将变量传递给 jenkins yaml podTemplate

[英]Passing variable to jenkins yaml podTemplate

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM