TeamCity Cloud 2024.12 Help

Configuring Build Parameters

Parameters are name=value pairs that can be referenced throughout TeamCity. There are three major parameter types in TeamCity:

  • Configuration Parameters — parameters whose primary objective is to share settings within a build configuration. You can also use these parameters to customize a configuration that was created from a template or uses a meta-runner. TeamCity does not pass parameters of this type to a build process (that is, these parameters are not accessible by a build script engine).

  • Environment Variables — parameters that start with the env. prefix. These parameters are passed to the process of a build runner similarly to the default env variables of a system.

  • System Properties — parameters that start with the system. prefix. TeamCity can pass parameters of this type to configuration files of certain runners as variables specific to a build tool.

Common Information

Parameters allow you to avoid using plain values in TeamCity UI and build scripts. Instead, you can reference a parameter by its name using the %parameter_name% syntax. In addition, parameters can reference other parameters in their values (for example, system.tomcat.libs=%env.CATALINA_HOME%/lib/*.jar).

Storing values in parameters allows you to:

  • Quickly reuse frequently used values;

  • Create reusable templates and meta-runners whose parameter values are overridden in target configurations;

  • Add flexibility to your build configurations: parameter values can be quickly altered in TeamCity UI, via the service message sent during a build, or in the Run Custom Build dialog;

  • Hide sensitive information that should not be visible to regular TeamCity developers;

  • Improve the readability of your configurations by using shorter parameter references instead of lengthy plain values, and so on.

See the following article for simple use cases where you can store values in parameters: Using Build Parameters.

Main Use Cases

Customize Template-Based Configurations

Configuration parameters allow you to create a base build configuration with parameters, extract it to the template, and override these parameters in configurations based on this template. Using this technique you can quickly duplicate your build configurations that have slight variations depending on your current task.

For example, the following build configuration has two steps and the Boolean skip.optional.step parameter. Step #2 will or will not be executed depending on this parameter value.

import jetbrains.buildServer.configs.kotlin.* import jetbrains.buildServer.configs.kotlin.buildSteps.script object SourceConfig : BuildType({ name = "SourceConfig" params { param("skip.optional.step", "false") } steps { script { name = "Mandatory Step" scriptContent = """echo "Mandatory step #1 is running..."""" } script { name = "Optional Step" scriptContent = """echo "Optional step #2 is running..."""" conditions { equals("skip.optional.step", "false") } } }})

If you extract a template from this configuration, you can create multiple copies of the same configuration. In those copies that do not need to run the optional step #2, override the skip.optional.step parameter and set it to true.

import jetbrains.buildServer.configs.kotlin.* object ConfigFromTemplate : BuildType({ templates(SourceConfigTemplate) name = "Build Config Based on Template" params { param("skip.optional.step", "true") } })

See the following section to learn more about step execution conditions: Specify Step Execution Conditions.

Pass Values to Meta-Runners

A meta-runner allows you to extract build steps, requirements, and parameters from a build configuration and create a custom build runner.

See this article for the example of an Ant-based meta-runner that utilizes the custom system.artifact.paths parameter to publish artifacts via a corresponding service message: Preparing Build Configuration.

Specify Step Execution Conditions

You can define step execution conditions to specify whether individual steps should run. You can craft these conditions using custom and predefined configuration parameters and environment variables.

To set up step execution conditions in TeamCity UI, go to step settings and click Add condition | Other condition...

Step execution condition

For example, you can run different shell scripts depending on the build agent's operating system.

import jetbrains.buildServer.configs.kotlin.* import jetbrains.buildServer.configs.kotlin.buildSteps.powerShell import jetbrains.buildServer.configs.kotlin.buildSteps.script object StepExecutionConditions : BuildType({ params { param("win.destination.path", "C:/Sources") param("unix.destination.path", "/Users/Admin/Sources") } steps { // PowerShell script runs only on Windows agents powerShell { name = "Copy File (Windows)" conditions { startsWith("teamcity.agent.jvm.os.name", "Windows") } scriptMode = script { content = """Copy-Item "%\system.teamcity.build.workingDir%/result.xml" -Destination %\win.destination.path%""" } } // Command Line runner for non-Windows agents script { name = "Copy File (Unix)" executionMode = BuildStep.ExecutionMode.RUN_ON_FAILURE conditions { doesNotContain("teamcity.agent.jvm.os.name", "Windows") } scriptContent = """cp "%\system.teamcity.build.workingDir%/result.xml" %\unix.destination.path%""" } } })

Specify Agent Requirements

Agent Requirements allow you to specify parameter-operator-value conditions. Only those agents that meet these conditions are allowed to build this build configuration.

You can define agent requirements using only those parameters whose values agents can report before the build starts. These parameters are:

  • Predefined configuration parameters available for all agents (for example, teamcity.agent.name).

  • Environment variables reported by agents (for example, env.DOTNET_SDK_VERSION).

  • Custom configuration parameters that are present in agents' buildAgent.properties files (for example, create a custom.agent.parameter in TeamCity UI and add the custom.agent.parameter=MyValue line to agents' properties files).

TeamCity automatically adds agent requirements depending on the configured build steps. For example, if a build step should be executed inside a Linux container, TeamCity adds requirements that specify an agent must have either Docker or Podman running on a Linux machine.

To define custom agent requirements in TeamCity UI, navigate to the Administration | <Build Configuration> | Agent Requirements tab.

Set agent requirements in TeamCity UI

In Kotlin DSL, use the requirements block of your build configuration to define a requirement.

import jetbrains.buildServer.configs.kotlin.* object BuildConfig : BuildType({ name = "Build Config" steps { // Build steps } requirements { // Requirements in the following format: // Operator("ParameterName", "ParameterValue") } })

For example, the following condition allows only Mac agents to run builds for the parent build configuration.

matches("teamcity.agent.jvm.os.family", "Mac OS")

The sample condition below allows builds to run only on machines with "Android" workload installed for .NET 7 SDK:

contains("DotNetWorkloads_7.0", "android")

The following condition requires that an agent running builds has either Docker or Podman:

exists("container.engine")

Pass Values to Simple Script Runners

You can insert references to parameters as %parameter_name% when writing scripts for Command Line, C# Script, and Python runners.

The script below prints the checkout directory path (configuration parameter) and TeamCity server version (environment variable) to the build log.

echo "Checkout directory: %teamcity.build.checkoutDir%" echo "Server version: '$TEAMCITY_VERSION'"

The script below uses a reference to the build branch to obtain a file that should be copied to the target directory.

set -e -x FILE=%\teamcity.build.branch%/fileToCopy.xml if test -f "$FILE"; then cp "$FILE" folderA/folderB fi

This sample script sends the REST API request to download the "libraries.tar.gz" archive from the server (whose URL is stored as the serverURL config parameter), add a build number to its name, and save it to the checkout directory. For example, the name of the archive from build #54 will be "libraries_54.tar.gz".

curl -o libraries_%\build.number%.tar.gz %\serverUrlBase%libraries.tar.gz

The following script prints the checkout directory path (configuration parameter) and TeamCity server version (environment variable) to the build log.

print(f'Current checkout directory is: %teamcity.build.checkoutDir%') print(f'TeamCity version is: %\env.TEAMCITY_VERSION%') # or print(f"TeamCity version is: {os.environ['TEAMCITY_VERSION']}")

The following script obtains the checkout directory path and appends an additional path to it:

string fullPath = Path.Combine("%teamcity.build.checkoutDir%", "myFolder/bin"); Console.WriteLine(fullPath);

To get values of environment variables, use the Environment.GetEnvironmentVariable method:

Console.WriteLine("Predefined variable value = " + System.Environment.GetEnvironmentVariable("TEAMCITY_VERSION")); Console.WriteLine("Custom variable value = " + System.Environment.GetEnvironmentVariable("My.Custom.Env.Variable"));

You can also add parameter references in the %parameter_name% format to the Script parameters field of the runner. These parameters will then be available from the global Args array.

See this blog post for an example of using parameters in C# scripts and .NET runner: How to automate CI/CD tasks with C# Scripting in TeamCity.

Share Values Between Steps

You can use parameters to pass simple data from one step/script to another. To do this, send the setParameter service message from a script that calculates new parameter values.

echo "##teamcity[setParameter name='myParam1' value='TeamCity Agent %\teamcity.agent.name%']"

In the following configuration, a C# script checks the current day of the week and writes it to the day.of.week parameter. A subsequent Python runner then uses the updated parameter value.

object MyBuildConf : BuildType({ params { param("day.of.week", "Monday") } steps { csharpScript { name = "Check the current day" content = """ if ("%\day.of.week%" != DateTime.Today.DayOfWeek.ToString()) { string today = DateTime.Today.DayOfWeek.ToString(); string TCServiceMessage = "##teamcity[setParameter name='day.of.week' value='" + today + "']"; Console.WriteLine(TCServiceMessage); } """.trimIndent() } python { name = "Welcome message" command = script { content = "print('Hello %\teamcity.build.triggeredBy.username%, today is %\day.of.week%!')" } } } })

Pass Values to Builders' Configuration Files

.NET, Maven, Gradle, Ant and NAnt runners allow you to reference TeamCity parameters in build configuration files. This technique allows you to pass the required values to build processes.

In .NET, pass parameter values using the $(<parameter_name>) syntax.

The following sample .csproj file defines two custom MSBuild targets:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <OutputZipFile>project.zip</OutputZipFile> <OutputUnzipDir>unzipped</OutputUnzipDir> </PropertyGroup> <Target Name="Zip"> <ItemGroup> <FilesToZip Include="project.proj*" /> </ItemGroup> <Exec Command="dir" /> <Microsoft.Build.Tasks.Message Text="##teamcity[progressMessage 'Archiving files to $(OutputZipFile) file...']"/> <Exec Command="PowerShell -command Compress-Archive @(FilesToZip, ',') $(OutputZipFile) -Force" /> </Target> <Target Name="Unzip"> <Microsoft.Build.Tasks.Message Text="##teamcity[progressMessage 'Unzipping files to $(OutputUnzipDir) folder...']"/> <Exec Command="PowerShell -command Expand-Archive $(OutputZipFile) -DestinationPath $(OutputUnzipDir) -Force" /> </Target> </Project>

To reference a parameter value in Maven and Ant, use the ${parameterName} syntax.

<!--pom.xml file--> <configuration> <tasks> <property environment="env"/> <echo message="TEMP = ${env.TEMP}"/> <echo message="TMP = ${env.TMP}"/> <echo message="java.io.tmpdir = ${java.io.tmpdir}"/> <echo message="build.number = ${build.number}"/> </tasks> </configuration>

To reference a parameter value in Maven and Ant, use the ${parameterName} syntax.

<target name="buildmain"> <ant dir="${teamcity.build.checkoutDir}" antfile="${teamcity.build.checkoutDir}/build-test.xml" target="masterbuild_main"/> </target>

For Gradle runner, TeamCity system properties can be accessed as native Gradle properties (those defined in the gradle.properties file). If the property name is allowed as a Groovy identifier (does not contain dots), use the following syntax:

println "Custom user property value is ${customUserProperty}"

Otherwise, if the property has dots in its name (for example, build.vcs.number.1), use the project.ext["build.vcs.number.1"] syntax instead.

Share Values Between Chain Builds

TeamCity parameters allow you to exchange values between configurations of a build chain. See this documentation article for more information: Use Parameters in Build Chains.

Last modified: 02 December 2024