簡體   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