Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 912
ALEX TRUSHKO Avatar asked Oct 06 '17 14:10

ALEX TRUSHKO


1 Answers

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.

like image 78
Fei Han Avatar answered Sep 20 '22 10:09

Fei Han