Reputation: 65
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}"
First variable is lastItemIndex
and second one is json
.
The second row is not running properly when I tried different options.
Upvotes: 1
Views: 1637
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
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