Cloud Native 5 min read

Implementing Elastic Jenkins Agents on Kubernetes Using ScriptConsole and Shared Library

This tutorial explains how to automatically create and delete Jenkins agent pods on a Kubernetes cluster for each pipeline run by storing Groovy scripts in a shared library, loading them with ScriptConsole, and invoking the Kubernetes API through Jenkins.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Implementing Elastic Jenkins Agents on Kubernetes Using ScriptConsole and Shared Library

The article continues a CI/CD series focused on building an elastic build pool on Kubernetes, demonstrating how to automatically provision a Jenkins agent for a pipeline run and recycle it after the job finishes.

The approach stores the Groovy scripts that create and delete agents in the resources/scripts directory of a shared library, loads them in the pipeline with libraryResource, replaces the placeholder __AGENT_NAME__ with a generated name, writes the script to a local file, and then executes it via Jenkins ScriptConsole API after obtaining a CSRF crumb.

Example of loading the shared library and setting environment variables:

@Library("mylib@feature-k8s") _      // load shared library<br/>import org.devops.*<br/><br/>env.namespace = "jenkins"<br/>env.agentName = "jenkinsagent${UUID.randomUUID().toString()[0..7]}"

The following Groovy helper methods perform the actual API calls. RunScriptConsole sends the script content to /scriptText using curl with the crumb header, and GetCrumb retrieves the crumb value from /crumbIssuer/api/json:

// ScriptConsole runs a script<br/>def RunScriptConsole(scriptContent, crumb){<br/>    response = sh returnStdout: true,<br/>        script: """<br/>            curl -s -d \"script=$(cat ${scriptContent})\" \
/>            --header \"Jenkins-Crumb:${crumb}\" \
/>            -X POST http://admin:[email protected]:8080/scriptText
/>        """<br/>    try {<br/>        response = readJSON text: response - "Result: "<br/>    } catch(e){<br/>        println(e)<br/>    }<br/>    return response<br/>}<br/><br/>// Get Crumb value<br/>def GetCrumb(){<br/>    response = sh returnStdout: true,<br/>        script: """<br/>            curl -s -u admin:admin \
/>            --location \
/>            --request GET 'http://192.168.1.200:8080/crumbIssuer/api/json'
/>        """<br/>    response = readJSON text: response<br/>    return response.crumb<br/>}

Pipeline stages use these helpers to create and delete the agent pod:

stage("CreateBuildENV"){<br/>    steps{<br/>        script{<br/>            // Get agent create script<br/>            scriptContent = libraryResource 'scripts/create_jenkins_agent.groovy'<br/>            scriptContent = scriptContent.replaceAll("__AGENT_NAME__", "${env.agentName}")<br/>            writeFile file: 'create_jenkins_agent.groovy', text: scriptContent<br/><br/>            // Run agent create script<br/>            jenkinsCrumb = GetCrumb()<br/>            agentConfig = RunScriptConsole("create_jenkins_agent.groovy", jenkinsCrumb)<br/>        }<br/>    }<br/>}<br/><br/>stage("DeleteBuildENV"){<br/>    steps{<br/>        script{<br/>            // Get agent delete script<br/>            scriptContent = libraryResource 'scripts/delete_jenkins_agent.groovy'<br/>            scriptContent = scriptContent.replaceAll("__AGENT_NAME__", "${env.agentName}")<br/>            writeFile file: 'delete_jenkins_agent.groovy', text: scriptContent<br/><br/>            // Run agent delete script<br/>            jenkinsCrumb = GetCrumb()<br/>            agentConfig = RunScriptConsole("delete_jenkins_agent.groovy", jenkinsCrumb)<br/>        }<br/>    }<br/>}

The current implementation uses plain credentials in the curl command, which should be moved to Jenkins credentials for better security. It also notes that the created agent is not yet connected to the Jenkins master, so further configuration is required.

In summary, when the pipeline runs, a Jenkins agent pod is automatically created and later destroyed, demonstrating elastic build pool capabilities; a live session is advertised for deeper debugging of the Kubernetes API and full elastic build pool setup.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Cloud Nativeci/cdKubernetesDevOpsGroovyJenkinsScriptConsole
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.