从位于存储库中的文件获取jenkinsfile环境变量

gab6jxml  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(217)

我需要从一个包含所有.env文件(每个api一个)的repo中获取不同api的env变量。例如:
在/env_file目录中:

  • foo.env
  • bar.env

是否可以使用位于repo中的.env文件来获取env变量,而不是在environment {}中手动设置它们?如果可以,如何在每个api阶段引用每个文件?提前感谢!以前从未在Jenkinsfile中使用过这种方法。如果这是一个奇怪的问题,请抱歉。

3duebb1j

3duebb1j1#

您可以将环境注入Jenkins管道的全局变量:env是一个Map和environment {}的幕后推手,但它有一个限制:
Allow insert new environment, NOT allow override existing environment
如果这些.env文件具有相同环境,并且需要一起加载它们,则会遇到'覆盖现有环境'问题
如果你不是在这种情况下,你可以做如下:

pipeline {
  stages {
    stage('Test endpoint A') {
      script {
        def props = readProperties file: 'A.env'
        for (p in props) {
           env[p.key] = p.value
        }
      }
      // other steps
    }
    stage('Test endpoint B') {
      script {
        def props = readProperties file: 'B.env'
        for (p in props) {
           env[p.key] = p.value
        }
      }
      // other steps
    }
  }
}

相关问题