Get Azure DevOps service connection service principal id with powershell - azure

I am working on automating Azure Active Directory App Registrations and Azure Devops Service Connections, and have hit a wall.
I want to query Azure DevOps service connections (service endpoints) by Service Principal ID (or at least get the id). This is possible when using Azure CLI:
az devops service-endpoint list --query "[?authorization.parameters.serviceprincipalid=='xxx']"
But since I am running this in Azure automation account as a powershell runbook, the Azure CLI is not supported.
Then I tried the Azure DevOps REST API, and called it from powershell, but the response does not contain the service principal ID, but just this:
authorization : #{parameters=; scheme=ServicePrincipal}
Does anyone have an idea on how to solve this?
UPDATE
I am calling the rest API like this:
$uriAccount = $UriOrg + "_apis/serviceendpoint/endpoints?endpointNames={name}&api-version=6.1-preview.4"
$result = Invoke-RestMethod -Uri $uriAccount -Method get -Headers $AzureDevOpsAuthenicationHeader
And $result.value gives me this:
authorization : #{parameters=; scheme=ServicePrincipal}

You can try the REST API Endpoints - Get Service Endpoints By Names.
GET https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4
In this REST API, you can find the id and details by the name of a service connection.
Here is an example to use the REST API in PowerShell:
$token = "{pat}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4"
$head = #{ Authorization =" Basic $token" }
Invoke-RestMethod -Uri $url -Method GET -Headers $head
Update:
The cause for this question is that you output result in the wrong way.
For JSON response bodies, there is no intuitive way to get results without specifying the final layer.
Here is my modified code, notice how I print result:
$token = "{pat}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4"
$head = #{ Authorization =" Basic $token" }
$reslut = Invoke-RestMethod -Uri $url -Method GET -Headers $head
echo $result.value.authorization.parameters

Related

With Graph API call, one az ad app works and another app throughs Forbidden 403 error

Two apps registered in two different tenants with identical Microsoft graph permission.
All I am trying to use Powershell Invoke-RestMethod with Micorsoft Graph API. Same code, works for one but not the other one.
Any Idea why?
Not sure what to try. Access token gets created. App authentication message also prints on the screen (both cases)
Click here for the picture of the full permission
I tried to reproduce the same in my environment and got the same error as below.
To resolve this issue, check whether you have granted admin consent like below.
After adding admin consent, use the below code to get token.
$tenantId = <tenantID>
$applicationId = <appID>
$secret= <secret>
$param = #{
Uri = "https://login.microsoftonline.com/$tenantId/oauth2/token?
api-version=2020-06-01";
Method = 'Post';
Body = #{
grant_type = 'client_credentials';
resource =
'https://graph.microsoft.com';
client_id = $applicationId;
client_secret = $secret
}
}
$result = Invoke-RestMethod #param
$token = $result.access_token
You can change the Uri based on your requirement and run the below commands.
$authHeader= #{Authorization=("Bearer {0}" -f $token)}
Invoke-RestMethod -Uri https://graph.microsoft.com/v1.0/users -Method GET -Headers $authHeader
Result:

Azure REST API: Stop a classic service

I'm trying to invoke Azure REST API from Powershell to start/stop a classic service.
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $($token.Token)")
$headers.Add("Content-Type", "application/json")
$response = Invoke-RestMethod "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$rscGrp/providers/Microsoft.ClassicCompute/domainNames/$serviceName/slots/production/$action?api-version=2020-02-01" -Method 'POST' -Headers $headers
$response | ConvertTo-Json
When $action="start", the command works perfectly and the service starts all instances as required.
However, when $action="stop", the command deletes the whole service all together. The whole deployment slot is deleted instead of simply stopping the instances.
Basically, I want it to behave exactly like clicking on the "stop" button in Azure Portal.
You can use this Rest API, to Power off the cloud service. Note that resources are still attached and you are getting charged for the resources
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/poweroff?api-version=2021-03-01

