C# で Azure VM の停止・開始・再起動を行う

Azure.ResourceManager.Compute を使えば、C#仮想マシンの停止・開始・再起動ができる。

www.nuget.org

認証には Azure.Identity を使う。

www.nuget.org

アプリに組み込んで使うことを想定しているので、Azure AD でアプリを登録しておく。

  1. Microsoft Azure ポータルで、リソースグループと仮想マシンはあらかじめ用意
  2. Azure Active Directory のアプリ登録でアプリを登録
  3. リソースグループのアクセス制御(IAM)で、ロールの割り当てを追加
    • 登録したアプリに仮想マシン共同作成者をひとまず割り当てておく

C# .NET 6 コンソールアプリを書いてみた。

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