Sending HTTP requests with Jenkins Pipelines
1 min read

Sending HTTP requests with Jenkins Pipelines

Sending HTTP requests with Jenkins Pipelines

As part of the CI/CD process, we might need to communicate with some external services' APIs (e.g. notifying elastic search of a new index alias). I found an easy way to do it: Using a jenkins plugin.

Jenkins plugin

Jenkins has a HTTP request plugin. If you install it (or have it installed), you have the ability to send HTTP requests to external servers from Jenkins. Fortunately, this plugin also plays wery well with pipelines. You can sent practically any (REST) command to a destination:

httpRequest (consoleLogResponseBody: true,
      contentType: 'APPLICATION_JSON',
      httpMode: 'POST',
      requestBody: command,
      url: "${machine}/_aliases",
      validResponseCodes: '200')

You can customisethe request body, the headers etc. and have a list of valid response codes (i.e. throwing an error if the result doesn't match).

Avoiding inline calls

I ended up defining a function to take care of my notification needs:

def changeAlias(machine, fromIndex, toIndex) {
    def command = """{
        \"actions\":[
          { \"remove\" : { \"index\" : \"${fromIndex}\", \"alias\" : \"main\" } },
          { \"add\" : { \"index\" : \"${toIndex}\", \"alias\" : \"main\" } }]
      }"""
    echo(command)
    response = httpRequest (consoleLogResponseBody: true,
      contentType: 'APPLICATION_JSON',
      httpMode: 'POST',
      requestBody: command,
      url: "${machine}/_aliases",
      validResponseCodes: '200')
    return response
}

It sends a command to an elastic seatch instance to change the main alias from one index to another.

The function is then called in a script step:

changeAlias("http://mymachine:9200", 'main_index', 'backup_index')

HTH,

PS: I heve found out there's a way via the java networking API, but IMHO it's too verbose.