Adding trigger to build config in TeamCity via REST API and PowerShell - rest

I'm trying to add a build trigger to a build configuration in an automated fashion through PowerShell and the TeamCity 8 REST API.
Using the following question as a reference, it would appear that what I am trying to do is possible:Adding a Trigger to a build configuration in TeamCity using the REST API
But, whenever I try to add the trigger to the build, using the following code, I get a (405) Method Not Allowed error:
$triggerXML= "<trigger id=`"TriggerID`" type=`"buildDependencyTrigger`">
<properties>
<property name=`"afterSuccessfulBuildOnly`" value=`"true`"/>
<property name=`"dependsOn`" value=`"BuildID`"/>
</properties>
</trigger>"
$webclient.UploadString('http://teamcity:8111/httpAuth/app/rest/buildTypes/BuildID', "POST", $triggerXML)
Has anyone implemented this successfully using PowerShell?

Not that API, but I have scripts that automate TeamCity.
Here is a code snippet I use:
$TeamCityHostAndPort = "myteamcityserver:8111"
# authenticate with NTLM
$LoginUrl = "http://$TeamCityHostAndPort/ntlmLogin.html"
Invoke-WebRequest -Uri $LoginUrl -UseDefaultCredentials -SessionVariable TeamCitySession | Out-Null
#start backup
$StartBackupUrl = "http://$TeamCityHostAndPort/httpAuth/app/rest/server/backup?includeConfigs=true&includeDatabase=true&includeBuildLogs=true&fileName=TeamCity_Backup_"
$filename = Invoke-RestMethod -WebSession $TeamCitySession -Method Post -Uri $StartBackupUrl
notice the first call to authenticate (I disabled built-in users and stick with Windows auth) and the authenticated session passed to subsequent calls.
Invoke-RestMethod is Powershell v4.

Related

How do I log on to JIRA in PowerShell using REST when basic authentication in plain text is blocked?

I've been trying to access our on-prem JIRA Server (configured with plain HTTP) using PowerShell Invoke-RestMethod, but I think I'm missing something.
The authentication header is created in base64
$cred = [convert]:.ToBase64String([text.encoding]::ASCII.GetBytes("account:password"))
$headers = #{Authorization = "Basic $cred"}
Using REST, I then ask for the issue (without posting any property filter to keep the request simple while I'm learning).
Invoke-RestMethod -Uri http://jiraserver:8080/jira-software/REST/agile/1.0/issue/test-1 `
-Headers $headers -ContentType "application/json" -AllowUnencryptedAuthentication
This obviously fails, as I get back a reply containing a login form
<form action="/login.jsp"
class="aui"
id="login-form"
method="post">
I do think I remember that basic authentication is no longer supported in JIRA.
How do I use OAuth in that case instead?
When working with another task that is well within the scope of AtlassianĀ“s PowerShell module JiraPS, I noticed a command called Invoke-JiraMethod.
It turns out that the module provides JIRA REST API access :)
So by setting up a JIRA session with the PowerShell module, I'll be able to use REST over an unencrypted connection.

jenkins powershell plugin url encoding

I am trying to fetch gitlab project info using gitlab api. Below powershell script works perfectly fine in powershell ise
$projects = Invoke-WebRequest https://gitlab.mycompany.com/api/v4/projects/namespace%2fproject
But when using same script in jenkins powershell plugin, i always get error 404 Not found. I dont know if its an issue with url encoding or powershell script encoding.
I have tried below jenkins command with and without encoding
powershell (script:'''
$project = Invoke-WebRequest
https://gitlab.mycompany.com/api/v4/projects/namespace%2fproject
echo $project
''', encoding: 'UTF-8', returnStdout: true)
Any help will be appreciated
That's probably because your project is not public or requires authentication. Go to your account setting and then Access Token. Generate a new token, and then add it to your request header:
$gitUrl = "https://gitlab.mycompany.com/api/v4/projects/namespace%2fproject"
$head = #{'PRIVATE-TOKEN'= 'YourTokenHere'; 'Content-Type'='application/json'}
Invoke-WebRequest -Uri $gitUrl -headers $head
Also check Invoke-RestMethod, it will parse the response into psobject (very handy sometimes)

Getting a file from BitBucket Rest API v2.0

