JackPGreen
JackPGreen

Reputation: 1139

Jenkins pipeline parameter being evaluated to previous value

I've got a pipeline which builds software, with a parameter used for the version.

The parameter defaults to a Groovy expression evaluating to the current date.

But when I run it, the value it's using is actually the date of the previous build.

Example:

Pipeline Script:

    pipeline {
        agent any
        parameters {
            string(
                name: "BUILD_VERSION",
                defaultValue: "Build version "+java.time.LocalDateTime.now()
                )
            }
            stages {
                stage("Print") {
                    steps {
                        echo params.BUILD_VERSION
                    }
                }
            }
        }

What am I missing? How can I default the parameter to the date it's executed?

Upvotes: 2

Views: 1202

Answers (2)

t0r0X
t0r0X

Reputation: 4772

Maybe this would be sufficient, if the timestamp doesn't need to be editable?

import groovy.transform.Field

@Field
String BUILD_VERSION_TXT

pipeline {
    agent any
    parameters {
        string(name: 'BUILD_VERSION', defaultValue: "Build version")
    }
    stages {
        stage('Initialize') {
            steps {
                script {
                    BUILD_VERSION_TXT = params.BUILD_VERSION + ' ' + java.time.LocalDateTime.now()
                }
            }
        }
        stage("Print") {
            steps {
                echo BUILD_VERSION_TXT
            }
        }
    }
}

Upvotes: 0

Noam Helmer
Noam Helmer

Reputation: 6824

When you are using the the defaultValue attribute of the string parameter you are actually setting the default value for the next execution of the project, not for the current one - as the default value is updated only after the build started to run with the given parameters.
Therefore the next build will be executed with the value set by the previous one.

To overcome this you need to define a parameter that is updated before the builds starts to run, and then the build will use that parameter in the execution.
One way to do it is with the Extended Choice Parameter Plugin which will generated the default value on runtime when you click the Build With Parameters in your job. This way the default time value will be used for the current running build.
Here is the code example:

pipeline {
    agent any
    parameters {
        extendedChoice(name: 'BUILD_VERSION', type: 'PT_TEXTBOX',
                       defaultGroovyScript: 'return java.time.LocalDateTime.now().toString()')
    }
    stages {
        stage("Print") {
            steps {
                echo params.BUILD_VERSION
            }
        }
    }
}

Upvotes: 1

Related Questions