다음을 통해 공유


Windows 이미지를 만들어 Azure Compute Gallery에 배포합니다.

적용 대상: ✔️ Windows VM

이 문서에서는 Azure VM Image Builder 및 Azure PowerShell을 사용하여 Azure Compute Gallery(이전의 공유 이미지 갤러리)에서 이미지 버전을 만든 다음, 이미지를 전역적으로 배포하는 방법에 대해 알아봅니다. 이 작업은 Azure CLI를 사용하여 수행할 수도 있습니다.

이미지를 구성하기 위해 이 문서에서는 armTemplateWinSIG.json에서 찾을 수 있는 JSON 템플릿을 사용합니다. 템플릿의 로컬 버전을 다운로드하고 편집하므로 로컬 PowerShell 세션도 사용합니다.

Azure Compute Gallery에 이미지를 배포하기 위해 이 템플릿에서는 sharedImage를 템플릿의 distribute 섹션 값으로 사용합니다.

VM Image Builder는 자동으로 Sysprep을 실행하여 이미지를 일반화합니다. 이 명령은 제네릭 Sysprep 명령이며, 필요한 경우 재정의할 수 있습니다.

사용자 지정을 계층화하는 횟수를 알고 있어야 합니다. Sysprep 명령은 단일 Windows 이미지에서 제한된 횟수만큼 실행할 수 있습니다. Sysprep 제한에 도달하면 Windows 이미지를 다시 만들어야 합니다. 자세한 내용은 Sysprep을 실행할 수 있는 횟수 제한을 참조하세요.

공급자 등록

VM Image Builder를 사용하려면 공급자를 등록해야 합니다.

  1. 공급자 등록을 확인합니다. 각 항목에서 등록됨을 반환하는지 확인합니다.

    Get-AzResourceProvider -ProviderNamespace Microsoft.VirtualMachineImages | Format-table -Property ResourceTypes,RegistrationState
    Get-AzResourceProvider -ProviderNamespace Microsoft.Storage | Format-table -Property ResourceTypes,RegistrationState 
    Get-AzResourceProvider -ProviderNamespace Microsoft.Compute | Format-table -Property ResourceTypes,RegistrationState
    Get-AzResourceProvider -ProviderNamespace Microsoft.KeyVault | Format-table -Property ResourceTypes,RegistrationState
    Get-AzResourceProvider -ProviderNamespace Microsoft.Network | Format-table -Property ResourceTypes,RegistrationState
    Get-AzResourceProvider -ProviderNamespace Microsoft.ContainerInstance | Format-table -Property ResourceTypes,RegistrationState
    
  2. 등록됨이 반환되지 않으면 다음 명령을 실행하여 공급자를 등록합니다.

    Register-AzResourceProvider -ProviderNamespace Microsoft.VirtualMachineImages
    Register-AzResourceProvider -ProviderNamespace Microsoft.Storage
    Register-AzResourceProvider -ProviderNamespace Microsoft.Compute
    Register-AzResourceProvider -ProviderNamespace Microsoft.KeyVault
    Register-AzResourceProvider -ProviderNamespace Microsoft.ContainerInstance
    
  3. PowerShell 모듈을 설치합니다.

    'Az.ImageBuilder', 'Az.ManagedServiceIdentity' | ForEach-Object {Install-Module -Name $_ -AllowPrerelease}
    

변수 만들기

일부 정보를 반복적으로 사용하게 되므로 해당 정보를 저장할 변수를 만듭니다.

usernamevmpassword와 같은 변수의 값을 사용자 고유의 정보로 바꿉니다.

# Get existing context
$currentAzContext = Get-AzContext

# Get your current subscription ID. 
$subscriptionID=$currentAzContext.Subscription.Id

# Destination image resource group
$imageResourceGroup="aibwinsig"

# Location
$location="westus"

# Image distribution metadata reference name
$runOutputName="aibCustWinManImg02ro"

# Image template name
$imageTemplateName="helloImageTemplateWin02ps"

# Distribution properties object name (runOutput).
# This gives you the properties of the managed image on completion.
$runOutputName="winclientR01"

# Create a resource group for the VM Image Builder template and Azure Compute Gallery
New-AzResourceGroup `
   -Name $imageResourceGroup `
   -Location $location

사용자 할당 ID 만들기 및 리소스 그룹에 대한 사용 권한 설정

VM Image Builder는 제공된 사용자 ID를 사용하여 이미지를 Azure Compute Gallery에 삽입합니다. 이 예에서는 이미지 배포에 대한 특정 작업을 사용하여 Azure 역할 정의를 만듭니다. 그런 다음, 역할 정의가 사용자 ID에 할당됩니다.

# setup role def names, these need to be unique
$timeInt=$(get-date -UFormat "%s")
$imageRoleDefName="Azure Image Builder Image Def"+$timeInt
$identityName="aibIdentity"+$timeInt

## Add an Azure PowerShell module to support AzUserAssignedIdentity
Install-Module -Name Az.ManagedServiceIdentity

# Create an identity
New-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName

