【问题标题】:setting environment variables in jenkins file在 jenkins 文件中设置环境变量
【发布时间】:2019-04-02 03:34:54
【问题描述】:

我正在尝试在 Groovy 中为我的项目编写 jenkins 构建脚本。 问题是我想在脚本顶部定义一些变量,并在需要时将它们用作环境变量。

def someVariable = 'foo'

pipeline{
    agent any

    stages{
        stage("build"){
            environment {
                specialParameter = someVariable
            }
            steps{
                ...
            }
        }
        ...
    }

}

我还有其他一些步骤,它们的环境变量不同,而且我只想更改脚本的顶部以能够构建其他分支等等。所以我只想要一种在 environment 正文中使用定义的 someVariable 的方法。

谢谢

【问题讨论】:

    标签: jenkins groovy environment-variables jenkins-pipeline


    【解决方案1】:

    刚刚找到了另一种使用已定义环境变量的方法。

    def getsomeVariable (){
        return 'foo'
    }
    
    
    pipeline{
        agent any
    
        stages{
            stage("build"){
                environment {
                    specialParameter = getsomeVariable()
                }
                steps{
                    ...
                }
            }
            ...
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      首先,您可以使用环境部分来定义整个脚本中已知的环境变量:

      pipeline {
          agent any
          environment {
              TEST='myvalue'
          }
          stages{
              stage("build"){
                  steps{
                      ...
                  }
              }
          }
      }
      

      你也可以定义一个只在一个阶段知道的变量:

      pipeline {
          agent any
          stages{
              stage("build"){
                  environment {
                      TEST='myvalue'
                  }
                  steps{
                      ...
                  }
              }
          }
      }
      

      但是对于您的解决方案(在管道上方使用 def),您可以这样做:

      def someVariable = 'foo'
      
      pipeline{
          agent any
      
          stages{
              stage("build"){
                  steps{
                      echo someVariable
                  }
              }
          }
      }
      

      这将输出'foo'

      您可以在variable declarations syntax by reading Jenkins online book.获取更多信息

      更新:

      def someVariable = 'foo'
      
      pipeline{
          agent any
      
          stages{
              stage("build"){
                  environment {
                      TEST = sh(script: "echo -n ${someVariable}", returnStdout: true)
                  }
                  steps{
                      sh 'echo "${TEST}"'
                  }
              }
          }
      }
      

      输出:

      [test] Running shell script
      + echo foo
      foo
      

      【讨论】:

      • 也许我的问题是模棱两可的,我认为你没有足够重视我的问题,我的问题的最后一句话说明了我想要什么。我想在“环境主体”中使用声明的变量而不是在“步骤”中,看看我的代码。
      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2020-05-03
      相关资源
      最近更新 更多