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

如何在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

  1. Disable the default Git source management
    Go to your job configuration → Source Code Management, uncheck "Git". We'll handle cloning manually instead.

  2. 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:
      @echo off
      git clone --recurse-submodules <YOUR_GIT_REPO_URL> .
      echo git_clone_exit_code=%errorlevel% > git_clone_result.properties
      
      Note: For Windows, you can wrap the git command in timeout /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.
  3. Inject the Git exit code as an environment variable
    Add a build step → Inject environment variables → Under "Properties File Path", enter git_clone_result.properties. This makes the git_clone_exit_code variable available in subsequent steps.

  4. 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")
    }
    
  5. Add your C# build step
    Now add your normal C# build steps (e.g., dotnet build or MSBuild commands). If this step fails, Jenkins will mark the build as failed as expected.


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 timeout block 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 ABORTED and terminate the pipeline.
  • The C# build stage runs only if the clone succeeds. If it fails, Jenkins will keep the default FAILED status, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:14:51