簡體   English   中英

如何在Jenkins聲明性管道的代理部分中使用環境變量?

[英]How to use an environment variable in the agent section of a Jenkins Declarative Pipeline?

我正在為一個基於node.js的應用程序構建一個Docker鏡像,其中一些依賴項需要一個私有NPM注冊表的NPM令牌,但是在構建映像時,包含該令牌的變量為null,例如

docker build -t 3273e0bfe8dd329a96070382c1c554454ca91f96 --build-args NPM_TOKEN=null -f Dockerfile

簡化的管道是:

pipeline {

  environment {
    NPM_TOKEN = credentials('npm-token')
  }

  agent {
    dockerfile {
      additionalBuildArgs "--build-args NPM_TOKEN=${env.NPM_TOKEN}"
    }
  }

  stages {
    stage('Lint') { 
      steps { 
        sh 'npm run lint' 
      }
    }
  }

}

有沒有辦法在該部分使用env變量或目前不支持?

順便說一句,我已經按照Docker中的建議和私有模塊有關如何使用NPM令牌構建一個docker鏡像

這肯定是聲明性管道的一個錯誤。 您可以在此處跟蹤與此相關的問題: https//issues.jenkins-ci.org/browse/JENKINS-42369

如果你不再使用聲明性管道並使用腳本管道,那么這不會發生,盡管你的Jenkins文件將是“更多的”

為此找到了解決方案。 使用憑據管理器添加NPM_TOKEN。 那你可以做

pipeline {
  agent {
    docker {
      image 'node:latest'
      args '-e NPM_TOKEN=$NPM_TOKEN'
    }

  }
  stages {
    stage('npm install') {
      steps {
        sh 'npm install'
      }
    }
    stage('static code analysis') {
      steps {
        sh 'npx eslint .'
      }
    }
  }
}

我想出了一個解決方法,它仍然使用聲明性管道。 我正在使用這種技術下載私人github repos與pip。

// Workarounds for https://issues.jenkins-ci.org/browse/JENKINS-42369
// Warning: The secret will show up in your build log, and possibly be in your docker image history as well.
// Don't use this if you have a super-confidential codebase

def get_credential(name) {
  def v;
  withCredentials([[$class: 'StringBinding', credentialsId: name, variable: 'foo']]) {
      v = env.foo;
  }
  return v
}

def get_additional_build_args() {
    return "--build-arg GITHUB_ACCESS_TOKEN=" + get_credential("mysecretid")
}


pipeline {
    agent {
        dockerfile {
            filename 'Dockerfile.test'
            additionalBuildArgs get_additional_build_args()
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM