Share via


Azure PowerShellを使用して DevTest Labs VM を作成します

この記事では、Azure PowerShell を使用して Azure DevTest Labs でラボ仮想マシンを作成する方法について説明します。 PowerShell スクリプトを使用して、ラボ VM の作成を自動化できます。

前提条件

この記事の手順に従うには、次の前提条件が必要です。

PowerShell VM 作成スクリプト

PowerShell Invoke-AzResourceAction コマンドレットはcreateEnvironment、ラボのリソース ID と VM パラメーターを使用してアクションを呼び出します。 それらのパラメーターは、すべてのVMプロパティが含まれたハッシュ テーブルにあります。 型のプロパティはVMの型によって異なります。 必要な VM の型のプロパティを取得するには、VM のプロパティの 取得に関するページを参照してください。

このサンプル スクリプトでは、Windows Server 2019 Datacenter VM を作成します。 このサンプルには、dataDiskParameters の下に 2 つ目のデータ ディスクを追加するプロパティも含まれています。

[CmdletBinding()]

Param(
[Parameter(Mandatory = $false)]  $SubscriptionId,
[Parameter(Mandatory = $true)]   $LabResourceGroup,
[Parameter(Mandatory = $true)]   $LabName,
[Parameter(Mandatory = $true)]   $NewVmName,
[Parameter(Mandatory = $true)]   $UserName,
[Parameter(Mandatory = $true)]   $Password
)

pushd $PSScriptRoot

try {
    if ($SubscriptionId -eq $null) {
        $SubscriptionId = (Get-AzContext).Subscription.SubscriptionId
    }

    $API_VERSION = '2016-05-15'
    $lab = Get-AzResource -ResourceId "/subscriptions/$SubscriptionId/resourceGroups/$LabResourceGroup/providers/Microsoft.DevTestLab/labs/$LabName"

    if ($lab -eq $null) {
       throw "Unable to find lab $LabName resource group $LabResourceGroup in subscription $SubscriptionId."
    }

    $virtualNetwork = @(Get-AzResource -ResourceType  'Microsoft.DevTestLab/labs/virtualnetworks' -ResourceName $LabName -ResourceGroupName $lab.ResourceGroupName -ApiVersion $API_VERSION)[0]

    #The preceding command puts the VM in the first allowed subnet in the first virtual network for the lab.
    #If you need to use a specific virtual network, use | to find the network. For example:
    #$virtualNetwork = @(Get-AzResource -ResourceType  'Microsoft.DevTestLab/labs/virtualnetworks' -ResourceName $LabName -ResourceGroupName $lab.ResourceGroupName -ApiVersion $API_VERSION) | Where-Object Name -EQ "SpecificVNetName"

    $labSubnetName = $virtualNetwork.properties.allowedSubnets[0].labSubnetName

    #Prepare all the properties needed for the createEnvironment call.
    # The properties are slightly different depending on the type of VM base.
    # The virtual network setup might also affect the properties.

    $parameters = @{
       "name"      = $NewVmName;
       "location"  = $lab.Location;
       "properties" = @{
          "labVirtualNetworkId"     = $virtualNetwork.ResourceId;
          "labSubnetName"           = $labSubnetName;
          "notes"                   = "Windows Server 2019 Datacenter";
          "osType"                  = "windows"
          "expirationDate"          = "2022-12-01"
          "galleryImageReference"   = @{
             "offer"     = "WindowsServer";
             "publisher" = "MicrosoftWindowsServer";
             "sku"       = "2019-Datacenter";
             "osType"    = "Windows";
             "version"   = "latest"
          };
          "size"                    = "Standard_DS2_v2";
          "userName"                = $UserName;
          "password"                = $Password;
          "disallowPublicIpAddress" = $true;
          "dataDiskParameters" = @(@{
            "attachNewDataDiskOptions" = @{
                "diskName" = "adddatadisk"
                "diskSizeGiB" = "1023"
                "diskType" = "Standard"
                }
          "hostCaching" = "ReadWrite"
          })
       }
    }

    #The following line has the same effect as invoking the
    # https://azure.github.io/projects/apis/#!/Labs/Labs_CreateEnvironment REST API

    Invoke-AzResourceAction -ResourceId $lab.ResourceId -Action 'createEnvironment' -Parameters $parameters -ApiVersion $API_VERSION -Force -Verbose
}
finally {
   popd
}

前のスクリプトをCreate-LabVirtualMachine.ps1 という名前の ファイルに保存。 次のコマンドを使用してスクリプトを実行します。 プレースホルダー用に実際の値を入力します。

.\Create-LabVirtualMachine.ps1 -ResourceGroupName '<lab resource group name>' -LabName '<lab name>' -userName '<VM administrative username>' -password '<VM admin password>' -VMName '<VM name to create>'

VM プロパティの取得

このセクションでは、作成したいVMの型の特定のプロパティの取得方法について説明します。 プロパティは、Azure portal の Azure Resource Manager (ARM) テンプレートから、または DevTest Labs Azure REST API を呼び出すことによって取得できます。

VM のプロパティを取得するにはAzure portaを使用します。