I have a script which grabs a file from GIT using the bitbucket REST API (1.0) however it has recently stopped working. I'm theorizing this may be due to the v1 REST API being depreciated but I'm not sure.
Anyway I am trying to retrieve the file using the new 2.0 REST API but I can't seem to get the syntax right as the request continually fails.
I'm starting out with curl since its easiest to test. This is what I'm trying:
curl -u myusername#mydomain.com "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/Scripts/Environment Setup/test.txt"
Enter host password for user 'myusername#mydomain.com': redacted
{"type": "error", "error": {"message": "Resource not found", "detail": "There is no API hosted at this URL.\n\nFor information about our API's, please refer to the documentation at: https://developer.atlassian.com/bitbucket/api/2/reference/"}}
Here is the reference documentation I am using: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/downloads/%7Bfilename%7D
Maybe I am using the wrong function? I'm not sure.
For posterities sake, you don't want to use the following to download an individual file from bitbucket:
https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/path/to/your/file.txt
("Downloads" is to download entire repo files like a .zip file)
Instead you want to do:
curl --user myuser#mydomain.com:password "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/src/master/path/to/file.txt"
If you're trying to use Invoke-RestRequest (in powershell) note there are some extra steps. With the old 1.0 API you could do:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/1.0/repositories/MyCompany/$($filepath)"
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Credential $cred -Uri $uri -Proxy $proxyUri -OutFile $destination
With the new 2.0 API that no longer works. Powershell's Invoke-RestMethod waits for a 401 response before sending the credentials, and the new 2.0 bitbucket api never provides one, so credentials never get sent causing a 403 forbidden.
To work around that you have to use the following ugly hack to force Invoke-RestMethod to send the credentials immediately in an Authorization header:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/2.0/repositories/MyCompany/$($filepath)"
$username = ($cred.GetNetworkCredential()).username
$password = ($cred.GetNetworkCredential()).password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Uri $uri -Proxy $proxyUri -OutFile $destination
Hopefully that helps someone else out in the future!
Thanks #Jim Redmond for the help.
You can also use the PowerShell module BitbucketServerAutomation. There's not a ton of cmdlets, they do have Get-BBServerFile and Get-BBServerFileContent. I have found it is well written, very usable and being updated regularly. The Invoke-BBServerRestMethod cmdlet is available if you need a command it doesn't have.

403 Error using PowerShell 5 as Kentico 8.2 REST client

This REST request works when I load it directly in a browser in which I'm simultaneously logged into the Kentico 8.2 admin site:
https://www.example.com/rest/CMS.SettingsKey
Now, I need to return the same results using PowerShell 5. I tried various versions of the following:
$url = "https://www.example.com/rest/CMS.SettingsKey"
$httpMethod = "Get"
$credentialsBytes = [System.Text.Encoding]::UTF8.GetBytes("username:password")
$credentialsEncoded = [System.Convert]::ToBase64String($credentialsBytes)
$headers = #{}
$headers.Add("Authorization", "Basic $($credentialsEncoded)")
$settings = (Invoke-RestMethod -Uri $url -Method $httpMethod -headers $headers)
Write-Host $settings
Note that "username" and "password" are the same credentials used to log into the admin site (when the REST request is working in the browser), and the user is a global admin.
The PS snippet gives me a 403 Forbidden error. I followed this page and this page, but I can't get it to work. What am I doing wrong?
EDIT:
I enabled the REST service, but now I'm getting a 401 Unauthorized error. Again, the user is a global admin. I get the feeling the headers aren't being included in the request (or that there is a problem with the headers), because the same request works (from PowerShell) if I generate a hash and use hash parameter authentication instead of basic authentication. I tried using Fiddler a bit as suggested in comments, but I'm new to it, and I don't have time to dive in too deep right now.
Just tested it using the latest hotfix versions (9.0.32 & 8.2.48) and it works just fine.
Make sure REST is enabled for the specific site (not only the global setting)
Make sure you have <modules runAllManagedModulesForAllRequests="true"> in your web.config as described here.

Send login username with REST API + Powershell

I've got the following Powershell script:
$url = "http://somerandomapikeyhere#prestashop.dev/my-store/api"
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
echo $response
which attempts to access my Prestashop API REST service.
I can access the URL from Chrome without a problem, but in PowerShell I get a 401 Unauthorized response, which is understandeable as the somerandomapikeyhere bit in the URL needs to get dealt with differently in PowerShell.
The question is, how? Any ideas / advice?
It's not powershel, but the .net class that is not able to take an url in that format. You need to provide the credentials seperate. See here or here.
But if you have powershell v3 you are better off using the build in commands for web requests or even REST requests.
Invoke-restmethod -uri 'prestashop.dev/my-store/api' -credential 'someapikey'