$identityNameResourceId=$(Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).Id
$identityNamePrincipalId=$(Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).PrincipalId

이미지를 배포하도록 ID에 필요한 권한 할당

이 명령을 사용하여 Azure 역할 정의 템플릿을 다운로드한 다음, 이전에 지정된 매개 변수로 업데이트합니다.

$aibRoleImageCreationUrl="https://raw.githubusercontent.com/azure/azvmimagebuilder/master/solutions/12_Creating_AIB_Security_Roles/aibRoleImageCreation.json"
$aibRoleImageCreationPath = "aibRoleImageCreation.json"

# Download the configuration
Invoke-WebRequest -Uri $aibRoleImageCreationUrl -OutFile $aibRoleImageCreationPath -UseBasicParsing

((Get-Content -path $aibRoleImageCreationPath -Raw) -replace '<subscriptionID>',$subscriptionID) | Set-Content -Path $aibRoleImageCreationPath
((Get-Content -path $aibRoleImageCreationPath -Raw) -replace '<rgName>', $imageResourceGroup) | Set-Content -Path $aibRoleImageCreationPath
((Get-Content -path $aibRoleImageCreationPath -Raw) -replace 'Azure Image Builder Service Image Creation Role', $imageRoleDefName) | Set-Content -Path $aibRoleImageCreationPath

# Create a role definition
New-AzRoleDefinition -InputFile  ./aibRoleImageCreation.json

# Grant the role definition to the VM Image Builder service principal
New-AzRoleAssignment -ObjectId $identityNamePrincipalId -RoleDefinitionName $imageRoleDefName -Scope "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup"

참고 항목

“New-AzRoleDefinition: 역할 정의 한도가 초과되었습니다. 더 이상 역할 정의를 만들 수 없습니다.” 오류가 표시되면 Azure RBAC(역할 기반 액세스 제어) 문제 해결을 참조하세요.

Azure Compute Gallery에서 VM Image Builder를 사용하려면 기존 갤러리 및 이미지 정의가 있어야 합니다. VM Image Builder는 갤러리와 이미지 정의를 자동으로 만들지 않습니다.

사용할 갤러리 및 이미지 정의가 아직 없는 경우 만들어야 합니다.

# Gallery name
$sigGalleryName= "myIBSIG"

# Image definition name
$imageDefName ="winSvrimage"

# Additional replication region
$replRegion2="eastus"

# Create the gallery
New-AzGallery `
   -GalleryName $sigGalleryName `
   -ResourceGroupName $imageResourceGroup  `
   -Location $location

# Create the image definition
New-AzGalleryImageDefinition `
   -GalleryName $sigGalleryName `
   -ResourceGroupName $imageResourceGroup `
   -Location $location `
   -Name $imageDefName `
   -OsState generalized `
   -OsType Windows `
   -Publisher 'myCompany' `
   -Offer 'WindowsServer' `
   -Sku 'WinSrv2019'

템플릿을 다운로드하고 구성합니다.

JSON 템플릿을 다운로드하고 변수로 구성합니다.


$templateFilePath = "armTemplateWinSIG.json"

Invoke-WebRequest `
   -Uri "https://raw.githubusercontent.com/azure/azvmimagebuilder/master/quickquickstarts/1_Creating_a_Custom_Win_Shared_Image_Gallery_Image/armTemplateWinSIG.json" `
   -OutFile $templateFilePath `
   -UseBasicParsing

(Get-Content -path $templateFilePath -Raw ) `
   -replace '<subscriptionID>',$subscriptionID | Set-Content -Path $templateFilePath
(Get-Content -path $templateFilePath -Raw ) `
   -replace '<rgName>',$imageResourceGroup | Set-Content -Path $templateFilePath
(Get-Content -path $templateFilePath -Raw ) `
   -replace '<runOutputName>',$runOutputName | Set-Content -Path $templateFilePath
(Get-Content -path $templateFilePath -Raw ) `
   -replace '<imageDefName>',$imageDefName | Set-Content -Path $templateFilePath
(Get-Content -path $templateFilePath -Raw ) `
   -replace '<sharedImageGalName>',$sigGalleryName | Set-Content -Path $templateFilePath
(Get-Content -path $templateFilePath -Raw ) `
   -replace '<region1>',$location | Set-Content -Path $templateFilePath
(Get-Content -path $templateFilePath -Raw ) `
   -replace '<region2>',$replRegion2 | Set-Content -Path $templateFilePath
((Get-Content -path $templateFilePath -Raw) -replace '<imgBuilderId>',$identityNameResourceId) | Set-Content -Path $templateFilePath

이미지 버전 만들기

템플릿을 서비스에 제출해야 합니다. 다음 명령은 스크립트와 같은 모든 종속 아티팩트를 다운로드하여 IT_ 접두사가 붙은 준비 리소스 그룹에 저장합니다.

