I've read following documents regarding on serializing local variables: 
https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md#serializing-local-variables

After reading, I try to test my understanding with an hands-on example like 
this:

pipeline {
  agent {
    node { label 'linux' }
  }
  stages {
    stage('1') {
      steps {
        script {
          def matcher = '123' =~ /^\d+$/
          if (matcher.matches()) {
            sh "echo \"it is a number!:  ${matcher[0]}\""
          }
        }
      }
    }
  }
}

If I understood correctly, one way to fix the issue here is to introduce a 
method annotated with @NonCPS:

pipeline {
  agent {
    node { label 'linux' }
  }
  stages {
    stage('1') {
      steps {
        script {
          def number = tryGetNumber('123')
          if (number) {
            sh "echo \"it is a number!:  ${number}\""
          }
        }
      }
    }
  }
}
 
@NonCPS // commenting this line also works!?
def tryGetNumber(text) {
  def matcher = text =~ /^\d+$/
  if (matcher.matches()) {
    return matcher[0]
  }
  return null
}

This last example code 
*works without @NonCPS annotation*
I've tried similar other non-serializable-local-variable cases, but all 
worked without @NonCPS annotation. Only introducing a method is suffice to 
fix the issue.

I'm not sure if I misread the documents. When should @NonCPS be used? Is it 
only for performance improvement? (so that non-necessary local variables 
not written to disk)

-- 
You received this message because you are subscribed to the Google Groups 
"Jenkins Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to jenkinsci-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/jenkinsci-users/cd3166a0-731d-477c-909c-28de7cdddc93n%40googlegroups.com.

Reply via email to