Azure REST API: Stop a classic service - azure

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

Related

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

Get Azure DevOps service connection service principal id with powershell

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

Is there a way to make an API call from Azure runbook?

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.

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"

How to get the provisioning state of the azure resource deployment through invoke command (REST API)

Deployment of webjobs in a web app
$t=Invoke-RestMethod -Uri $Url -Headers $Headers -UserAgent $userAgent -Method PUT -InFile $f
You can use following Azure Rest API to get the deployment status of Azure Web App resources.
https://learn.microsoft.com/en-us/rest/api/appservice/webapps/getdeployment
There's a nice "Try it" section, where you can play this API, live with your subscription.
Edit 1
Please follow here on how to call Azure Rest APIs via Powershell:
https://blog.tekspace.io/access-azure-rest-api-using-powershellhttps://blog.tekspace.io/access-azure-rest-api-using-powershell/
Let me know if that helps!

Resources