Eitan Ashtamker
Eitan Ashtamker

Reputation: 65

Variable inside a variable in Jenkinsfile

What is the correct Jenkinsfile syntax in order to use a variable value when executing command with another variable?

For example:

def lastItemIndex = "${json.items.size()-1}"
def path = "${json.items[${lastItemIndex}].assets.downloadUrl}"
echo "${path}"

Upvotes: 1

Views: 1637

Answers (2)

Matthew Schuchard
Matthew Schuchard

Reputation: 28854

The syntax in your second row is mostly fine. Your problem is that you are storing the return of lastItemIndex as a String and then attempting to use it as an Integer in your second row of code.

You can fix your first row with:

lastItemIndex = json.items.size() - 1

and then it will be an Integer type and def path = "${json.items[lastItemIndex].assets.downloadUrl}" will succeed.

Alternatively, you could just have the second line of code with:

def path = "${json.items[-1].assets.downloadUrl}"

to access the last element of the array.

Note that in general if you need to convert a String to an Integer within a Jenkins Pipeline via Groovy you can utilize the to_Integer method.

Upvotes: 1

Eitan Ashtamker
Eitan Ashtamker

Reputation: 65

Thanks to Matt, eventually that what works for me:

def lastItemIndex = json.items.size()-1

def path = json.items[lastItemIndex].assets.downloadUrl

Upvotes: 0

Related Questions