Azure portalで VM を作成すると、VM のプロパティを示すAzure Resource Manager (ARM) テンプレートが生成されます。 VM ベースを選択すると、ARM テンプレートを表示し、実際に VM を作成せずにプロパティを取得できます。 この方法は、その型のラボ VM をまだ持ってない場合に、JSON VM の説明を取得する最も簡単な方法です。

  1. Azure portalでご自身のラボの [概要] ページ で、上部のツール バーの [追加 ] を選択します。

  2. [ベースの選択] ページで、目的の VM の種類を選びます。 ラボの設定に応じて、VM ベースは、Azure Marketplace、カスタム イメージ、数式、または環境にできます。

  3. [ラボ リソースの作成] ページで、必要に応じてアーティファクトを追加し、[基本設定] タブと [詳細設定]タブで必要なその他の設定を構成します。

  4. [詳細設定 ] タブで 、ページの下部 にある [ARM テンプレートの表示] を選択します。

  5. [ Azure Resource Managerテンプレート]のページで 、VM を作成するための JSON テンプレートを確認します。 [リソース]セクション には VM プロパティがあります。

    たとえば、次のセクションresourcesには、Windows Server 2022 Datacenter VM のプロパティがあります。

      "resources": [
           {
                "apiVersion": "2018-10-15-preview",
                "type": "Microsoft.DevTestLab/labs/virtualmachines",
                "name": "[variables('vmName')]",
                "location": "[resourceGroup().location]",
                "properties": {
                     "labVirtualNetworkId": "[variables('labVirtualNetworkId')]",
                     "notes": "Windows Server 2022 Datacenter: Azure Edition Core",
                     "galleryImageReference": {
                          "offer": "WindowsServer",
                          "publisher": "MicrosoftWindowsServer",
                          "sku": "2022-datacenter-azure-edition-core",
                          "osType": "Windows",
                          "version": "latest"
                     },
                     "size": "[parameters('size')]",
                     "userName": "[parameters('userName')]",
                     "password": "[parameters('password')]",
                     "isAuthenticationWithSshKey": false,
                     "labSubnetName": "[variables('labSubnetName')]",
                     "disallowPublicIpAddress": true,
                     "storageType": "Standard",
                     "allowClaim": false,
                     "networkInterface": {
                          "sharedPublicIpAddressConfiguration": {
                               "inboundNatRules": [
                                    {
                                         "transportProtocol": "tcp",
                                         "backendPort": 3389
                                    }
                               ]
                          }
                     }
                }
           }
      ],
    
  6. 今後の PowerShell オートメーションで使用するテンプレートをコピーして保存し、プロパティを PowerShell VM 作成スクリプトに転送します。

DevTest Labs Azure REST APIを使用して VM のプロパティを取得する

DevTest Labs REST API を呼び出し、既存のラボ VM のプロパティを取得できます。 これらのプロパティを使用して、同じ型のラボ VM を作成できます。

  1. [Virtual Machines - リスト] ページで、 最初の コード ブロックの 上にある [試してみる] を選択します。
  2. [ REST API 試す] ページで、次の方法を 実行します。
    • [labName] にラボ名を入力します。
    • [labResourceGroup] で、ラボ リソース グループ名を入力します。
    • [ subscriptionId] で、ラボの Azure サブスクリプションを選択します。
  3. [実行] を選択します。
  4. [応答 ] セクション[本文] で、ラボ内のすべての既存の VM のプロパティを表示します。

VM の有効期限を設定する

トレーニング、デモ、試用版のシナリオでは、特定の日付に VM を自動的に削除することで、不要なコストを回避できます。 VM を作成するときに、VM expirationDate プロパティを設定できます。 この記事で既に説明した PowerShell VM 作成スクリプトでは、properties に有効期限を設定します 。

  "expirationDate": "2022-12-01"

PowerShell を使用して、既存の VM の有効期限を設定できます。 次の PowerShell スクリプトは、既存のラボ VM に有効期限をまだ設定していない場合は、有効期限を設定します。

# Enter your own values:
$subscriptionId = '<Lab subscription Id>'
$labResourceGroup = '<Lab resource group>'
$labName = '<Lab name>'
$VmName = '<VM name>'
$expirationDate = '<Expiration date, such as 2022-12-16>'

# Sign in to your Azure account

Select-AzSubscription -SubscriptionId $subscriptionId
$VmResourceId = "subscriptions/$subscriptionId/resourcegroups/$labResourceGroup/providers/microsoft.devtestlab/labs/$labName/virtualmachines/$VmName"

$vm = Get-AzResource -ResourceId $VmResourceId -ExpandProperties

# Get the Vm properties
$VmProperties = $vm.Properties

# Set the expirationDate property
If ($VmProperties.expirationDate -eq $null) {
    $VmProperties | Add-Member -MemberType NoteProperty -Name expirationDate -Value $expirationDate -Force
} Else {
    $VmProperties.expirationDate = $expirationDate
}

Set-AzResource -ResourceId $VmResourceId -Properties $VmProperties -Force

次のステップ

Az.DevTestLabs PowerShell リファレンス