Azure DevTest Labs에 대한 Azure PowerShell 샘플

이 문서에는 Azure DevTest Labs에 대한 다음 샘플 Azure PowerShell 스크립트가 포함되어 있습니다.

필수 조건

  • 사용자 또는 역할을 추가하거나 할당하려면 랩의 소유자 역할 또는 랩이 포함된 Azure 구독의 소유자 또는 사용자 액세스 관리자 역할이 필요합니다.
  • 허용되는 랩 VM 크기를 설정하거나, Marketplace 이미지를 추가하거나, 사용자 지정 이미지를 만들려면 랩 또는 Azure 구독에서 적어도 기여자 역할이 필요합니다.
  • 모든 스크립트에는 Azure PowerShell이 필요합니다. Azure Cloud Shell을 사용하거나 PowerShell을 로컬로 설치할 수 있습니다.
    • Cloud Shell에서 PowerShell 환경을 선택합니다.
    • 로컬 PowerShell 설치의 경우 실행 Update-Module -Name Az 하여 최신 버전의 Azure PowerShell을 다운로드하고 Connect-AzAccount 를 실행하여 Azure에 로그인합니다. 여러 Azure 구독이 있는 경우 사용하려는 구독 ID를 제공하는 데 사용합니다 Set-AzContext -SubscriptionId "<SubscriptionId>" .

랩에 외부 사용자 추가

이 샘플 PowerShell 스크립트는 DevTest Labs 사용자 역할이 있는 랩에 외부 사용자를 추가합니다. 추가할 사용자는 조직의 Microsoft Entra ID에 있어야 합니다.

스크립트를 사용하려면 주석 아래 # Values to change 의 매개 변수 값을 사용자 고유의 값으로 바꿉다. Azure 포털의 랩 기본 페이지에서 subscriptionId, labResourceGroup, 및 labName 값을 가져올 수 있습니다.

이 스크립트는 다음 명령을 사용합니다.

  • Get-AzADUser: Microsoft Entra ID에서 사용자 개체를 가져옵니다.
  • New-AzRoleAssignment: 지정된 범위에서 지정된 사용자에게 DevTest Labs 사용자 역할을 할당합니다.
# Values to change
$subscriptionId = "<Azure subscription ID>"
$labResourceGroup = "<Lab resource group name>"
$labName = "<Lab name>"
$userDisplayName = "<User display name in Microsoft Entra ID>"

# Select the Azure subscription that contains the lab. This step is optional if you have only one subscription.
Select-AzSubscription -SubscriptionId $subscriptionId

# Get the user object.
$adObject = Get-AzADUser -SearchString $userDisplayName

# Assign the role. 
$labId = ('/subscriptions/' + $subscriptionId + '/resourceGroups/' + $labResourceGroup + '/providers/Microsoft.DevTestLab/labs/' + $labName)
New-AzRoleAssignment -ObjectId $adObject.Id -RoleDefinitionName 'DevTest Labs User' -Scope $labId

사용자 지정 랩 사용자 역할 만들기 및 할당

이 샘플 PowerShell 스크립트는 랩 사용자가 랩 정책을 수정할 수 있도록 하는 사용자 지정 역할을 만들고 사용자 지정 역할을 외부 사용자에게 할당합니다. 역할을 할당할 사용자는 조직의 Microsoft Entra ID에 있어야 합니다.

스크립트를 사용하려면 주석 아래 # Values to change 의 매개 변수 값을 사용자 고유의 값으로 바꿉다. Azure 포털의 랩 기본 페이지에서 subscriptionId, rgName, 및 labName 값을 가져올 수 있습니다.

이 스크립트는 다음 명령을 사용합니다.

  • Get-AzProviderOperation: 리소스 공급자에 사용 가능한 모든 작업을 나열합니다 Microsoft.DevTestLab .
  • Get-AzRoleDefinition: DevTest Labs 사용자 역할에 허용되는 모든 작업을 나열합니다.
  • New-AzRoleDefinition: 새 정책 기여자 사용자 지정 역할을 만듭니다.
  • New-AzRoleAssignment: 지정된 범위에서 지정된 사용자에게 사용자 지정 역할을 할당합니다.
