Azure Lab Services 用 Azure PowerShell サンプル
この記事には、Azure Lab Services 用のサンプル Azure PowerShell スクリプトが含まれています。
注意
Azure を操作するには、Azure Az PowerShell モジュールを使用することをお勧めします。 作業を開始するには、Azure PowerShell のインストールに関する記事を参照してください。 Az PowerShell モジュールに移行する方法については、「AzureRM から Az への Azure PowerShell の移行」を参照してください。
このサンプルには、Azure PowerShell Az 1.0 以降が必要です。 Get-Module -ListAvailable Az
を実行して、インストールされているバージョンを確認します。
インストールする必要がある場合は、Azure PowerShell モジュールのインストールに関するページを参照してください。
Connect-AzAccount を実行して Azure にサインインします。
この記事には、次のサンプルが含まれています。
スクリプト | 説明 |
---|---|
外部ユーザーをラボに追加する | この PowerShell スクリプトは、Azure DevTest Labs でラボに外部ユーザーを追加します。 |
マーケットプレース イメージをラボに追加する | この PowerShell スクリプトは、Azure DevTest Labs でラボにマーケットプレース イメージを追加します。 |
仮想ハード ドライブ (VHD) からカスタム イメージを作成する | この PowerShell スクリプトは、Azure DevTest Labs のラボでカスタム イメージを作成します。 |
ラボ内にカスタム ロールを作成する | この PowerShell スクリプトは、Azure Lab Services のラボ内にカスタム ロールを作成します。 |
許可される仮想マシン サイズを設定する | この PowerShell スクリプトは、許可される仮想マシンのサイズをラボ内に設定します。 |
前提条件
これらのすべてのスクリプトには、次の前提条件があります。
- 既存のラボ。 ラボがない場合は、Azure portal でラボを作成する方法に関するこのクイックスタートに従ってください。
外部ユーザーをラボに追加する
このサンプル PowerShell スクリプトは、Azure DevTest Labs でラボに外部ユーザーを追加します。
# Values to change
$subscriptionId = "<Enter Azure subscription ID here>"
$labResourceGroup = "<Enter lab's resource name here>"
$labName = "<Enter lab name here>"
$userDisplayName = "<Enter user's display name here>"
# Log into your Azure account
Login-AzAccount
# Select the Azure subscription that contains the lab.
# This step is optional if you have only one subscription.
Select-AzSubscription -SubscriptionId $subscriptionId
# Retrieve the user object
$adObject = Get-AzADUser -SearchString $userDisplayName
# Create the role assignment.
$labId = ('subscriptions/' + $subscriptionId + '/resourceGroups/' + $labResourceGroup + '/providers/Microsoft.DevTestLab/labs/' + $labName)
New-AzRoleAssignment -ObjectId $adObject.Id -RoleDefinitionName 'DevTest Labs User' -Scope $labId
このスクリプトでは以下のコマンドを使用します。
コマンド | Notes |
---|---|
Get-AzADUser | Microsoft Entra ID からユーザー オブジェクトを再試行します。 |
New-AzRoleAssignment | 指定したプリンシパルに、指定のスコープで、指定したロールを割り当てます。 |
ラボにマーケットプレース イメージを追加する
このサンプル PowerShell スクリプトは、Azure DevTest Labs でラボにマーケットプレース イメージを追加します。
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' -ResourceNameEquals $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 arent 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
このスクリプトでは以下のコマンドを使用します。
コマンド | Notes |
---|---|
Get-AzResource | リソースを取得します。 |
Set-AzResource | リソースを変更します。 |
New-AzResource | リソースを作成します。 |
VHD ファイルからカスタム イメージを作成する
この PowerShell のサンプル スクリプトは、Azure Lab Services で VHD ファイルからカスタム イメージを作成します。
# Select the desired Azure subscription.
$subscriptionId = '<Specify your subscription ID here>'
Select-AzSubscription -SubscriptionId $subscriptionId
# Get the lab object.
$labRg = '<Specify your lab resource group name here>'
$labName = '<Specify your lab name here>'
$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 the URI of the VHD file.
$vhdUri = '<Specify the VHD URI here>'
# Set the custom image name and description values.
$customImageName = '<Specify the custom image name>'
$customImageDescription = '<Specify the custom image description>'
# 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/201-dtl-create-customimage-from-vhd/azuredeploy.json' -TemplateParameterObject $parameters
このスクリプトでは以下のコマンドを使用します。
コマンド | Notes |
---|---|
Get-AzResource | リソースを取得します。 |
Get-AzStorageAccountKey | Azure ストレージ アカウントのアクセス キーを取得します。 |
New-AzResourceGroupDeployment | リソース グループに Azure デプロイを追加します。 |
ラボ内にカスタム ロールを作成する
この PowerShell のサンプル スクリプトは、Azure DevTest Labs のラボで使用するカスタム ロールを作成します。
$rgName = <Specify your lab's resource group name>
$subscriptionId = <Specify your subscription ID>
$labName = <Specify your lab name>
‘List all the operations/actions for a resource provider.
Get-AzProviderOperation -OperationSearchString "Microsoft.DevTestLab/*"
‘List actions in a particular role.
(Get-AzRoleDefinition "DevTest Labs User").Actions
‘Create 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)
$user=Get-AzADUser -SearchString "SomeUser"
$scope = '/subscriptions/' + subscriptionId + '/resourceGroups/' + $rgName + '/providers/Microsoft.DevTestLab/labs/' + $labName + '/policySets/default/policies/AllowedVmSizesInLab'
New-AzRoleAssignment -ObjectId $user.ObjectId -RoleDefinitionName "Policy Contributor" -Scope $scope
このスクリプトでは以下のコマンドを使用します。
コマンド | メモ |
---|---|
Get-AzProviderOperation | Azure ロールベースのアクセス制御を使用してセキュリティで保護された Azure リソース プロバイダーの操作を取得します。 |
Get-AzRoleDefinition | 割り当て可能なすべての Azure ロールを一覧表示します。 |
New-AzRoleDefinition | カスタム ロールを作成します。 |
許可される仮想マシン サイズの設定
この PowerShell のサンプル スクリプトは、Azure Lab Services で許可される仮想マシンのサイズを設定します。
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 be added")]
[Array] $SizesToAdd
)
function Get-Lab
{
$lab = Find-AzResource -ResourceType 'Microsoft.DevTestLab/labs' -ResourceNameEquals $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' -ResourceName $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 sizes. It needs all their current sizes as well as any from our list that arent already there
$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
command | Notes |
---|---|
Get-AzResource | リソースを取得します。 |
Set-AzResource | リソースを変更します。 |
New-AzResource | リソースを作成します。 |
次のステップ
Azure PowerShell の詳細については、Azure PowerShell のドキュメントをご覧ください。
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示