Home > Mobile >  How to call a method inside triggers block in Jenkinfile
How to call a method inside triggers block in Jenkinfile

Time:09-01

I have a pipeline which needs to be scheduled to run at a particular time. There are some dynamic parameters that needs to be passed while running the pipeline. I have created a function that gives me the desired parameter value. However this pipeline does not get triggered as the function value is not getting resolved inside trigger block & is getting treated as string.

getlatest is the method I created which takes in 3 parameters. The value of this method is not getting resolved & instead treated as string. The pipeline rund as expected if I hardcode some value for version.

triggers{
  parameterizedCron("H/5 * * * * % mod=test; version=getlatest('abc','xyz','lmn');")
}

CodePudding user response:

I've never seen this being tried before so I don't know if what you are doing is something Jenkins is capable of. Instead, remove the parameter and create an environment variable called version and assign the function result to that:

environment {
    VERSION = getlatest('abc','xyz','lmn')
}

And reference this VERSION variable instead of your input parameter.

How to reference:

env.VERSION or ${VERSION} or ${env.VERSION}

Examples:

currentBuild.displayName=env.VERSION

env.SUBJECT="Checkout Failure on ${VERSION}"

string(name: 'VERSION', value: "${env.VERSION}")

CodePudding user response:

The problem is that the code that calculates the parameter — just like any other code in Jenkins — needs an executor to run. To get an executor, you need to run your pipeline. To run your pipeline, you need to give Jenkins the parameters. But to give Jenkins the parameters, you need to run your code.

So there's a chicken and egg problem, there.

To break out of this cycle, you may want to run scripted pipeline before you run the declarative one:

node('built-in') { // or "master", or any other
    def version = getlatest('abc','xyz','lmn')
    def cron_parameters = "H/5 * * * * % mod= test; version=${version}"
    println "cron_parameters is ${cron_parameters}"
    env.CRON_PARAM = cron_parameters
}

pipeline {
    agent { node { label "some_label" } }

    triggers {
        parameterizedCron(env.CRON_PARAM)
    }
    // ...
}
  • Related