如何为Jenkins配置Git触发器(基于TFS2017环境)
Got it, let's walk through exactly how to tie Jenkins into your TFS 2017 setup—with 150-200 Git repos each having 10-30 branches, scalability and proper trigger logic are key. Here's a practical, step-by-step approach to get builds triggering on code pushes, with all the repo/branch details you need passed through:
First, we need to set up TFS to send a POST request to Jenkins every time code is pushed to any of your repos. Here's how:
- Log into your TFS 2017 instance, navigate to your team project collection, and go to Project Settings > Service Hooks.
- Click Create subscription, select Git repository as the event source, then pick Code pushed as the trigger event.
- Next, choose Generic service (this is more flexible than the built-in Jenkins option for custom payloads) as the service to notify.
- Enter your Jenkins job's trigger URL—if you're using the Generic Webhook Trigger Plugin (we'll cover this next), the URL will look like:
http://<your-jenkins-url>/job/<your-job-name>/generic-webhook-trigger/invoke - Optional but recommended: Add a secret token to the URL (e.g.,
?token=YOUR_SECRET_TOKEN) to prevent unauthorized trigger requests.
- Enter your Jenkins job's trigger URL—if you're using the Generic Webhook Trigger Plugin (we'll cover this next), the URL will look like:
- Configure optional filters if you don't want every branch push to trigger a build—for example, you can limit triggers to branches matching
refs/heads/mainorrefs/heads/release/*. - Save the subscription, and repeat (or automate, see section 3) for all your repos.
You'll need a few core Jenkins plugins to handle the trigger and parameter passing:
- Generic Webhook Trigger Plugin: Parses the JSON payload TFS sends and extracts variables like branch name and repo URL.
- Git Plugin: Pulls code from your TFS Git repos.
- Pipeline Plugin (optional but highly recommended): Makes it easier to define reusable build/deploy/test workflows as code.
For Pipeline Jobs (Most Flexible)
Create a new Pipeline job, then configure these key parts:
- In Build Triggers, check Generic Webhook Trigger.
- Under Post content parameters, define the variables you need:
- Branch Name: Set variable name
BRANCH_NAME, JSON path$.refUpdates[0].name, then add a regex replacementrefs/heads/(.*)→$1to strip therefs/heads/prefix and get a clean branch name. - Repo URL: Variable name
REPO_URL, JSON path$.repository.url. - Repo Name: Variable name
REPO_NAME, JSON path$.repository.name.
- Branch Name: Set variable name
- Use these variables in your Jenkinsfile to drive the workflow. Example snippet:
pipeline { agent any parameters { string(name: 'BRANCH_NAME', defaultValue: 'main', description: 'Branch from TFS code push') string(name: 'REPO_URL', defaultValue: '', description: 'TFS Git repo URL') string(name: 'REPO_NAME', defaultValue: '', description: 'Name of the TFS repo') } stages { stage('Checkout Code') { steps { git url: params.REPO_URL, branch: params.BRANCH_NAME } } stage('TFS Build') { steps { // Call your existing TFS build process—use tf cli or TFS REST API sh 'tf build start /collection:<your-tfs-collection-url> /definition:<your-build-def-id> /branch:$BRANCH_NAME' } } stage('External Deployment') { steps { // Run your deployment script/tools (Ansible, kubectl, etc.) sh './deploy-script.sh --branch $BRANCH_NAME --repo $REPO_NAME' } } stage('Run Tests') { steps { // Execute your test suite sh './run-tests.sh --target-branch $BRANCH_NAME' } } } }
For Freestyle Jobs
If you prefer Freestyle over Pipeline:
- In Source Code Management, select Git, then use
$REPO_URLas the Repository URL and*/$BRANCH_NAMEas the Branch Specifier. - In build steps, reference the variables directly (e.g.,
$BRANCH_NAME,$REPO_URL) in scripts or commands.
Manually creating webhooks for every repo is tedious—use this PowerShell script to automate the process via TFS REST API:
$tfsCollectionUrl = "http://<your-tfs-server>:8080/tfs/DefaultCollection" $jenkinsTriggerUrl = "http://<your-jenkins-url>/job/<your-job-name>/generic-webhook-trigger/invoke?token=YOUR_SECRET" $projectName = "Your-Team-Project" # Fetch all Git repos in the project $repos = Invoke-RestMethod -Uri "$tfsCollectionUrl/$projectName/_apis/git/repositories?api-version=3.0" -Method Get foreach ($repo in $repos.value) { # Build the webhook payload $webhookPayload = @{ eventType = "git.push" resourceVersion = "1.0" consumerId = "webHooks" consumerActionId = "httpRequest" publisherId = "tfs" resource = @{ repository = @{ id = $repo.id } } consumerInputs = @{ url = $jenkinsTriggerUrl httpMethod = "POST" headers = "Content-Type: application/json" } } | ConvertTo-Json -Depth 10 # Create the webhook subscription Invoke-RestMethod -Uri "$tfsCollectionUrl/_apis/hooks/subscriptions?api-version=3.0" -Method Post -Body $webhookPayload -ContentType "application/json" Write-Host "Added webhook for repo: $($repo.name)" }
- Push a small change to any branch in one of your TFS repos.
- Check Jenkins' build history to confirm the job triggered automatically.
- Verify the
BRANCH_NAME,REPO_URL, andREPO_NAMEparameters are correctly populated in the build logs. - Walk through each stage (checkout, build, deploy, test) to ensure everything runs as expected.
内容的提问来源于stack exchange,提问作者NibblesMK