# Values to change
$subscriptionId = "<Azure subscription ID>"
$rgName = "<Lab resource group name>"
$labName = "<Lab name>"
$userDisplayName = "<User display name in Microsoft Entra ID>"

# List all the operations for a resource provider.
Get-AzProviderOperation -OperationSearchString "Microsoft.DevTestLab/*"

# List allowed actions for a role.
(Get-AzRoleDefinition "DevTest Labs User").Actions

# Create the custom role.
$policyRoleDef = (Get-AzRoleDefinition "DevTest Labs User")
$policyRoleDef.Id = $null
$policyRoleDef.Name = "Policy Contributor"
$policyRoleDef.IsCustom = $true
$policyRoleDef.AssignableScopes.Clear()
$policyRoleDef.AssignableScopes.Add("/subscriptions/" + $subscriptionId)
$policyRoleDef.Actions.Add("Microsoft.DevTestLab/labs/policySets/policies/*")
$policyRoleDef = (New-AzRoleDefinition -Role $policyRoleDef)

# Retrieve the user object.
$adObject = Get-AzADUser -SearchString $userDisplayName

# Create the role assignment. 
$scope = '/subscriptions/' + $subscriptionId + '/resourceGroups/' + $rgName + '/providers/Microsoft.DevTestLab/labs/' + $labName + '/policySets/default/policies/*'
New-AzRoleAssignment -ObjectId $adObject.Id -RoleDefinitionName "Policy Contributor" -Scope $scope

허용되는 VM 크기 설정

이 샘플 PowerShell 스크립트는 랩 VM을 만드는 데 허용되는 크기를 설정합니다. 메시지가 표시될 때 스크립트에서 호출하는 정보를 제공합니다.

param (
[Parameter(Mandatory=$true, HelpMessage="The name of the DevTest Lab to update")]
    [string] $DevTestLabName,
[Parameter(Mandatory=$true, HelpMessage="The array of VM sizes to add")]
    [Array] $SizesToAdd
)

function Get-Lab
{
    $lab = Get-AzResource -ResourceType 'Microsoft.DevTestLab/labs' -Name $DevTestLabName

if(!$lab)
    {
        throw "Lab named $DevTestLabName was not found"
    }
    
    return $lab
}

function Get-PolicyChanges ($lab)
{
    #start by finding the existing policy
    $script:labResourceName = $lab.Name + '/default'
    $existingPolicy = (Get-AzResource -ResourceType 'Microsoft.DevTestLab/labs/policySets/policies' -Name $labResourceName -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2016-05-15) | Where-Object {$_.Name -eq 'AllowedVmSizesInLab'}
    if($existingPolicy)
    {
        $existingSizes = $existingPolicy.Properties.threshold
        $savePolicyChanges = $false
    }
    else
    {
        $existingSizes = ''
        $savePolicyChanges = $true
    }

if($existingPolicy.Properties.threshold -eq '[]')
    {
        Write-Output "Skipping $($lab.Name) because it currently allows all sizes"
        return
    }

# Make a list of all the current allowed sizes plus the `$SizesToAdd`.
    $finalVmSizes = $existingSizes.Replace('[', '').Replace(']', '').Split(',',[System.StringSplitOptions]::RemoveEmptyEntries)

foreach($vmSize in $SizesToAdd)
    {
        $quotedSize = '"' + $vmSize + '"'

if(!$finalVmSizes.Contains($quotedSize))
        {
            $finalVmSizes += $quotedSize
            $savePolicyChanges = $true
        }
    }

if(!$savePolicyChanges)
    {
        Write-Output "No policy changes required for VMSize in lab $($lab.Name)"
    }

return @{
        existingPolicy = $existingPolicy
        savePolicyChanges = $savePolicyChanges
        finalVmSizes = $finalVmSizes
    }
}

