Jenkinsfile参数默认值无法获取env.BUILD_NUMBER实际值问题
Got it, let's break down what's happening here and how to fix it quickly.
The Root Cause
Your issue is that in the parameters block of your declarative pipeline, wrapping ${env.BUILD_NUMBER} in double quotes tells Jenkins to treat it as a literal string rather than evaluating the variable. Declarative DSL doesn't automatically interpolate variables inside double quotes in the parameters section the way you'd expect in regular Groovy code.
The Fix
All you need to do is remove the double quotes around the default value and directly reference the env.BUILD_NUMBER variable. Since env.BUILD_NUMBER is already a string, no extra conversion is needed:
string( name: 'DEPLOY_BUILD_NUMBER', defaultValue: env.BUILD_NUMBER, description: 'Fresh Build and Deploy OR Deploy Previous Build Number' )
While you're at it, there's another small issue in your CopyArtifact step: you're using single quotes for '${JOB_NAME}', which also won't interpolate. Switch to using the env.JOB_NAME variable directly (or double quotes if you prefer):
projectName: env.JOB_NAME,
Full Modified Jenkinsfile
Here's the complete pipeline with both fixes applied:
pipeline { agent { label 'windows' } options { copyArtifactPermission("${JOB_NAME}"); } parameters { string( name: 'DEPLOY_BUILD_NUMBER', defaultValue: env.BUILD_NUMBER, description: 'Fresh Build and Deploy OR Deploy Previous Build Number' ) } stages { stage ('Build') { steps { sh ''' echo "Building Project" echo "Packaging into tar.gz" ''' } post { success { archiveArtifacts artifacts: '*.tar.gz' } } } stage ('Deploy') { steps { echo "Deploying...." echo "${params.DEPLOY_BUILD_NUMBER}" echo "${env.BUILD_NUMBER}" script { step ([$class: 'CopyArtifact', projectName: env.JOB_NAME, filter: "*.tar.gz", fingerprintArtifacts: true, selector: [$class: 'SpecificBuildSelector', buildNumber: "${params.DEPLOY_BUILD_NUMBER}"] ]); } } } } post { success { script { currentBuild.displayName = "#${BUILD_NUMBER}" } } } }
Why This Works
- By removing the double quotes from
defaultValue, Jenkins now references the actualenv.BUILD_NUMBERvariable value that's assigned when the pipeline initializes, instead of treating it as a static string. - Using
env.JOB_NAMEin theCopyArtifactstep ensures Jenkins uses the current job's name correctly, avoiding any interpolation failures from single-quoted strings.
内容的提问来源于stack exchange,提问作者rp346

