powershellauthenticationpostteamcityteamcity-8.0

TeamCity REST Api returns 403 using system credentials


When I run a build on TeamCity, I want to tag the build with an environment variable. I hoped this might be straightforward but it seems there is no built-in way to do it. I found a link which uses the TeamCity REST Api to add the tag, but it uses curl and my build server is Windows. So, I figured PowerShell can probably do it.

Using Invoke-WebRequest I've come up with the following script, where TeamCity build parameters are substituted automatically:

$username = "%system.teamcity.auth.userId%"
$password = "%system.teamcity.auth.password%" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)

Invoke-WebRequest `
   -Uri "%teamcity.serverUrl%/httpAuth/app/rest/builds/%teamcity.build.id%/tags" `
   -Credential $cred `
   -Method POST `
   -ContentType "application/xml" `
   -Body '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><tags><tag>%env.Environment%</tag></tags>' `
   -UseBasicParsing

The TeamCity documentation states that the system properties can be used as credentials:

If you perform a request from within a TeamCity build, consider using teamcity.auth.userId/teamcity.auth.password system properties as credentials (within TeamCity settings you can reference them like %system.teamcity.auth.userId% and %system.teamcity.auth.password%)

However, when I run the above as a Powershell script build step, I receive a 403 forbidden:

> [16:48:35][Step 1/1] Invoke-WebRequest : The remote server returned an
> error: (403) Forbidden. [16:48:35][Step 1/1] At line:1 char:1
> [16:48:35][Step 1/1] + Invoke-WebRequest ` [16:48:35][Step 1/1] +
> ~~~~~~~~~~~~~~~~~~~ [16:48:35][Step 1/1]     + CategoryInfo          :
> InvalidOperation: (System.Net.HttpWebRequest:Htt  [16:48:35][Step 1/1]
> pWebRequest) [Invoke-WebRequest], WebException [16:48:35][Step 1/1]   
> + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe  [16:48:35][Step 1/1]
> ll.Commands.InvokeWebRequestCommand [16:48:35][Step 1/1]  
> [16:48:35][Step 1/1] Process exited with code 1 [16:48:35][Step 1/1]
> Step Powershell failed

Do I need to enable something in TeamCity to allow this user to post to the URL?


Solution

  • %system.teamcity.auth.userId% + %system.teamcity.auth.password% currently does not work: https://youtrack.jetbrains.com/issue/TW-39206

    Specify credentials explicitly. If you want to hide the password, you can create a Configuration Parameter with spec password display='hidden'. In this case the parameter's value will not be available for read, only for write. The parameter will also be masked in logs.