如何通过Azure管理api转on/offAzure虚拟机(休息)

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

我想为自己创建一个 start/stop Azure VM 机器人。我想要做的是让 slack/telegram 机器人通过命令 /start/stop 监听消息和 starts/stops 我的虚拟机。我应该使用什么 REST api 命令来做到这一点?

需要什么:

调用 Azure 管理 API 启动解除分配的虚拟机的 C# 示例代码

一些参考资料,我可以在其中获取 API 方法参数的值(例如订阅 ID、资源 ID 等)。

还有

我已阅读 this 问题,但它并没有帮助我理解如何处理授权以及从哪里获取这些参数。

我正在使用 C# 语言创建该机器人。

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).

您可以在 Azure 门户上找到 {subscriptionId}{ resourceGroup}

how to deal with authorization

您可以查看 this article 以开始使用 Azure REST 操作和请求身份验证。您可以参考以下代码获取访问令牌。

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;

另外,这篇文章说明了如何create AD application and service principal that can access resources,请参考。