如何在Jenkins声明式流水线中获取SVN版本号
Got it, let's tackle this problem head-on since Declarative Pipeline has some key differences from Freestyle or Scripted Pipelines when it comes to accessing the SVN revision number.
First, you’re right that ${SVN_REVISION} works out of the box in Freestyle jobs, and the Scripted Pipeline approach uses the checkout step's returned variables. For Declarative Pipeline, we just need to wrap that script-style logic in a script block (since Declarative enforces a structured syntax but allows escape hatches for scripted code).
Solution 1: Explicit SVN Checkout with Variable Capture
If you’re defining your SVN repo directly in the pipeline, use this approach to checkout and capture the revision:
pipeline { agent any stages { stage('Checkout SVN & Capture Revision') { steps { script { // Execute SVN checkout and store SCM-related variables def scmVars = checkout([ $class: 'SubversionSCM', locations: [[ remote: 'https://your-svn-repo-url/trunk', local: '.' ]], // Add any additional SVN config here (credentials, ignore rules, etc.) additionalCredentials: [], ignoreDirPropChanges: false, workspaceUpdater: [$class: 'UpdateUpdater'] ]) // Save the revision to an environment variable for global use env.SVN_REVISION = scmVars.SVN_REVISION } } } stage('Use the SVN Revision') { steps { echo "Current SVN Revision: ${env.SVN_REVISION}" // Use the revision number for tasks like packaging, tagging, or logging sh "echo 'Building revision ${env.SVN_REVISION}'" } } } }
Solution 2: Using checkout scm (Works for Configured SCMs, Not Just Multibranch)
You mentioned thinking checkout scm only works for Multibranch Pipelines, but that’s not true—this works whenever your pipeline has an SCM configured (either via the job's UI or in the pipeline definition). You can still capture the revision like this:
pipeline { agent any options { skipDefaultCheckout(true) // Skip auto-checkout to do it manually and capture variables } stages { stage('Checkout & Get Revision') { steps { script { def scmVars = checkout scm env.SVN_REVISION = scmVars.SVN_REVISION } } } stage('Validate Revision') { steps { echo "Checked out SVN revision: ${env.SVN_REVISION}" } } } }
Key Notes:
- The
scriptblock lets you use Scripted Pipeline syntax within Declarative, which is necessary for capturing thescmVarsobject returned bycheckout. - By assigning
scmVars.SVN_REVISIONtoenv.SVN_REVISION, you make the revision number available across all stages in your pipeline. - Unlike Freestyle jobs, Declarative Pipeline doesn’t auto-inject the
SVN_REVISIONenvironment variable, so this explicit capture is required.
内容的提问来源于stack exchange,提问作者Marcel M.

