You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求Jenkins插件:读取项目列表文件并生成构建状态报告

Hey there! Let me share two reliable ways to solve your problem—one using a Jenkins Pipeline (super flexible and integrated) and another with the Jenkins CLI if you prefer command-line workflows.

Solution 1: Custom Jenkins Pipeline with Pipeline Utility Steps Plugin

This approach lets you build a reusable pipeline that reads your project list file, fetches the required build statuses, and generates a clean report right within Jenkins.

Step 1: Install the Required Plugin

First, install the Pipeline Utility Steps Plugin from Jenkins' plugin manager. This plugin adds handy functions for reading files, which we'll use to load your project list.

Step 2: Create the Pipeline Script

Create a new Pipeline job in Jenkins, then use this script (adjust paths and settings to match your environment):

pipeline {
    agent any
    stages {
        stage('Generate Build Status Report') {
            steps {
                script {
                    // Read your project list file (one project name per line)
                    def projectList = readFile('projects.txt')
                        .split('\n')
                        .collect { it.trim() }
                        .findAll { it } // Skip empty lines
                    
                    // Initialize report with Markdown formatting
                    def report = "### Jenkins Project Build Status Report\n\n"
                    report += "| Project Name | Last Build Time | Build Success? | Last Successful Build Time |\n"
                    report += "|--------------|-----------------|----------------|-----------------------------|\n"
                    
                    // Loop through each project to fetch statuses
                    projectList.each { projectName ->
                        def job = Jenkins.instance.getItem(projectName)
                        
                        if (job) {
                            def lastBuild = job.lastBuild
                            def lastSuccessfulBuild = job.lastSuccessfulBuild
                            
                            // Format last build time
                            def lastBuildTime = lastBuild ? 
                                lastBuild.getTime().format('yyyy-MM-dd HH:mm:ss') : 
                                'Never Built'
                            
                            // Check if last build succeeded
                            def buildSuccess = lastBuild ? 
                                (lastBuild.result == Result.SUCCESS ? '✅ Success' : "❌ ${lastBuild.result}") : 
                                'N/A'
                            
                            // Format last successful build time
                            def lastSuccessTime = lastSuccessfulBuild ? 
                                lastSuccessfulBuild.getTime().format('yyyy-MM-dd HH:mm:ss') : 
                                'Never Succeeded'
                            
                            // Add row to report
                            report += "| ${projectName} | ${lastBuildTime} | ${buildSuccess} | ${lastSuccessTime} |\n"
                        } else {
                            // Handle cases where the project doesn't exist in Jenkins
                            report += "| ${projectName} | N/A | Project Not Found | N/A |\n"
                        }
                    }
                    
                    // Print report to console
                    println report
                    
                    // Optional: Save report as HTML and archive it for later access
                    writeFile file: 'build-status-report.html', text: report
                    archiveArtifacts artifacts: 'build-status-report.html', fingerprint: true
                }
            }
        }
    }
}

How It Works

  • Reads projects.txt (place this file in your job's workspace, or use a full path if it's stored elsewhere)
  • Fetches each Jenkins project's build data using the Jenkins API
  • Generates a human-readable Markdown report (and optionally saves it as an archived HTML file)
Solution 2: Jenkins CLI + Shell Script

If you prefer running this outside of Jenkins (e.g., as a scheduled task), use the Jenkins CLI with a shell script to generate the report.

Step 1: Prepare Jenkins CLI

Download the Jenkins CLI JAR from your Jenkins instance at http://your-jenkins-url:8080/jnlpJars/jenkins-cli.jar.

Step 2: Shell Script Example

Save this as jenkins-build-status.sh (update JENKINS_URL and other variables to match your setup):

#!/bin/bash

# Configure your Jenkins details
JENKINS_URL="http://your-jenkins-url:8080"
JENKINS_CLI="java -jar jenkins-cli.jar -s $JENKINS_URL --username your-username --password your-api-token"
PROJECT_FILE="projects.txt"

# Generate report header
echo "### Jenkins Project Build Status Report"
echo ""
echo "| Project Name | Last Build Time | Build Success? | Last Successful Build Time |"
echo "|--------------|-----------------|----------------|-----------------------------|"

# Loop through each project in the list
while IFS= read -r project; do
    project=$(echo "$project" | xargs) # Trim whitespace
    [ -z "$project" ] && continue # Skip empty lines

    # Fetch last build details via CLI (parsed from job XML)
    last_build_data=$($JENKINS_CLI get-job "$project" | xmllint --xpath '/*/lastBuild/timestamp/text() | /*/lastBuild/result/text()' - 2>/dev/null)
    last_build_timestamp=$(echo "$last_build_data" | sed -n '1p')
    last_build_result=$(echo "$last_build_data" | sed -n '2p')

    # Fetch last successful build timestamp
    last_success_timestamp=$($JENKINS_CLI get-job "$project" | xmllint --xpath '/*/lastSuccessfulBuild/timestamp/text()' - 2>/dev/null)

    # Format timestamps to readable dates
    last_build_time="Never Built"
    [ -n "$last_build_timestamp" ] && last_build_time=$(date -d @"$((last_build_timestamp/1000))" '+%Y-%m-%d %H:%M:%S')

    build_success="N/A"
    if [ -n "$last_build_result" ]; then
        if [ "$last_build_result" = "SUCCESS" ]; then
            build_success="✅ Success"
        else
            build_success="❌ ${last_build_result}"
        fi
    fi

    last_success_time="Never Succeeded"
    [ -n "$last_success_timestamp" ] && last_success_time=$(date -d @"$((last_success_timestamp/1000))" '+%Y-%m-%d %H:%M:%S')

    # Print report row
    echo "| $project | $last_build_time | $build_success | $last_success_time |"
done < "$PROJECT_FILE"

How to Run

  1. Make the script executable: chmod +x jenkins-build-status.sh
  2. Place your projects.txt file in the same directory
  3. Run the script: ./jenkins-build-status.sh
Key Notes
  • For the Pipeline approach: You'll need to approve Jenkins API access in Manage Jenkins > In-process Script Approval (the first time you run the pipeline, it will prompt you to approve methods like Jenkins.instance.getItem).
  • For the CLI approach: Use an API token instead of your password (generate one from your Jenkins user profile) for better security.
  • Both methods work with any project list file where each line contains a single Jenkins project name.

内容的提问来源于stack exchange,提问作者Manoj Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:22:50