2

I am writing a declarative Jenkins pipeline for CICD of a maven project. I set an environment variable called REL_VER which could take the form such as 0.1-rc1, 0.20-alpha1, 0.15-beta2, etc.

  environment {
        REL_VER = '0.1-alpha1'
        DEV_VER = '0.1-SNAPSHOT'    
    } 

I need to split REL_VER and pass the first element named osgi_ver to a shell command I run in the steps to replace a word in a Java file based on the answer of this post

   stages {
        stage('package') {
            steps {
                script {
                    def vars = Jenkins.instance.getGlobalNodeProperties()[0].getEnvVars()
                    def osgi_ver = vars['REL_VER'].tokenize('-')[0]
                }
                sh "echo ${osgi_ver}"

                withMaven(
                    maven: 'maven-3.3.9',
                    mavenSettingsConfig: 'dist-maven-settings',
                    mavenLocalRepo: '.m2repo') {   

                    sshagent (credentials: ['dist-serv']) { 
                        sh "sed -i '/setSystemExtraPackages/s/.*/\t\t.setSystemExtraPackages(new String[]{\"com.xxx;version=${osgi_ver}\"}));/' DsgPluginTest.java"

However I am getting error org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance

What is the correct way to manipulate a env var and send the created var as a parameter for a later step in declarative pipeline?

ddd
  • 4,665
  • 14
  • 69
  • 125

1 Answers1

2

it's not allowing you to call Jenkins.instance. But you don't need to do that to get the environment variables. env.REL_VER works, like this:

pipeline {
  agent { label 'docker' }
  environment {
    REL_VER = '0.1-alpha1'
  }
  stages {
    stage('build') {
      steps {
        script {
          def osgi_ver = env.REL_VER.tokenize('-')[0]
          echo "osgi_ver in script block: ${osgi_ver}"
          withMaven(maven: 'maven-3.3.9', mavenSettingsConfig: 'dist-maven-settings', mavenLocalRepo: '.m2repo') {
            sshagent (credentials: ['dist-serv']) {
              sh "sed -i '/setSystemExtraPackages/s/.*/\t\t.setSystemExtraPackages(new String[]{\"com.xxx;version=${osgi_ver}\"}));/' DsgPluginTest.java"
            }
          }
        }
      }
    }
  }
}

note that if you're defining a local variable in a script block, all references to it must also be in the same script block.

burnettk
  • 13,557
  • 4
  • 51
  • 52