jenkinsparametersjenkins-pipelinedevopsjenkins-groovy

Can I set the value of a boolean parameter inside Jenkins pipeline


I have a Jenkins pipeline that takes a boolean parameter as input. However, I need to be able to set the value of this parameter programmatically inside the pipeline based on some conditions. Here is the snippet of my pipeline:

pipeline {
  agent any
  parameters {
    booleanParam(
      defaultValue: true,
      description: 'This is a boolean parameter',
      name: 'MY_BOOLEAN_PARAM'
    )
  }
  stages {
    stage('Example') {
      steps {
        script {
          // some condition
          def myBooleanValue = true
          // I need to set the value of MY_BOOLEAN_PARAM based on myBooleanValue
        }
      }
    }
  }
}

I've tried using the setBuildParameters method like this:

setBuildParameters([[$class: 'BooleanParameterValue', name: 'MY_BOOLEAN_PARAM', value: true]])

But this throws an error that says: "No such DSL method 'setBuildParameters' found among steps". I've also tried setting the value of MY_BOOLEAN_PARAM using the params object like this:

params.MY_BOOLEAN_PARAM = true

But this doesn't seem to work either. Is it possible to set the value of the MY_BOOLEAN_PARAM parameter inside the pipeline based on the myBooleanValue variable? If so, can someone please provide an example of how I can do this?


Solution

  • afaik it is not allowed to change params from pipeline script, however you may modify env as a workaround:

    pipeline {
        parameters {
            booleanParam(
              defaultValue: true,
              description: 'This is a boolean parameter',
              name: 'MY_BOOLEAN_PARAM'
            )
        }
    
        agent any
    
        stages {
            stage('before') {
                steps {
                    echo "before env   : ${env.MY_BOOLEAN_PARAM}"
                }
            }
            stage('reset') {
                steps {
                    script{
                        env.MY_BOOLEAN_PARAM = false
                    }
                }
            }
            stage('after') {
                steps {
                    echo "after env   : ${env.MY_BOOLEAN_PARAM}"
                }
            }
        }
    }
    

    Output:

    before env   : true
    ...
    after env   : false