function Set-PolicyChanges ($lab, $policyChanges)
{
    if($policyChanges.savePolicyChanges)
    {
        $thresholdValue = ('[' + [String]::Join(',', $policyChanges.finalVmSizes) + ']')

$policyObj = @{
            subscriptionId = $lab.SubscriptionId
            status = 'Enabled'
            factName = 'LabVmSize'
            resourceGroupName = $lab.ResourceGroupName
            labName = $lab.Name
            policySetName = 'default'
            name = $lab.Name + '/default/allowedvmsizesinlab'
            threshold = $thresholdValue
            evaluatorType = 'AllowedValuesPolicy'
        }

$resourceType = "Microsoft.DevTestLab/labs/policySets/policies/AllowedVmSizesInLab"
        if($policyChanges.existingPolicy)
        {
            Write-Output "Updating $($lab.Name) VM Size policy"
            Set-AzResource -ResourceType $resourceType -ResourceName $labResourceName -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2016-05-15 -Properties $policyObj -Force
        }
        else
        {
            Write-Output "Creating $($lab.Name) VM Size policy"
            New-AzResource -ResourceType $resourceType -ResourceName $labResourceName -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2016-05-15 -Properties $policyObj -Force
        }
    }
}

$lab = Get-Lab
$policyChanges = Get-PolicyChanges $lab
Set-PolicyChanges $lab $policyChanges

랩에 Marketplace 이미지 추가

이 샘플 PowerShell 스크립트는 랩 VM 만들기에 사용할 수 있는 기본 이미지에 Marketplace 이미지를 추가합니다. 메시지가 표시될 때 스크립트에서 호출하는 정보를 제공합니다.

스크립트는 다음 명령을 사용합니다.

  • Get-AzResource: 랩, 랩 정책 및 갤러리 이미지 리소스를 가져옵니다.
  • Set-AzResource: 기존 랩 Marketplace 이미지 정책을 수정합니다.
  • New-AzResource: 새로운 실험실 Marketplace 이미지 정책을 만듭니다.
param (
[Parameter(Mandatory=$true, HelpMessage="The name of the DevTest Lab to update")]
    [string] $DevTestLabName,
[Parameter(Mandatory=$true, HelpMessage="The array of Marketplace image names to enable")]
    [Array] $ImagesToAdd
)

function Get-Lab
{
    $lab = Get-AzResource -ResourceType 'Microsoft.DevTestLab/labs' -Name $DevTestLabName

if(!$lab)
    {
        throw "Lab named $DevTestLabName was not found"
    }
    
    return $lab
}

function Get-PolicyChanges ($lab)
{
    #start by finding the existing policy
    $script:labResourceName = $lab.Name + '/default'
    $existingPolicy = (Get-AzResource -ResourceType 'Microsoft.DevTestLab/labs/policySets/policies' -Name $labResourceName -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2016-05-15) | Where-Object {$_.Name -eq 'GalleryImage'}
    if($existingPolicy)
    {
        $existingImages = [Array] (ConvertFrom-Json $existingPolicy.Properties.threshold)
        $savePolicyChanges = $false
    }
    else
    {
        $existingImages =  @()
        $savePolicyChanges = $true
    }

if($existingPolicy.Properties.threshold -eq '[]')
    {
        Write-Output "Skipping $($lab.Name) because it currently allows all marketplace images"
        return
    }

$allAvailableImages = Get-AzResource -ResourceType Microsoft.DevTestLab/labs/galleryImages -Name $lab.Name -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2017-04-26-preview
    $finalImages = $existingImages

# loop through the requested images and add them to the finalImages list if they aren't already there
    foreach($image in $ImagesToAdd)
    {
        $imageObject = $allAvailableImages | Where-Object {$_.Name -eq $image}
        
        if(!$imageObject)
        {
            throw "Image $image is not available in the lab"
        }

$addImage = $true
        $parsedAvailableImage = $imageObject.Properties.imageReference

foreach($finalImage in $finalImages)
        {
            # determine whether or not the requested image is already allowed in this lab
            $parsedFinalImg = ConvertFrom-Json $finalImage

if($parsedFinalImg.offer -eq $parsedAvailableImage.offer -and $parsedFinalImg.publisher -eq $parsedAvailableImage.publisher -and $parsedFinalImg.sku -eq $parsedAvailableImage.sku -and $parsedFinalImg.osType -eq $parsedAvailableImage.osType -and $parsedFinalImg.version -eq $parsedAvailableImage.version)
            {
                $addImage = $false
                break
            }
        }

if($addImage)
        {
            Write-Output "  Adding image $image to the lab"
            $finalImages += ConvertTo-Json $parsedAvailableImage -Compress
            $savePolicyChanges = $true
        }
    }

if(!$savePolicyChanges)
    {
        Write-Output "No policy changes required for allowed Marketplace Images in lab $($lab.Name)"
    }

return @{
        existingPolicy = $existingPolicy
        savePolicyChanges = $savePolicyChanges
        finalImages = $finalImages
    }
}

