Share via


Azure PowerShell을 사용하여 DevTest Labs VM 만들기

이 문서에서는 Azure PowerShell을 사용하여 랩에서 Azure DevTest Labs 가상 머신(VM)을 만드는 방법을 보여줍니다. PowerShell 스크립트를 사용하여 랩 VM 만들기를 자동화할 수 있습니다.

필수 조건

이 문서를 진행하려면 다음 필수 구성 요소가 필요합니다.

PowerShell VM 생성 스크립트

PowerShell Invoke-AzResourceAction cmdlet은 랩의 리소스 ID 및 VM 매개변수를 사용하여 createEnvironment 작업을 호출합니다. 매개 변수는 모든 VM 속성을 포함하는 해시 테이블에 있습니다. 속성은 VM 유형마다 다릅니다. 원하는 VM 유형에 대한 속성을 얻으려면 VM 속성 가져오기를 참조하세요.

이 샘플 스크립트는 Windows Server 2019 Datacenter VM을 만듭니다. 이 샘플에는 dataDiskParameters 아래에 두 번째 데이터 디스크를 추가하는 속성도 포함되어 있습니다.

[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의 ARM(Azure Resource Manager) 템플릿에서 또는 DevTest Labs Azure REST API를 호출하여 속성을 가져올 수 있습니다.

Azure Portal을 사용하여 VM 속성 가져오기

Azure Portal에서 VM을 만들면 VM의 속성을 보여주는 ARM(Azure Resource Manager) 템플릿이 생성됩니다. VM 기반을 선택하면 실제로 VM을 만들지 않고도 ARM 템플릿을 보고 속성을 가져올 수 있습니다. 이 메서드는 JSON VM 설명을 얻는 가장 쉬운 방법입니다(해당 유형의 랩 VM이 아직 없는 경우).

  1. Azure Portal의 랩 개요 페이지 위쪽 도구 모음에서 추가를 선택합니다.

  2. 기본 선택 페이지에서 원하는 VM 유형을 선택합니다. 랩 설정에 따라 VM 기반은 Azure Marketplace 이미지, 사용자 지정 이미지, 수식 또는 환경일 수 있습니다.

  3. 랩 리소스 만들기 페이지에서 필요에 따라 아티팩트를 추가하고 기본 설정고급 설정 탭에서 원하는 다른 설정을 구성합니다.

  4. 고급 설정 탭의 페이지 아래쪽에서 ARM 템플릿 보기를 선택합니다.

  5. Azure Resource Manager 템플릿 보기 페이지에서 VM을 만들기 위한 JSON 템플릿을 검토합니다. resources 섹션에는 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 참조