I have an automation account in Azure and I have a runbook in it. What I'm trying to do is to make an API call from this runbook. I'll need to login to some web service, get a session token and then use this session token to call some controller's methods.
So far I have only found some ways to call Azure runbooks through API (let's say from some backend c# code), but not vica versa. What I need to do is to call some c# methods FROM Azure runbook.
Is there a way to do it? If there is, how do I pass queries within my call?
What I'm expecting to see is something like:
$response = MakeApiCall -Url "www.someurl.com" -Body "some json for example"
Yes you can.
It's either
$Url = "https://my-url"
$Body = #{
field = "value"
}
Invoke-RestMethod -Method POST -Uri $url -Body $body -UseBasicParsing
or
Invoke-WebRequest
Invoke-RestMethod by default parses output, Invoke-WebRequest donesn't.
Related
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
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
I have created a simple Logic app with HHT trigger response to take a test in JSON object and then pass it in teams channel. I have tested it successfully in Postman where I set Authorization type as "No Auth". When I am trying to call the same using powershell I am getting error
{"error":{"code":"DirectApiRequestHasMoreThanOneAuthorization","message":"The request has both SAS authentication scheme and 'None' authorization
scheme. Only one scheme should be used."}}
Below is the PowerShell code I am using . Please suggest what should I change in it.
$body ="{
`"testName`": `"NewTest`"
}"| ConvertTo-Json
$body = $body | ConvertFrom-Json
$supportAreaUri = 'https://<URL>'
$supportAreaUri = [uri]::EscapeUriString($supportAreaUri)
$Header = #{Authorization="None"}
Invoke-RestMethod -Method Post -Uri $supportAreaUri -ContentType application/json -Body $body -Headers $Header
Here is the screenshot of logic app
When you created the logic app with "When a HTTP request is received" trigger, it will generate a url for request like https://prod-04.eastasia.logic.azure.com:443/workflows/830xxxxxxxxa5ebb/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=l5xxxxxxxxxxzMRM. The url is protected with SAS token, the SAS token follows the base url in querystring. When you request in postman, it will fill the querystring in "Params" like below screenshot:
But when you request the url in powershell, you specify the header with Authorization="None", the request method will assume that you don't use any authentication and it is conflict with SAS token. So it shows the error message The request has both SAS authentication scheme and 'None' authorization scheme which you provided.
To solve this problem, you just need to request the url without -Header.
Invoke-RestMethod -Method Post -Uri $supportAreaUri -ContentType application/json -Body $body
By the way: When you request the url without -Header, it may show this error message You do not have permissions to perform action 'run' on scope '/triggers/manual/paths/'. It was caused by the line $supportAreaUri = [uri]::EscapeUriString($supportAreaUri) . Actually, you do not need to do escapeUriString, so just remove this line and request again.
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
I know it's possible to get all packages contained in a single Artifact Feed using the link below:
https://feeds.dev.azure.com/{organization}/{project}/_apis/packaging/Feeds/{feedId}/packages?api-version=6.0-preview.1
I noticed in Azure DevOps that the search bar has the ability to look into ALL feeds inside a project. Thus, my question is: Is it possible to achieve the same functionality through the API, and get all packages from all feeds instead of one.
Is it possible to achieve the same functionality through the API, and get all packages from all feeds instead of one.
As far as I know, this is achievable.
You could use the Rest API -Feed Management - Get Feeds to get All feeds in Project level.
Then you could use the Rest API to get the packages. You can execute these two apis simultaneously through powershell.
Here is the Powershell sample:
$token = "PAT"
$url="https://feeds.dev.azure.com/{Organization Name}/{Project Name}/_apis/packaging/feeds?api-version=6.0-preview.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
ForEach( $feedid in $response.value.id )
{
echo $feedid
$url1="https://feeds.dev.azure.com/{Organization Name}/{Project Name}/_apis/packaging/Feeds/$($feedid)/packages?api-version=6.0-preview.1"
$response1 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
Write-Host "Package = $($response1 | ConvertTo-Json -Depth 100)"
}
In this case, you can get alls feeds of project scope in a project, and then get all the packages in it.
By the way, if you want to get all organization scope feeds, you only need to delete the project parameter in the URL.