Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

Good day, Habr!

Today I would like to share one of the ways how to use Active Choices Plugin do the task in Jenkins the most unified and understandable for the user.

Introduction

Such an abbreviation as DevOps is not something new for the IT community for a long time. For many people, the phrase β€œmake DevOps” is associated with some kind of magic button, when clicked, the application code automatically turns into a deployed and tested application (it’s actually more complicated, but we abstract from all processes).

So, we received an order to make such a magic button so that administrators can deploy the application with one click. There are various types of implementation of this task: starting from writing a bot for any of the messengers and ending with the development of a separate application. Nevertheless, the goal of all this is the same - to make the launch of the assembly and deployment of the application as transparent and convenient as possible.

In our case, we will use Jenkins.


Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

Task

Create a convenient Jenkins job that will run the assembly and (or) deployment of the selected microservice of a certain version.

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

Input data

We have several repositories that contain the source code of various microservices.

Defining parameters

The input of our job should receive the following parameters:

  1. The URL of the repository with the microservice code that we want to build and deploy when running the job.
  2. The ID of the commit to build from.

AS IS

The easiest way to accomplish this task is to create two parameters of type String.

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

In this case, the user will need to manually enter the path to the repository and the commit id, which, you see, is not very convenient.

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

AS TO BE

Now let's try another type of parameters to see all its advantages.
Let's create the first parameter with type Choice Parameter, the second - Active Choices Reactive Reference Parameter. In the parameter with the Choice type, we will manually add the names of the repositories in the Choices field, where the code of our microservices is stored.

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

If the audience likes this article, then in the next article I will describe the process of configuring tasks in Jenkins using the description through the code (Configuration as code), i.e. we won't need to manually enter the names of the repositories and create parameters, everything will happen automatically (our code will get the list of repositories from the SCM and create a parameter with this list).

The values ​​of the second parameter will be filled dynamically, depending on what value the first parameter takes (test1 or test2), because each repository has its own list of commits.

Active Choices Reactive Reference Parameter has the following fields to fill in:

  1. Name – parameter name.
  2. Script - code that will be executed every time the value of the parameter from the Referenced parameter field is changed (in our case, when we choose between test1 and test2).
  3. Description – short description of the parameter.
  4. Choice Type - the type of the object returned by the script (in our case, we will return the html code).
  5. referenced parameter – the name of the parameter, when the value of which changes, the code from the Script section will be executed.

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

Let's proceed directly to filling in the most important field in this parameter. We are offered two types of implementation to choose from: using Groovy Script or Scriptler Script.
We choose the first one, since Scriptler is just a plugin that saves the scripts you have already written and allows you to use them in other tasks without copy-pasting again.

Groovy code to get all commits from a selected repository:

AUTH = "Π»ΠΎΠ³ΠΈΠ½ ΠΈ ΠΏΠ°Ρ€ΠΎΠ»ΡŒ Π² Base64"                           
GIT_URL = "url до вашСй SCM (https://bitbucket.org/)"                       
PROJECT_NAME = "имя ΠΏΡ€ΠΎΠ΅ΠΊΡ‚Π½ΠΎΠΉ области, Π³Π΄Π΅ находятся Ρ€Π΅ΠΏΠΎΠ·ΠΈΡ‚ΠΎΡ€ΠΈΠΈ"

def htmlBuild() {
    html = """
            <html>
            <head>
            <meta charset="windows-1251">
            <style type="text/css">
            div.grayTable {
            text-align: left;
            border-collapse: collapse;
            }
            .divTable.grayTable .divTableCell, .divTable.grayTable .divTableHead {
            padding: 0px 3px;
            }
            .divTable.grayTable .divTableBody .divTableCell {
            font-size: 13px;
            }
            </style>
            </head>
            <body>
        """

    def commitOptions = ""
    getCommitsForMicroservice(MICROSERVICE_NAME).each {
        commitOptions += "<option style='font-style: italic' value='COMMIT=${it.getKey()}'>${it}</option>"
    }
    html += """<p style="display: inline-block;">
        <select id="commit_id" size="1" name="value">
            ${commitOptions}
        </select></p></div>"""

    html += """
            </div>
            </div>
            </div>
            </body>
            </html>
         """
    return html
}

def getCommitsForMicroservice(microserviceRepo) {
    def commits = [:]
    def endpoint = GIT_URL + "/rest/api/1.0/projects/${PROJECT_NAME}/repos/${microserviceRepo}/commits"
    def conn = new URL(endpoint).openConnection()
    conn.setRequestProperty("Authorization", "Basic ${AUTH}")
    def response = new groovy.json.JsonSlurper().parseText(conn.content.text)
    response.values.each {
        commits.put(it.displayId, it.message)
    }
    return commits
}

return htmlBuild()

Without going into details, this code receives the name of the microservice (MICROSERVICE_NAME) as input, sends a request to bitbucket (method getCommitsForMicroservice) using its API and gets the id and commit message of all commits for the given microservice.
As mentioned earlier, this code should return the html that will be displayed on the page Build with Parameters in Jenkins, so we wrap all the received values ​​from Bitbucket in a list and add them to the select.

After completing all the steps, we should get such a beautiful page Build with Parameters.

If you chose the test1 microservice:

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

If you chose the test2 microservice:

Creating dynamic parameters in a Jenkins job, or how to make your task user-friendly

Agree that it will be much more convenient for the user to interact with your task in this way than to copy the url every time and look for the required commit id.

PS This article is a very simplified example that may not be of practical use as it is, as assemblies have many more different options, but the purpose of this article was to show how the tool works, not to provide a working solution.

PSS As I wrote earlier, if this article is useful, then the next one will be about dynamic configuration of Jenkins tasks via code.

Source: habr.com

Add a comment