function Set-PolicyChanges ($lab, $policyChanges)
{
    if($policyChanges.savePolicyChanges)
    {
        $thresholdValue = '["'
        for($i = 0; $i -lt $policyChanges.finalImages.Length; $i++)
        {
            $value = $policyChanges.finalImages[$i]
            if($i -ne 0)
            {
                $thresholdValue = $thresholdValue + '","'
            }

            $thresholdValue = $thresholdValue + $value.Replace('"', '\"')
        }
        $thresholdValue = $thresholdValue + '"]'

$policyObj = @{
            status = 'Enabled'
            factName = 'GalleryImage'
            threshold = $thresholdValue
            evaluatorType = 'AllowedValuesPolicy'
        }

$resourceType = "Microsoft.DevTestLab/labs/policySets/policies/galleryimage"
        if($policyChanges.existingPolicy)
        {
            Write-Output "Updating $($lab.Name) Marketplace Images policy"
            Set-AzResource -ResourceType $resourceType -ResourceName $labResourceName -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2017-04-26-preview -Properties $policyObj -Force
        }
        else
        {
            Write-Output "Creating $($lab.Name) Marketplace Images policy"
            New-AzResource -ResourceType $resourceType -ResourceName $labResourceName -ResourceGroupName $lab.ResourceGroupName -ApiVersion 2017-04-26-preview -Properties $policyObj -Force
        }
    }
}

$lab = Get-Lab
$policyChanges = Get-PolicyChanges $lab
Set-PolicyChanges $lab $policyChanges

VHD 파일에서 사용자 지정 이미지 만들기

이 샘플 PowerShell 스크립트는 공용 DevTest Labs 템플릿 리포지토리의 배포 템플릿을 사용하여 VHD 파일에서 DevTest Labs 사용자 지정 이미지를 만듭니다. 이 스크립트를 사용하려면 랩의 Azure Storage 계정에 업로드된 Windows VHD 파일이 필요합니다.

스크립트를 사용하려면 주석 아래 # Values to change 의 매개 변수 값을 사용자 고유의 값으로 바꿉다. Azure 포털의 랩 기본 페이지에서 subscriptionId, labRg, 및 labName 값을 가져올 수 있습니다. vhdUri VHD 파일을 업로드한 Azure Storage 컨테이너에서 값을 가져옵니다.

이 스크립트는 다음 명령을 사용합니다.

# Values to change
$subscriptionId = '<Azure subscription ID>'
$labRg = '<Lab resource group name>'
$labName = '<Lab name>'
$vhdUri = '<URI for the uploaded VHD>'
$customImageName = '<Name for the custom image>'
$customImageDescription = '<Description for the custom image>'

# Select the Azure subscription. 
Select-AzSubscription -SubscriptionId $subscriptionId

# Get the lab object.
$lab = Get-AzResource -ResourceId ('/subscriptions/' + $subscriptionId + '/resourceGroups/' + $labRg + '/providers/Microsoft.DevTestLab/labs/' + $labName)

# Get the lab storage account and lab storage account key values.
$labStorageAccount = Get-AzResource -ResourceId $lab.Properties.defaultStorageAccount 
$labStorageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $labStorageAccount.ResourceGroupName -Name $labStorageAccount.ResourceName)[0].Value

# Set up the parameters object.
$parameters = @{existingLabName="$($lab.Name)"; existingVhdUri=$vhdUri; imageOsType='windows'; isVhdSysPrepped=$false; imageName=$customImageName; imageDescription=$customImageDescription}

# Create the custom image.
New-AzResourceGroupDeployment -ResourceGroupName $lab.ResourceGroupName -Name CreateCustomImage -TemplateUri 'https://raw.githubusercontent.com/Azure/azure-devtestlab/master/samples/DevTestLabs/QuickStartTemplates/201-dtl-create-customimage-from-vhd/azuredeploy.json' -TemplateParameterObject $parameters

Azure PowerShell 설명서