如何通过TeamCity API避免同一分支已有构建时重复触发构建?
I’ve run into this exact issue before—JIRA Automation has no visibility into TeamCity’s build state by default, so it’ll happily fire off duplicate builds for the same branch if your rule triggers multiple times. Here’s how to add a "check first, trigger second" guardrail:
Step 1: Add a Pre-Check Webhook to Query TeamCity’s Build State
First, insert a Send webhook request action before your existing build-triggering webhook. This will check if there’s already a running or queued build for your target branch and build type.
- Request URL:
http://teamcity.url/app/rest/builds?locator=buildType:<buildTypeId>,branch:{{issue.fields.branch}},state:running,queued- Breakdown of the locator parameters:
buildType:<buildTypeId>: Targets your specific TeamCity build configurationbranch:{{issue.fields.branch}}: Uses the branch from your JIRA issuestate:running,queued: Checks both actively running builds and those waiting in the queue
- Breakdown of the locator parameters:
- Request Method:
GET - Authentication: Use TeamCity’s HTTP Basic Auth (create a dedicated service account with "View builds" permissions, and use its username + API token)
- Store response: Enable this option and assign a variable name like
existingBuilds(so we can reference the result later)
Step 2: Add a Conditional Check
Next, add a Condition component right after the pre-check webhook. This will only proceed to trigger the build if no existing builds are found.
Use this JIRA Smart Value condition:
{{webhookResponse.body.builds.size}} == 0
- This checks if the
buildsarray returned by TeamCity is empty (meaning no matching running/queued builds exist)
Step 3: Keep Your Original Build-Triggering Webhook
Move your original build-triggering webhook inside the conditional block (so it only runs if the condition passes). Your original setup stays mostly the same:
- Request URL:
http://teamcity.url/app/rest/buildQueue?buildTypeId=<buildTypeId> - Request Method:
POST - Request Body:
<build branchName="{{issue.fields.branch}}"> <buildType id="<buildTypeId>"/> </build> - Don’t forget to keep the same authentication setup as the pre-check webhook
Pro Tips
- Test the pre-check first: Add a Log action after the pre-check webhook to output
{{webhookResponse.body}}—this lets you verify TeamCity is returning the correct build data before relying on the condition. - Handle special branch names: If your branch names have spaces or special characters, use
{{issue.fields.branch.urlEncode}}in the pre-check URL to safely encode the branch name. - Lock down permissions: Make sure your TeamCity service account only has the minimum permissions needed (View builds + Trigger builds) to follow security best practices.
内容的提问来源于stack exchange,提问作者tCode

