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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With