пятница, 11 ноября 2016 г.

Enable (Disable) TeamCity agents in specified pool


Python script that make Enabled or Disabled all agents in specified TeamCity pool

#!/usr/bin/python
# coding: UTF-8
#
# script running from console with 2 arguments
# 1st is pool name and 2nd is disable/enable (which what you want to do with agents enable or disable)
#
# Example: python ed_agents.py "Test Pool" disable
#

import sys
import xml.etree.ElementTree as ET
import requests

#Username for TeamCity
username = 'guest'
#password for TeamCity
passwd = username
#url of TeamCity
url = 'http://teamcity.corp'
poolnId = ''

#Function to do agents Disabled or Enabled
def agentAction(action):

        r = requests.get(listPoolAgents, auth=(username, passwd))
        content = r.content
        tree = ET.fromstring(content)

        if action == "disable":
                for place in tree.findall('agent'):
                        #taking link to agent
                        agentHref = place.get('href')
                        #taking name of agent
                        agentName = place.get('name')
                        agentDisable = url + agentHref + '/enabled'
                        #put request to TeamCity API
                        r = requests.put(agentDisable, data='false', auth=(username, passwd))
                        print "Agent " + agentName + " is disabled"
        if action == "enable":
                for place in tree.findall('agent'):
                        agentHref = place.get('href')
                        agentName = place.get('name')
                        agentEnable = url + agentHref + '/enabled'
                        r = requests.put(agentEnable, data='true', auth=(username, passwd))
                        print "Agent " + agentName + " is enabled"

#get list of all agents using TeamCity API
r = requests.get('http://teamcity.corp/httpAuth/app/rest/agentPools', auth=(username, passwd))
content = r.content
tree = ET.fromstring(content)

#taking id of pool what you need
for place in tree.findall('agentPool'):
        poolName = place.get('name')
        poolId = place.get('id')

        if (poolName == sys.argv[1]):
                poolnId = poolId

#creating url for pool's agents
listPoolAgents = 'http://teamcity.corp/app/rest/agentPools/id:' + poolnId + '/agents'

agentAction(sys.argv[2])