Variable as a Groovy map key

Maps are the structures which can be very helpful. I’m not a developer, so I’m sure that many of you will take this post with a grain of salt. Even though, If you use Jenkins, you can face the same problem I faced some time ago. My experience with Groovy is limited to Jenkins job DSL configuration, but I always try to create a configuration as simple as possible. So sometimes my scripts are full of loops, conditionals, and variables. In one of my job, I tried to use a map and create a nested loop, where one of the keys should be equal to another key. In other words, I wanted to use a variable as a Groovy map key. Hard to understand? Let me show you what I mean.

What’s the problem?

Please take a look at the following example:

What is the suspected output of the code above? Something like that:

But after the code execution, we won’t see that output. We will this:

It is not what we want.

How to properly use a variable as a Groovy map key?

We have to use quotation marks. Yes, you read this well. Quotation marks. Probably it’s something obvious for Developers, but if someone is not familiar with any programming language, it could be a small surprise. Anyway, there is the proper way of the example I’ve shown you above:

As the result you will get the following output:

And that’s all. Now you can use a variable as a Groovy map key in your code. It’s very useful for every Jenkins Administrator – it is possible to create a very flexible and scalable code of your job configurations.

Leave a Reply

Your email address will not be published. Required fields are marked *