Setting Up TeamCity for Amazon EC2
TeamCity Amazon EC2 integration allows TeamCity auto-scale its building resources by automatically starting and stopping cloud-hosted agents on-demand, depending on the current build queue workload.
You can set up various types of EC2 integrations in TeamCity. Depending on the settings and the source you use, cloud AWS-hosted agents can run on:
Multiple identical instances cloned from the same Amazon Machine Image (AMI). Can be launched as On-Demand or spot instances.
A single permanent EC2 instance managed by TeamCity. Can be shared between multiple TeamCity servers.
A set of spot instances requested from AWS (Spot Fleet).
This section describes the steps that you must perform in your AWS account before setting up a cloud profile in TeamCity UI.
Create and Setup an EC2 Instance
Open the Amazon EC2 console.
Install an agent on your instance. Depending on the OS type, the required steps may vary. See these articles for more information:
Install any additional software required to run build steps and the TeamCity agent itself: JDKs and JREs, SDKs, runtime frameworks, building tools such as Git and Docker, and so on.
Run the agent and ensure it successfully connects to your TeamCity server and is compatible with all required configurations.
Configure the system to automatically run a TeamCity agent when an instance starts.
For Windows instances, follow these steps: Additional configuration for Windows agents.
Restart your instance to ensure the build agent starts automatically and can connect to the server.
Create an AMI
Skip this section if you want the instance created in the previous step to directly connect to a TeamCity server and serve as a stand-alone agent machine. Otherwise, if you want TeamCity to automatically scale the number of active cloud agents based on the current workload, create an AMI from this instance.
Stop the build agent. For Windows instances, stop the agent service but leave its startup type Automatic.
Remove all temporary and excess data from your instance: installation wizards, downloaded archives, build logs, and so on.
Optional: Delete the
Optional: Delete the
Remove the following properties from the
name— TeamCity will automatically assign unique names to your instances.
serverUrl— for the EC2 integration plugin, this property is safe to remove since you will provide a server URL for all instances when setting up a cloud profile. Other plugins may require this property to be present and set to a correct value.
authorizationToken— new cloud agents are authorized automatically.
Stop the instance.
On the overview page of your instance, click Actions | Image and Templates | Create Image.
Setup EC2 Integration in TeamCity
After you have created a required instance or AMI, you can set up cloud profiles in TeamCity UI.
Create a Cloud Profile
A cloud profile is a collection of general settings for TeamCity to start virtual machines.
Navigate to Administration | <Required Project> | Cloud Profiles. If you want cloud agents in this profile to be available globally, choose the <Root project>. Profiles owned by individual projects can be used to spawn agents that can be used only in these projects.
Click Create new profile.
Set Cloud type to "Amazon EC2".
Enter your profile name and optional description.
Choose between authentication via access key/secret pair or credentials stored locally on the server machine. Regardless of the selected mode, a user or IAM role used by TeamCity to access AWS resources must have all permissions listed in this section: Required IAM Permissions.
This option lets you specify credentials that TeamCity will use to access your AWS resources. Using static credentials is the least secure approach, we recommend the Use default credential provider chain option instead.
5.1. Go to the AWS Identity and Access Management (IAM) dashboard.
5.2. Switch to the Users tab and find a user whose credentials can be used by TeamCity to access your EC2 instances and AMIs.
5.3. Switch to the Security Credentials tab and scroll to the Access keys section.
5.4. Create a new key. Paste its ID and secret to the related fields in TeamCity UI.
The Use default credential provider chain option allows TeamCity to look for AWS credentials stored on the server machine. Typically, the
configfile with your AWS credentials is located at
~/.aws/configon Linux or macOS, or at
C:\Users\USERNAME\.aws\configon Windows. This approach is more stable and secure compared to using static access keys.
See the following article for more information about locally stored AWS credentials: Configuration and credential file settings.
Choose an AWS region in which your instances are hosted.
Set up the agent limit. This number specifies the overall limit for agents created from all cloud images of this profile.
Specify the TeamCity server URL. This value will be automatically passed to agents'
buildAgent.propertiesfiles. If not specified, agents will use the same value as on the Administration | Global Settings page.
Specify the set of criteria for winding down active cloud agents. You can choose how long agents can remain idle and (or) how long they can perform actual building routines.
Click Apply changes to save the profile and exit the profile settings page.
Add a Cloud Image
Cloud profiles specify global settings, such as authorization credentials and instance regions. Each profile can have one or multiple images that store settings related to the specific type of cloud instance that should be started. You can add as many images to a profile as your needs dictate. However, note that the total number of agents started by all images cannot exceed the limit set in the profile settings (and the number of agents permitted by your license).
Click the Add image button.
Specify the image name. All images in a cloud profile must have unique names.
Choose the required image type.
Choose an AMI that TeamCity will use to spawn identical instances.
3.1. Check the Use launch template option if you want TeamCity to import and use a specific launch template. When the default/latest version of the template updates on the server, TeamCity detects these changes and updates the running instances.
3.2. Choose a required AMI.
Own AMI — TeamCity scans a collection of AMIs available under credentials specified in the cloud profile settings. You can browse all found AMIs and choose a required image.
AMI by ID — Allows you to utilize a shared AMI.
AMI by tags — Specify a comma-separated list of AWS tags, for example,
Owner=Mike,Project=Glacier,Subnet=Public. If the specified tags point to multiple AMIs, TeamCity will use the most recently created AMI. If no AMIs were found, the image name under the Agents section will be "Image name (no data)" instead of "Image name (ami-xxxxxxxxx)".
3.3. Specify one or multiple instance types.
Specify one type (for example,
t2.medium) if you need to launch On-Demand or spot instances of this specific type only. You can add multiple images that target the same AMI with different instance type values. By doing so you can set different active instance limits for each type, and manually start instances of a specific type.
Set multiple types (for instance,
t2.large) if you plan to order spot instances. This approach increases your chances of having a spot instance assigned.
3.4. Optional: Specify additional image settings.
IAM Role — The IAM role that all launched instances will assume. This role specifies the permissions granted to applications running on your EC2 instances. The AWS account used by TeamCity must have
iam:PassRolepermissions to utilize IAM roles.
Key pair — Required if you may need to connect to your EC2 instances using SSH.
Tags — The list of comma-separated instance tags. For example
LaunchedBy=TeamCity,TeamCityCloudProfileName=MyProfile1. Tagging requires the
ec2:*Tagspermission. See the following section for more information: Tagging.
3.5. Check Use spot instances if you prefer cheaper spot instances to On-Demand ones. The Max price field lets you to specify your maximum bid price for spot instances (in US dollars). The default On-Demand price will be used if the bid price is not specified.
TeamCity can automatically choose Regions or Availability Zones in which your spot requests are most likely to succeed based on their spot placement scores. To allow TeamCity to request and utilize these scores, add the
3.6. Specify networking settings for your EC2 instances.
This option allows you to add the specific instance to TeamCity. Compared to AMIs that allow TeamCity to start multiple identical instances, this type implies you have a static virtual machine that TeamCity can start and stop.
3.1. Specify the desired instance type. Since there can be only one active instance, you can select only one type.
3.2. Choose a Key pair if you may need to connect to your EC2 instance using SSH.
Amazon Spot Fleet allows you to book a combination of regular (On-Demand) and spot instances based on the given criteria. See the following AWS documentation article for sample requests: Spot Fleet example configurations.
3.1. In AWS Management Console, Go to Instances | Spot Requests | Request Spot Instances.
3.2. Specify the required AMI, minimum compute unit, availability zones, and other request details.
3.3. Click JSON config to download a JSON file with the spot fleet configuration parameters. Note that only fields from the
SpotFleetRequestConfigDataclass are supported.
3.4. Paste the generated JSON configuration file in the Spot Fleet Request field in TeamCity.
To run the image, TeamCity will launch spot instances matching the allocation strategy specified in the spot fleet configuration.
Set up the maximum number of active cloud agents starting from this image. Note that the total number of agents started from all images added to a profile cannot exceed the limit set on the settings page of this profile.
Specify the agent pool to which newly created instances will belong.
Click Save to exit the image settings page.
After you have configured an image, TeamCity winds up one test agent for this image to test whether it can start and connect to the server. When an agent is connected and authorized, TeamCity saves its parameters to correctly assign builds to compatible agents.
If your image has the Use spot instances setting checked and a test instance cannot be launched at the moment (for example, if there is no available capacity or your bid price is too low), TeamCity will repeat attempts to launch a spot instance once a minute, as long as there are queued builds which can run on this agent.
Manage Cloud Agents
When a build is queued, TeamCity attempts to run queued builds on regular (non-cloud) agents first. If none are currently available, TeamCity finds a compatible cloud image and (if the limit of simultaneously running instances is not yet reached) starts a new instance.
You can manually start and stop cloud agents from the Agents tab. Note that the Start button is disabled if the number of active cloud agents reaches the limit specified in the profile or image settings.
The Running instances block shows all agents started from this specific image.
Instances that successfully started but have not yet connected to the TeamCity server have AWS instance IDs as names ("i-xxxxxxxxxxxx").
Connected and authorized instances have names merged from a parent image name and an AWS instance ID ("Ubuntu-22.04-Large-i-xxxxxxxxxxxx").
If a connected agent reports outdated build tools, it will automatically disconnect for an upgrade. Once all required software is updated, the agent will reconnect to the server. TeamCity shows a corresponding warning for outdated agent images.
You can open an interactive terminal to any active agent instance via the Open Terminal button. The terminal allows you to debug and maintain your cloud agent machines.
The following Kotlin snippet illustrates a sample DSL configuration for a cloud profile that uses locally stored credentials and includes three images with different settings.
Required IAM permissions
TeamCity requires the following permissions for Amazon EC2 Resources:
To use spot instances, grant the following permissions in addition to those listed above:
ec2:GetSpotPlacementScores(optional, allows TeamCity to choose AWS Regions or Availability Zones based on their spot placement scores).
To use Spot Fleets, the following additional permissions are required:
iam:CreateServiceLinkedRole(if you are getting "The provided credentials do not have permission to create the service-linked role for EC2 Spot Fleet" error; you can safely revoke this permission once the service role is created)
To launch an instance under an assumed IAM Role (applicable to instances cloned from AMIs and launch templates), the following additional permissions are required:
To use encrypted EBS volumes, the following additional permissions are required:
The snippet below illustrates a custom IAM policy definition that allows all EC2 operations initiated by TeamCity from the specific IP address:
Additional Configuration for Windows Agents
To ensure proper TeamCity agent communication with EC2 API (including access to additional drives) on Windows, add a dependency from the TeamCity Build Agent service on the AmazonSSMAgent or EC2Launch/EC2Config service (the service which ensures the machine is fully initialized in regard to AWS infrastructure use). This can be done, for example, via the Registry or using sc config (for instance,
sc config TCBuildAgent depend=EC2Config).
Alternatively, you can use the "Automatic (delayed start)" service starting mode.
Amazon EBS-Optimized Instances
The behavior of EBS optimization in TeamCity is similar to that offered by EC2 console. When configuring an image of the Amazon cloud profile, the optimization can be set using the corresponding box of the Instance Type. Note that:
EBS optimization is turned on by default for
EBS optimization is turned off by default for any other instance types and can be turned on for instances that support it (such as
Tagging Instances Launched by TeamCity
The following requirements must be met for tagging instances launched by TeamCity:
You have all
The maximum number of tags (50) for your Amazon EC2 resource is not reached.
Without tagging permissions, TeamCity can still launch Amazon AMI and EBS images with no tags applied but is unable to launch Amazon EC2 spot instances
TeamCity enables users to get instance launch information by marking the created instances with the
teamcity:TeamcityData tag containing
<server UUID>:-<cloud profile ID>:-<image reference>. This tag is necessary for TeamCity integration with EC2 and must not be deleted.
Custom tags can be applied to EC2 cloud agent instances: when configuring Cloud profile settings, in the Add Image/Edit Image dialog use the Instance tags: field to specify tags in the format of
<key1>=<value1>,<key2>=<value2>. Amazon tag restrictions need to be considered.
When using the equal(=) sign in the tag value, no escaping is needed. For instance, the string
extraParam=name=John will be parsed into
<key=extraParam> and value
Tagging Instance-Dependent Resources
When launching Amazon EC2 instances, TeamCity tags all the resources (for example, volumes and network adapters) associated with the created instances, which is important when evaluating the overall cost of an instance (taking into account the storage drive type and size, I/O operations (for standard drives), network (transfers out), and so on.
Sharing an EBS Instance Between Multiple TeamCity Servers
As mentioned above, TeamCity tags every instance it launches with the
teamcity:TeamcityData tag that stores information about a server, cloud profile, and source (AMI or EBS-instance). So, when several TeamCity servers try to use the same EBS instance, the second one will see the following message "Instance is used by another TeamCity server. Unable to start/stop it". If you are sure that no other TeamCity servers are working with this instance, you can delete the
teamcity:TeamcityData tag and the instance will become available for all TeamCity servers again.
Estimating EC2 Costs
Standard Amazon EC2 pricing applies. Amazon charges can depend on the specific configuration implemented to deploy TeamCity. We advise you to regularly check your configuration and Amazon account data to discover and prevent unexpected expenses as soon as possible.
Here are some points to help you estimate TeamCity-related traffic:
If TeamCity server is not located within the same EC2 region or availability zone that is configured in TeamCity EC2 settings for agents, traffic between the server and agent is subject to usual Amazon EC2 external traffic charges.
When estimating traffic, bear in mind that there are lots types of traffic related to TeamCity (see a non-complete list below).
External connections originated by a server:
Internal connections originated by a server:
TeamCity agents (checking status, sending commands, retrieving information like thread dumps, and so on)
External connections originated by a agent:
VCS servers (in case of agent-side checkout)
Any connections performed from the build process itself
Internal connections originated by an agent:
TeamCity server (retrieving build sources in case of server-side checkout or personal builds, downloading artifacts, and so on)
Usual connections served by a server:
As Amazon rounds machine uptime to the full hour for some configurations (more at How are Amazon EC2 instance hours billed?), adjust timeout setting on the EC2 image setting on TeamCity cloud integration settings according to your usual builds length.
It is also highly recommended to set execution timeout for all your builds so that a build hanging does not cause prolonged instance running with no payload.