SEB
SEB

Reputation: 49

Jenkins Groovy - overwriting global variable in definition

I have a problem with overwriting an existing global variable value within a definition. A simple example piece of a jenkinsfile:

my_var = 0

def my_def() {
  my_var = 1
}

node {
  stage 'test'
  my_def()
  echo my_var
}

The output of echo is 0 and I'd like it to be 1. I read this post: Groovy: what's the purpose of "def" in "def x = 0"? but I couldn't make it work. I couldn't find any explanations of how to return a value from such a definition.

Upvotes: 2

Views: 2708

Answers (1)

BMitch
BMitch

Reputation: 265130

I believe you want to use transform. Off the top of my head, that would look like:

@groovy.transform.Field int my_var = 0

def my_def() {
  my_var = 1
}

node {
  stage 'test'
  my_def()
  echo my_var
}

Upvotes: 3

Related Questions