Search code examples
gitsonarqubebitbucketteamcity

How to work with dynamic parameters in TeamCity?


I am working on integration of BitBucket, TeamCity and SonarQube. My scenario is as follows:

  1. A developer starts a new PR or changes an existing one;
  2. TeamCity starts building the PR automatically;
  3. TeamCity posts the analysis results to SonarQube via SonarQube Runner with -Dsonar.branch.name=%teamcity.build.branch%;
  4. BitBucket requests the analysis details from SonarQube by the branch name and displays them on the PR page.

So the problem is that I cannot deduce the name of the branch the PR is based on. Here is what happens:

  1. I configure TeamCity to listen to the +:refs/pull-requests/*/from reference in the VCS branch specification;
  2. When TeamCity discovers a new PR it starts a build
  3. The name of the branch (teamcity.build.branch) gets to be equal to the number of the PR (because of the asterisk in the reference);
  4. BitBucket cannot retrieve the analysis details by the PR's branch name, because they are stored in SonarQube under the name which is equal to the number of the PR and not the name of the branch.

Solution 1 (dynamic parameters):

  1. to define some sort of a dynamic parameter;
  2. to assign a value to the parameter in one of the build steps;
  3. to use that value to post analysis results to SonarQube.

Solution 2:

  1. to listen to both references: +:refs/pull-requests/*/from and +:refs/heads/*;
  2. to set up a VCS trigger that listens to +:refs/heads/* only;
  3. to fail the build in the first build step if no pull-request reference for the current branch is found.

It does not seem like a good solution.

So it seems to me that the solution should be something like:

  1. to make TeamCity trigger a build when a new PR is found (the way it works now);
  2. to make it to figure out the correct branch name (by commit hash) and store it in a dynamic parameter;
  3. to pass the value of this parameter into SonarQube Runner (-Dsonar.branch.name=%dynamic.branch...%)

I read the documentation about TeamCity predefined branch parameters, but have not found anything helpful.

Please help me figure out how to config it.


Solution

  • By using a dedicated service message in your build script, you can dynamically update build parameters of the build right from a build step (the parameters need to be defined in the Parameters section of the build configuration).

    Build Script Interaction with TeamCity

    echo ##teamcity[setParameter name='ddd' value='fff']
    

    P.S. echo is mandatory