Azure.ResourceManager.Compute を使えば、C# で仮想マシンの停止・開始・再起動ができる。
認証には Azure.Identity を使う。
アプリに組み込んで使うことを想定しているので、Azure AD でアプリを登録しておく。
- Microsoft Azure ポータルで、リソースグループと仮想マシンはあらかじめ用意
- Azure Active Directory のアプリ登録でアプリを登録
- リソースグループのアクセス制御(IAM)で、ロールの割り当てを追加
- 登録したアプリに仮想マシン共同作成者をひとまず割り当てておく
using Azure; using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.Compute; const string ClientId = "クライアント ID"; const string ClientSecret = "クライアントシークレット"; const string TenantId = "テナント ID"; const string SubscriptionId = "サブスクリプション ID"; const string ResourceGroupName = "リソースグループ名"; const string VmName = "仮想マシン名"; var credential = new ClientSecretCredential( tenantId: TenantId, clientId: ClientId, clientSecret: ClientSecret); var client = new ArmClient(credential); var id = VirtualMachineResource.CreateResourceIdentifier( subscriptionId: SubscriptionId, resourceGroupName: ResourceGroupName, vmName: VmName); var vm = client.GetVirtualMachineResource(id); // 仮想マシンの停止 await vm.DeallocateAsync(WaitUntil.Completed); // 仮想マシンの開始 await vm.PowerOnAsync(WaitUntil.Completed); // 再起動 await vm.RestartAsync(WaitUntil.Completed);