Hello and welcome to this community, @Tech_Tan.
To achieve this, I think you could use a combination of Jenkins Pipeline, Groovy scripting, and the Jenkins REST API.
Here is an untested example (because I don’t have an endpoint to receive the events) of how you could maybe implement this:
- Create a Jenkins Pipeline Script: This script will capture the status of each stage and send the data to an endpoint.
- Use the Jenkins REST API: To fetch the status of all running jobs.
Step 1: Jenkins Pipeline Script
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
def startTime = System.currentTimeMillis()
try {
// Your build steps here
echo 'Building...'
} catch (Exception e) {
def endTime = System.currentTimeMillis()
def duration = endTime - startTime
sendStageStatus('Build', 'FAILURE', duration, e.message)
throw e
}
def endTime = System.currentTimeMillis()
def duration = endTime - startTime
sendStageStatus('Build', 'SUCCESS', duration, null)
}
}
}
stage('Test') {
steps {
script {
def startTime = System.currentTimeMillis()
try {
// Your test steps here
echo 'Testing...'
} catch (Exception e) {
def endTime = System.currentTimeMillis()
def duration = endTime - startTime
sendStageStatus('Test', 'FAILURE', duration, e.message)
throw e
}
def endTime = System.currentTimeMillis()
def duration = endTime - startTime
sendStageStatus('Test', 'SUCCESS', duration, null)
}
}
}
}
}
def sendStageStatus(stageName, status, duration, errorMessage) {
def payload = [
stageName: stageName,
status: status,
duration: duration,
errorMessage: errorMessage
]
def jsonPayload = new groovy.json.JsonBuilder(payload).toString()
httpRequest(
httpMode: 'POST',
url: 'http://your-endpoint.com/api/status',
contentType: 'APPLICATION_JSON',
requestBody: jsonPayload
)
}
You will have to accept in Scripts Approvals new groovy.json.JsonBuilder java.lang.Object
and to install the HTTP Request plugin.
Step 2: Fetch Status of All Running Jobs
You should be able to use the Jenkins REST API to fetch the status of all running jobs. Here is an example of how to do this using a Groovy script:
import groovy.json.JsonSlurper
def jenkinsUrl = 'http://your-jenkins-url.com'
def apiUrl = "${jenkinsUrl}/api/json?tree=jobs[name,url,color]"
def getRunningJobs() {
def response = new URL(apiUrl).text
def json = new JsonSlurper().parseText(response)
def runningJobs = json.jobs.findAll { it.color == 'blue_anime' }
return runningJobs
}
def runningJobs = getRunningJobs()
runningJobs.each { job ->
println "Job Name: ${job.name}"
println "Job URL: ${job.url}"
}
You could also do that thanks to bash or python:
#!/bin/bash
JENKINS_URL="http://your-jenkins-url.com"
API_URL="${JENKINS_URL}/api/json?tree=jobs[name,url,color]"
# If your Jenkins requires authentication, use the following variables
# Replace 'your-username' and 'your-api-token' with your actual Jenkins credentials
USERNAME="****"
API_TOKEN="****"
# Fetch the JSON response from Jenkins API using wget
if [ -n "$USERNAME" ] && [ -n "$API_TOKEN" ]; then
response=$(wget --quiet --user=$USERNAME --password=$API_TOKEN --output-document=- $API_URL)
else
response=$(wget --quiet --output-document=- $API_URL)
fi
# Check if the response is empty
if [ -z "$response" ]; then
echo "Failed to fetch data from Jenkins API. Please check your URL and credentials."
exit 1
fi
# Parse the JSON response to find running jobs
echo "$response" | jq -r '.jobs[] | select(.color == "blue_anime" or .color == "blue") | "\(.name) \(.url)"'
import requests
import json
JENKINS_URL = "http://your-jenkins-url.com"
API_URL = f"{JENKINS_URL}/api/json?tree=jobs[name,url,color]"
USERNAME = "****"
API_TOKEN = "****"
# Fetch the JSON response from Jenkins API using requests
response = requests.get(API_URL, auth=(USERNAME, API_TOKEN), headers={"Accept": "application/json"})
# Check if the response is empty
if response.status_code != 200:
print("Failed to fetch data from Jenkins API. Please check your URL and credentials.")
exit(1)
# Parse the JSON response to find running jobs
jobs = response.json().get('jobs', [])
for job in jobs:
if job['color'] in ['blue_anime', 'blue']:
print(f"{job['name']} {job['url']}")