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.

One Reply to “Variable as a Groovy map key”

  1. Hi
    If I need to define the map based on the parameter input of the job, how can I do it?
    Eg: user inputs person1, person2, person3 as input
    map needs to be created for each person –
    ie person1 [ id: ‘ ‘ , name: ‘ ‘]
    person2 [ id: ‘ ‘, name: ‘ ‘]
    etc

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.