如何在Git克隆/同步失败时将Jenkins构建标记为中止而非失败
Got it, let's tackle this problem. You want Jenkins to mark the build as ABORTED (not failed) when the Git clone/submodule sync fails, but keep the failure status for the C# build step. Here are two detailed solutions depending on whether you're using a Freestyle project or a Pipeline project:
Solution 1: For Freestyle Projects
Since the default Git source management step marks the build as failed on error, we need to replace it with manual Git execution and control the build status ourselves.
Step-by-Step Setup
Disable the default Git source management
Go to your job configuration → Source Code Management, uncheck "Git". We'll handle cloning manually instead.Add a build step to run Git clone (with timeout and submodules)
Choose either Execute shell (for Linux agents) or Execute Windows batch command (for Windows agents):- Linux Shell:
# Clone repo with submodules, wrap in timeout to enforce 30-minute limit timeout --signal=SIGKILL 30m git clone --recurse-submodules <YOUR_GIT_REPO_URL> . # Save exit code to a properties file for later check echo "git_clone_exit_code=$?" > git_clone_result.properties - Windows Batch:
Note: For Windows, you can wrap the git command in@echo off git clone --recurse-submodules <YOUR_GIT_REPO_URL> . echo git_clone_exit_code=%errorlevel% > git_clone_result.propertiestimeout /t 1800 /nobreak(1800 seconds = 30 minutes) if you need a hard timeout, but Git's native flags or PowerShell timeout may be more reliable.
- Linux Shell:
Inject the Git exit code as an environment variable
Add a build step → Inject environment variables → Under "Properties File Path", entergit_clone_result.properties. This makes thegit_clone_exit_codevariable available in subsequent steps.Add a system Groovy script to set build status to ABORTED on clone failure
Add a build step → Execute system Groovy script, paste this code:def build = Thread.currentThread().executable def gitExitCode = build.getEnvironment(null).get('git_clone_exit_code') if (gitExitCode != '0') { // Mark build as ABORTED build.setResult(hudson.model.Result.ABORTED) // Stop further build steps throw new InterruptedException("Git clone failed with exit code ${gitExitCode}, aborting build") }Add your C# build step
Now add your normal C# build steps (e.g.,dotnet buildor MSBuild commands). If this step fails, Jenkins will mark the build as failed as expected.
Solution 2: For Pipeline Projects (Recommended)
Pipeline gives you more flexibility to handle errors directly in code. Here's a clean implementation:
Pipeline Code
pipeline { agent any stages { stage('Git Clone (With Submodules)') { steps { script { try { // Enforce 30-minute timeout for clone + submodule sync timeout(time: 30, unit: 'MINUTES') { git( url: '<YOUR_GIT_REPO_URL>', credentialsId: '<YOUR_CREDENTIALS_ID>', // Optional: for private repos extensions: [ [$class: 'SubmoduleOption', recursiveSubmodules: true] ] ) } } catch (Exception cloneError) { // Mark build as ABORTED on any clone failure (timeout, network issues, etc.) currentBuild.result = 'ABORTED' echo "Git clone failed: ${cloneError.getMessage()}" // Terminate the pipeline immediately error "Aborting build due to Git clone failure" } } } } stage('Build C# Project') { steps { // Replace with your actual C# build command bat 'dotnet build YourSolution.sln' // Use 'sh' instead of 'bat' for Linux agents } post { failure { echo "C# build failed - marking build as FAILED (as expected)" } } } } }
How It Works
- The
timeoutblock ensures the clone process is killed after 30 minutes, throwing an exception that we catch. - Any exception during the clone (timeout, network errors, submodule sync issues) triggers the catch block, where we set the build result to
ABORTEDand terminate the pipeline. - The C# build stage runs only if the clone succeeds. If it fails, Jenkins will keep the default
FAILEDstatus, which aligns with your requirement.
Key Notes
- For Freestyle projects, you'll need these plugins installed: Groovy, EnvInject, and optionally Conditional BuildStep (if you want to skip the C# build step conditionally).
- For private repos, make sure your Jenkins agent has access (either via SSH keys configured in the agent, or using Jenkins credentials in the Pipeline/git command).
内容的提问来源于stack exchange,提问作者Mani Vannan

