Apr 18 2020

Auto Register a Jenkins Slave with REST API

Published by at 4:00 pm under Jenkins

Here is how to create a Jenkins node that registers automatically with a REST API call on the master. Most of the work is to build some json code that describes the new Jenkins slave. The configuration can be slightly different depending on the node settings you are willing to apply. To get exactly what you want, you may create a dummy slave manually and capture the JSON object in your browser developer tool’s network tab while you click on “Save”. In the meantime, here is mine, assuming agent launches with a startup script:

{
   "name": "my_jenkins_slave",
   "nodeDescription": "my Jenkins slave",
   "numExecutors": "2",
   "remoteFS": "/home/jenkins",
   "labelString": "slave",
   "mode": "EXCLUSIVE",
   "": [
      "hudson.slaves.JNLPLauncher",
      "hudson.slaves.RetentionStrategy$Always"
   ],
   "launcher": {
      "stapler-class": "hudson.slaves.JNLPLauncher",
      "$class": "hudson.slaves.JNLPLauncher",
      "workDirSettings": {
         "disabled": true,
         "workDirPath": "",
         "internalDir": "remoting",
         "failIfWorkDirIsMissing": false
      },
      "tunnel": "",
      "vmargs": ""
   },
   "retentionStrategy": {
      "stapler-class": "hudson.slaves.RetentionStrategy$Always",
      "$class": "hudson.slaves.RetentionStrategy$Always"
   },
   "nodeProperties": {
      "stapler-class-bag": "true",
      "hudson-slaves-EnvironmentVariablesNodeProperty": {
         "env": [
            {
               "key": "JAVA_HOME",
               "value": "/usr/lib/jvm/java-8-openjdk-amd64"
            }
         ]
      },
      "_comment:": {
         "hudson-tools-ToolLocationNodeProperty": {
           "locations": [
               {
                  "key": "hudson.model.JDK$DescriptorImpl@JAVA-8",
                  "home": "/usr/bin/java"
               }
            ]
         }
      }
   }
}


All you need is define the 3 following environment variables in the shell:

jenkins_user=my_jenkins_user
jenkins_token=my_jenkins_token
jenkins_url=https://jenkins.mydomain.lan


And post above JSON file with a simple curl:

$ curl -L -s -o /dev/null -w "%{http_code}" -u $jenkins_user:$jenkins_token \
-H "Content-Type:application/x-www-form-urlencoded" -X POST \
-d "json=$(cat /tmp/node.json)" \
"$jenkins_url/computer/doCreateItem?name=my_jenkins_slave&type=hudson.slaves.DumbSlave"; \
echo
200


If you do not get a 200 response code, run the same skipping “-o /dev/null” to troubleshoot.
Some say you may do the same with different tools like Jenkins CLI or some plugins but Jenkins REST API works through any firewall and is pretty easy to set up.
In the next post, I’ll use this method to automate Jenkins agent registration with Ansible


No responses yet

Trackback URI | Comments RSS

Leave a Reply