New-AzResourceGroupDeployment `
   -ResourceGroupName $imageResourceGroup `
   -TemplateFile $templateFilePath `
   -ApiVersion "2022-02-14" `
   -imageTemplateName $imageTemplateName `
   -svclocation $location

이미지를 빌드하려면 템플릿에서 'Run'을 호출합니다.

Invoke-AzResourceAction `
   -ResourceName $imageTemplateName `
   -ResourceGroupName $imageResourceGroup `
   -ResourceType Microsoft.VirtualMachineImages/imageTemplates `
   -ApiVersion "2022-02-14" `
   -Action Run

이미지를 만들고 두 영역에 복제하는 데 몇 분 정도 걸릴 수 있습니다. 이 부분이 완료될 때까지 기다린 후에 VM 만들기를 시작합니다.

Get-AzImageBuilderTemplate -ImageTemplateName $imageTemplateName -ResourceGroupName $imageResourceGroup |
  Select-Object -Property Name, LastRunStatusRunState, LastRunStatusMessage, ProvisioningState

VM 만들기

VM Image Builder에서 만든 이미지 버전에서 VM을 만듭니다.

  1. 만든 이미지 버전을 가져옵니다.

    $imageVersion = Get-AzGalleryImageVersion `
    -ResourceGroupName $imageResourceGroup `
    -GalleryName $sigGalleryName `
    -GalleryImageDefinitionName $imageDefName
    $imageVersionId = $imageVersion.Id
    
  2. 이미지가 복제된 두 번째 지역에서 VM을 만듭니다.

    $vmResourceGroup = "myResourceGroup"
    $vmName = "myVMfromImage"
    
    # Create user object
    $cred = Get-Credential -Message "Enter a username and password for the virtual machine."
    
    # Create a resource group
    New-AzResourceGroup -Name $vmResourceGroup -Location $replRegion2
    
    # Network pieces
    $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24
    $vnet = New-AzVirtualNetwork -ResourceGroupName $vmResourceGroup -Location $replRegion2 `
    -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig
    $pip = New-AzPublicIpAddress -ResourceGroupName $vmResourceGroup -Location $replRegion2 `
    -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
    $nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP  -Protocol Tcp `
    -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * `
    -DestinationPortRange 3389 -Access Deny
    $nsg = New-AzNetworkSecurityGroup -ResourceGroupName $vmResourceGroup -Location $replRegion2 `
    -Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP
    $nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $vmResourceGroup -Location $replRegion2 `
    -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id
    
    # Create a virtual machine configuration using $imageVersion.Id to specify the image
    $vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1_v2 | `
    Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
    Set-AzVMSourceImage -Id $imageVersion.Id | `
    Add-AzVMNetworkInterface -Id $nic.Id
    
    # Create a virtual machine
    New-AzVM -ResourceGroupName $vmResourceGroup -Location $replRegion2 -VM $vmConfig
    

사용자 지정 확인

VM을 만들 때 설정한 사용자 이름 및 암호를 사용하여 VM에 대한 원격 데스크톱 연결을 만듭니다. VM에서 명령 프롬프트 창을 열고, 다음 명령을 실행합니다.

dir c:\

이미지를 사용자 지정하는 동안 만들어진 buildActions라는 디렉터리가 표시됩니다.

리소스 정리

참고 항목

이미지 버전을 다시 사용자 지정하여 동일한 이미지의 새 버전을 만들려면 여기에 설명된 단계를 건너뛰고VM Image Builder를 사용하여 다른 이미지 버전 만들기로 이동합니다.

이 문서의 프로세스에 따라 만든 리소스가 더 이상 필요하지 않은 경우 삭제할 수 있습니다.

다음 프로세스에서는 만든 이미지와 다른 모든 리소스 파일을 모두 삭제합니다. 리소스를 삭제하기 전에 이 배포를 완료했는지 확인합니다.

먼저 리소스 그룹 템플릿을 삭제합니다. 그렇지 않으면 VM Image Builder에서 사용하는 준비 리소스 그룹(IT_)이 정리되지 않습니다.

  1. 이미지 템플릿의 ResourceID를 가져옵니다.

    $resTemplateId = Get-AzResource -ResourceName $imageTemplateName -ResourceGroupName $imageResourceGroup -ResourceType Microsoft.VirtualMachineImages/imageTemplates -ApiVersion "2022-02-14"
    
  2. 이미지 템플릿을 삭제합니다.

    Remove-AzResource -ResourceId $resTemplateId.ResourceId -Force
    
  3. 역할 할당을 삭제합니다.

    Remove-AzRoleAssignment -ObjectId $identityNamePrincipalId -RoleDefinitionName $imageRoleDefName -Scope "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup"
    
  4. 정의를 제거합니다.

    Remove-AzRoleDefinition -Name "$identityNamePrincipalId" -Force -Scope "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup"
    
  5. ID를 삭제합니다.

    Remove-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName -Force
    
  6. 해당 리소스 그룹을 삭제합니다.

    Remove-AzResourceGroup $imageResourceGroup -Force
    

다음 단계

이 문서에서 만든 이미지 버전을 업데이트하려면 VM Image Builder를 사용하여 다른 이미지 버전 만들기를 참조하세요.