Azure devops automate target vm deletion from deployment group

There is a method available for deleting a target machine from an azure deployment group using the API and its documentation can be seen here.
Is there a similar functionality available as a powershell script?
There isn't a PowerShell module available for Azure DevOps. However, you can invoke the same Azure DevOps REST APIs through the Invoke-RestMethod cmdlet.
Here is how:
$Username =""
$Password="<Personal-Access-Token>"
$Tokens = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $Username,$Password)))
$Authheader = #{Authorization = 'Basic ' + $Tokens }
# Targets - Delete REST API
$Uri = "https://dev.azure.com/{organization}/{project}/_apis/distributedtask/deploymentgroups/{deploymentGroupId}/targets/{targetId}?api-version=6.0-preview.1"
Invoke-RestMethod -Uri $Uri -Method delete -Headers $Authheader

Get Azure Security Center tasks via API

im trying to write a backend program that will get all of Azure Security Center tasks (Recommendation) with no browser authorization involved.
As far as i saw, Graph API does not have an end point for Security tasks and the only endpoint i could find is https://learn.microsoft.com/en-us/rest/api/securitycenter/tasks/list which supports only Implicit flow authorization.
Is there a way to get authorization without using consent window in the browser, or to get the tasks via different endpoint?
You can use the below Powershell script which is using the REST API to get all the tasks:
$subscriptionId = "yoursubid"
$context = Get-AzContext
$profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($profile)
$token = $profileClient.AcquireAccessToken($context.Subscription.TenantId)
$authHeader = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer ' + $token.AccessToken
}
$uri = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Security/tasks?api-version=2015-06-01-preview"
$response = Invoke-RestMethod -Uri $uri `
-Method Get `
-Headers $authHeader
$response.value | ConvertTo-Json
OR
You can directly use Azure CLI to get directly .
Command:
az security task list
Reference:
az security task | Microsoft Docs
Install the Azure Az PowerShell module with PowerShellGet | Microsoft Docs
Output for the above powershell script:
For those who will need this in the future,
it is possible.
It didnt work for me because i requested the bearer token from the wrong address, use the following url for the bearer token request:
https://login.microsoftonline.com/{tenantId}/oauth2/token
And NOT:
https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
(This is the azure AD typical bearer token request url)
If you would rather not mess around with getting the bearer token (and you want to go the powershell route) you can also use Invoke-AzRestMethod
# Capture everything MDC can do from a REST API
$Capabilities = (Invoke-AzRestMethod -ApiVersion "2022-09-01" -ResourceProviderName 'Microsoft.Security').Content | ConvertFrom-Json
$Capabilities.resourceTypes

How to get the access token to start or shut down VMs on azure classic portal?

How to get the access token to start or shut down VMs on azure classic portal, I have tried multiple links for the same such as https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-api-authentication, also whatever access token I m getting using that I can only start, shutdown ARM vms, not classic VMs. Can somebody please help me on this ?
I'm very lazy, so I'm using arm token to startup\shutdown classic vms :). sample code:
$header = #{ Authorization = "Bearer $token" }
$uri = "https://management.azure.com{0}/{1}?api-version={2}" -f $vmId, $action, $apiVer
Invoke-WebRequest -Headers $header -Method Post -Uri $uri -UseBasicParsing
to start use $action = 'start'
to shutdown use $action = 'shutdown'
for apiVersion use $apiVer = '2017-04-01'
for ID, just use classic VM resource id, example:
/subscriptions/GUID/resourceGroups/rgName/providers/Microsoft.ClassicCompute/virtualMachines/vmName
you would need to grant yourself (or the entity you are getting script on behalf of) proper rights. I'm using these:
"Microsoft.ClassicCompute/virtualMachines/read"
"Microsoft.ClassicCompute/virtualMachines/start/action"
"Microsoft.ClassicCompute/virtualMachines/shutdown/action"
"Microsoft.ClassicCompute/virtualMachines/operationStatuses/read"

Resources