Laurent Michel
Laurent Michel

Reputation: 1331

How do I programmatically stop a teamcity build agent instance after current build?

On Teamcity, when I click an agent, I get the "Agent Summary", "Build History", "Compatible Configurations", etc. etc. I can also see the running build and the "Miscellaneous" section, like this one:

enter image description here

I would like to know how I can run the "Stop instance after current build" with the Teamcity API. Does that correspond to deleting the agent or is there something else?

Upvotes: 0

Views: 577

Answers (2)

Laurent Michel
Laurent Michel

Reputation: 1331

The best way I was advised to follow in order to solve my issue is to define a cloud profile which terminates agents after the first build. To achieve that, in my teamcity project, I have defined (in kotlin DSL):

project {
  [...]

  features { 
    feature(ProjectFeature({
      type = "CloudProfile"
      id = "stop_instance_after_current_build"
      // various cloud profile parameters, like
      // profileServerUrl, secure:access-id, total-work-time, etc.
      // which you find by GETting <teamcity-url>/app/rest/projects/id:<project-id>/projectFeatures/
      [...]
      // there should be no terminate-idle-time parameter
      param("terminate-after-build", true.toString())
    })
  }
}

With that in place, in a build configuration associated to that project, I do

class SomeBuildConfig() : BuildType({
  [...]

  requirements {
    equals("system.cloud.profile_id", "stop_instance_after_current_build")
  }
})

If we don't want to rely on %system.cloud.profile_id%, it is also possible to define a dedicated variable in the agent through the user-script parameter of a ProjectFeature of CloudImage type:

project {
  [...]

  features { 
    feature(ProjectFeature({
      type = "CloudProfile"
      id = "stop_instance_after_current_build"
      // as above
      [...]
    })

    feature(ProjectFeature({
      type = "CloudImage"
      // various parameters like e.g. image-name-prefix, key-pair-name, subnet-id, amazon-id, etc.
      [...]
      param("profileId", "stop_instance_after_current_build")
      param("user-script", userData)
    })
  }
}

where userData is the content of a script like this:

#! /bin/sh
echo "teamcity.agent.killed_after_current_build=true" >> /home/ubuntu/buildAgent/conf/buildAgent.properties

Then, in a build configuration associated to that project, we can do

requirements {
  equals("teamcity.agent.killed_after_current_build", "true")
}

Upvotes: 0

user3074969
user3074969

Reputation: 11

If you want to do it from the build itself, then you can emulate the HTTP request that UI sends when a user clicks the "Stop instance after current build" button

Upvotes: 1

Related Questions