C# で VPN ゲートウェイのアドレスプールを変更する

Microsoft Azure の仮想ネットワークに VPN の P2S で繋ぐとき、クライアントのアドレスプールをあらかじめポータルで設定しておくけど、REST APISDK でもアドレスプールを変更できる。

www.nuget.org

ポータルではアドレスプールなのに対し、REST APISDK では VpnClientAddressPrefixes だったので、見つけるの苦労した。

using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Network;
using Azure.ResourceManager.Resources;

const string ClientId = "クライアントID";
const string ClientSecret = "クライアントシークレット";
const string TenantId = "テナントID";
const string SubscriptionId = "サブスクリプションID";
const string ResourceGroupName = "リソースグループ名";
const string VirtualNetworkGatewayName = "VPNゲートウェイ名";

var credential = new ClientSecretCredential(
    tenantId: TenantId,
    clientId: ClientId,
    clientSecret: ClientSecret);
var client = new ArmClient(credential);

ResourceGroupResource resourceGroup = await client.GetSubscriptionResource(
    SubscriptionResource.CreateResourceIdentifier(SubscriptionId))
    .GetResourceGroupAsync(ResourceGroupName);

VirtualNetworkGatewayResource gateway = await resourceGroup.GetVirtualNetworkGatewayAsync(VirtualNetworkGatewayName);
foreach (var prefix in gateway.Data.VpnClientConfiguration.VpnClientAddressPrefixes)
{
    Console.WriteLine(prefix);
}

// VPN クライアントのアドレスプールを変更する。
gateway.Data.VpnClientConfiguration.VpnClientAddressPrefixes.Clear();
gateway.Data.VpnClientConfiguration.VpnClientAddressPrefixes.Add("192.168.10.0/24");

// VPN クライアントのアドレスプールを変更を反映させる。
// 完了まで待つと結構時間がかかるので、タイムアウトが気になる場合は
// WaitUntil.Started の方がいいかもしれない。
var gatewayCollection = resourceGroup.GetVirtualNetworkGateways();
var updateOperation = await gatewayCollection.CreateOrUpdateAsync(
    waitUntil: WaitUntil.Completed,
    virtualNetworkGatewayName: VirtualNetworkGatewayName,
    data: gateway.Data);
VirtualNetworkGatewayResource updatedGateway = await updateOperation.WaitForCompletionAsync();
foreach (var prefix in updatedGateway.Data.VpnClientConfiguration.VpnClientAddressPrefixes)
{
    Console.WriteLine(prefix);
}