How to turn on/off Azure virtual machine via Azure management api (rest)
Asked Answered
B

1

6

I want to create a start/stop Azure VM bot for myself. What I want to do is to have a slack/telegram bot that listens to messages and starts/stops my VM by commands /start/stop. What REST api command should I use to do that?

What is needed:

Some sample code in C# that calls azure management API to start deallocated virtual machine

Some reference where I can get values for API method parameters (e.g. subscription id, resource id, etc).

Also

I have read this question, but it didn't help me to understand how to deal with authorization and where to get those parameters.

I am creating that bot using C# language.

Breadthways answered 6/10, 2017 at 14:38 Comment(1)
Add more details about what you want to achieve. The link you try to post does not works.Mullet
C
9

calls azure management API to start deallocated virtual machine

Virtual Machines REST API lists the operations on virtual machines. To start a virtual machine, you can try this API:

POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{vm}/start?api-version={apiVersion}

where I can get values for API method parameters (e.g. subscription id, resource id, etc).

You can find {subscriptionId} and { resourceGroup} on Azure portal.

enter image description here

how to deal with authorization

You can check this article to get started with Azure REST operations and request authentication. And you can refer to the following code to acquire an access token.

string tenantId = "{tenantId}";
string clientId = "{clientId}";
string clientSecret = "{secret}";
string subscriptionid = "{subscriptionid}";

string authContextURL = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientSecret);
var result = await authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential);

if (result == null)
{
    throw new InvalidOperationException("Failed to obtain the JWT token");
}

string token = result.AccessToken;

Besides, this article explained how to create AD application and service principal that can access resources, please refer to it.

Caaba answered 12/10, 2017 at 8:55 Comment(1)
Worked like a charm! Thanks!Breadthways

© 2022 - 2024 — McMap. All rights reserved.