Azure DevTest Labs için Azure PowerShell örnekleri

Bu makale, Azure DevTest Labs için aşağıdaki örnek Azure PowerShell betiklerini içerir:

Önkoşullar

  • Kullanıcı veya rol eklemek veya atamak için laboratuvarda Sahip rolüne veya laboratuvarı içeren Azure aboneliğinde Sahip veya Kullanıcı Erişimi Yöneticisi rolüne ihtiyacınız vardır.
  • İzin verilen laboratuvar VM boyutlarını ayarlamak, Market görüntüsü eklemek veya özel görüntü oluşturmak için laboratuvarda veya Azure aboneliğinde en az Katkıda Bulunan rolüne sahip olmanız gerekir.
  • Tüm betikler Için Azure PowerShell gerekir. Azure Cloud Shell'i kullanabilir veya PowerShell'i yerel olarak yükleyebilirsiniz.
    • Cloud Shell'de PowerShell ortamını seçin.
    • Yerel bir PowerShell yüklemesi için komutunu çalıştırarak Update-Module -Name Az Azure PowerShell'in en son sürümünü alın ve Connect-AzAccount komutunu çalıştırarak Azure'da oturum açın. Birden çok Azure aboneliğiniz varsa, kullanmak istediğiniz abonelik kimliğini sağlamak için kullanın Set-AzContext -SubscriptionId "<SubscriptionId>" .

Laboratuvara dış kullanıcı ekleme

Bu örnek PowerShell betiği , DevTest Labs Kullanıcı rolüne sahip bir laboratuvara dış kullanıcı ekler. Eklenecek kullanıcı, kuruluşun Microsoft Entra Kimliği'nde olmalıdır.

Betiği kullanmak için açıklamanın altındaki # Values to change parametre değerlerini kendi değerlerinizle değiştirin. Azure portalında laboratuvarın subscriptionIdana sayfasından , labResourceGroupve labName değerlerini alabilirsiniz.

Bu betik şu komutları kullanır:

  • Get-AzADUser: Kullanıcı nesnesini Microsoft Entra Id'den alır.
  • New-AzRoleAssignment: Belirtilen kapsamda belirtilen kullanıcıya DevTest Labs Kullanıcı rolünü atar.
# 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

Özel laboratuvar kullanıcı rolü oluşturma ve atama

Bu örnek PowerShell betiği, laboratuvar kullanıcılarının laboratuvar ilkelerini değiştirmesine olanak tanıyan özel bir rol oluşturur ve özel rolü bir dış kullanıcıya atar. Rolü atayan kullanıcının kuruluşun Microsoft Entra kimliğinde olması gerekir.

Betiği kullanmak için açıklamanın altındaki # Values to change parametre değerlerini kendi değerlerinizle değiştirin. Azure portalında laboratuvarın subscriptionIdana sayfasından , rgNameve labName değerlerini alabilirsiniz.

Bu betik şu komutları kullanır:

# 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

İzin verilen VM boyutlarını ayarlama

Bu örnek PowerShell betiği, laboratuvar VM'leri oluşturmak için izin verilen boyutları ayarlar. Betik sizden bilgi istediğinde gerekli bilgileri sağlayın.

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

Laboratuvara Pazar Yeri görseli ekleyin

Bu örnek PowerShell betiği, laboratuvar VM'sinin oluşturulması için kullanılabilir temel görüntülere bir Market görüntüsü ekler. Betik istediğinde talep ettiği bilgileri sağlayın.

Betik aşağıdaki komutları kullanır:

  • Get-AzResource: Laboratuvar, laboratuvar ilkesi ve galeri görüntüsü kaynaklarını alır.
  • Set-AzResource: Mevcut laboratuvar Pazarı görüntü ilkesini değiştirir.
  • New-AzResource: Yeni bir laboratuvar Marketplace görüntü politikası oluşturur.
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 dosyasından özel görüntü oluşturma

Bu örnek PowerShell betiği, genel DevTest Labs şablon deposundan bir dağıtım şablonu kullanarak bir VHD dosyasından DevTest Labs özel görüntüsü oluşturur. Bu betik, laboratuvarın Azure Depolama hesabına yüklenmiş bir Windows VHD dosyası gerektirir.

Betiği kullanmak için açıklamanın altındaki # Values to change parametre değerlerini kendi değerlerinizle değiştirin. Azure portalında laboratuvarın subscriptionIdana sayfasından , labRgve labName değerlerini alabilirsiniz. vhdUri VHD dosyasını yüklediğiniz Azure Depolama kapsayıcısından değeri alın.

Bu betik şu komutları kullanır:

# 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 belgeleri