如何从“执行系统Groovy脚本”中更改Jenkins环境变量

时间:2019-02-26 21:44:42

标签: jenkins groovy

我的Jenkins工作(不是管道)中有这个“执行系统Groovy脚本” ...

import hudson.EnvVars
import hudson.model.Environment

def process_type = build.properties.environment.PROCESSTYPE.toString();
def SDATE = build.properties.environment.START_DATE.toString();
def EDATE = build.properties.environment.END_DATE.toString();

         println "Old Dates :"    
         println "$SDATE"
         println "$EDATE"


if(process_type == "Nightly") {

    def today = new Date()
    def sevenDaysAgo = today - 7

    def START_DATE2 =   sevenDaysAgo.format("yyyy-MM-dd")
    def END_DATE2 = today.format("yyyy-MM-dd")

    String START_DATE =  START_DATE2.toString()
    String END_DATE = END_DATE2.toString()

         println "New Dates :"    
         println "$START_DATE"
         println "$END_DATE"

        String vars = [START_DATE: "$START_DATE", END_DATE: "$END_DATE"]

  }

我可能需要的东西更多,因为在Jenkins的工作中使用Groovy对我来说是新手,并且我一直在尝试各种方法来使其正常工作。无论如何,此詹金斯作业可以“夜间运行”,然后使用7天的日期范围,也可以提供日期范围。如果设置为“ Nightly”,则要设置7天的日期范围(覆盖两个默认日期),然后在下一个构建步骤(即“ Execute Windows Batch命令”)中使用新日期,并使用参数。 。'%START_DATE%''%END_DATE%'。

上面的代码已执行,但是Windows步骤仍然使用旧的默认日期。那么,如何在groovy步骤中更改环境变量,然后将其传递回Jenkins,以便Windows批处理步骤获得新值?

1 个答案:

答案 0 :(得分:0)

仍然不确定我使用的API是否超出了我的需要,但是我可以使用以下代码。看来您无法修改已经存在的Job Parameter的值,所以我不得不创建一个新的要在下一个Job步骤中使用的参数。这是代码...

import hudson.EnvVars
import hudson.model.Environment

def process_type = build.properties.environment.PROCESSTYPE.toString();
def SDATE = build.properties.environment.START_DATE.toString();
def EDATE = build.properties.environment.END_DATE.toString();

println "Old Dates :"    
println "$SDATE"
println "$EDATE"


EnvVars envVars = build.getEnvironment(listener);

if(process_type == "Nightly") {

    def today = new Date()
    def sevenDaysAgo = today - 7

    def START_DATE2 =   sevenDaysAgo.format("yyyy-MM-dd")
    def END_DATE2 = today.format("yyyy-MM-dd")

    String START_DATE =  START_DATE2.toString()
    String END_DATE = END_DATE2.toString()

         println "New Dates :"    
         println "$START_DATE"
         println "$END_DATE"

        File file = new File(envVars.get('WORKSPACE') + "\\Dates.txt")
        file.write "NEW_START_DATE=" + "$START_DATE" + "\r\n"
        file <<  "NEW_END_DATE=" + "$END_DATE" + "\r\n"
        println file.text
} else
{ 
       // The next step 'Inject Environment variables', requires this file to exist
       // if not a nightly run use date range provided in parameters

         println "New Old Dates :"    
         println "$SDATE"
         println "$EDATE"

       File file = new File(envVars.get('WORKSPACE') + "\\Dates.txt")
        file.write "NEW_START_DATE=" + "$SDATE" + "\r\n"
        file <<  "NEW_END_DATE=" + "$EDATE" + "\r\n"
        println file.text
}