다음을 통해 공유


Azure VM Image Builder를 사용하여 개발 상자 이미지 만들기

이 문서에서는 Azure VM Image Builder 템플릿을 사용하여 Azure Compute Gallery에서 사용자 지정된 VM 이미지를 만들고 전역적으로 배포하는 방법을 보여 줍니다. 그런 다음, 이미지를 사용하여 Microsoft Dev Box에서 개발 상자를 만들 수 있습니다.

표준화된 VM 이미지는 미리 정의된 보안, 구성 및 소프트웨어를 포함하여 일관된 개발 상자 배포를 보장하는 데 도움이 될 수 있습니다. 그러나 이미징 파이프라인을 수동으로 설정하는 것은 시간이 많이 걸리고 복잡하며 사용자 지정 VM(가상 머신) 이미지를 만드는 것은 어렵고 불안정할 수 있습니다.

Azure VM Image Builder는 개발 상자용 VM 이미지를 만들고 빌드하는 프로세스를 간소화하는 HashiCorp Packer를 기반으로 하는 관리되는 서비스입니다. 이 문서의 Image Builder 템플릿에는 Visual Studio Code 및 Chocolatey를 설치하는 사용자 지정 단계가 포함되어 있습니다.

VM Image Builder는 다음을 수행할 수 있습니다.

  • 수동 단계 또는 복잡한 도구 및 프로세스를 추상화하고 Azure 관련 요구 사항을 숨깁니다. 예를 들어, sysprep을(를) 실행하여 이미지를 일반화하지만 고급 사용자가 이를 재정의할 수 있도록 허용합니다.
  • 기존 이미지 빌드 파이프라인을 사용합니다. 파이프라인에서 VM Image Builder를 호출하거나 Azure Pipelines에서 Azure VM Image Builder 서비스 작업을 사용할 수 있습니다.
  • 다양한 원본에서 사용자 지정 데이터를 수집하므로 직접 수집할 필요가 없습니다.
  • Azure Compute Gallery와 통합하여 전역 배포, 복제, 버전 관리 및 크기 조정을 위한 이미지 관리 시스템을 만듭니다. 이미지를 다시 빌드하지 않고 가상 하드 디스크와 관리형 이미지로 배포할 수 있습니다.

중요합니다

Microsoft Dev Box는 신뢰할 수 있는 시작 보안 유형을 사용하는 이미지만 지원합니다.

필수 구성 요소

이 문서의 예제에서는 Azure PowerShell을 사용합니다. Azure CLI를 사용할 수도 있습니다.

카테고리 요구 사항
도구 및 사용 권한 소유자 또는 기여자 권한이 있는 Azure 리소스 그룹입니다.
Tools Azure PowerShell 6.0 이상이 설치되었습니다. 지침은 Windows에 Azure PowerShell 설치를 참조하세요.

도구 및 역할 설정

도구 및 역할을 설정하려면 다음을 수행합니다.

  1. 필요한 Azure PowerShell 모듈을 설치합니다.
  2. 두 번 이상 사용하는 정보에 대한 변수를 설정합니다.
  3. 필요한 Azure 리소스 공급자를 등록합니다.
  4. 리소스 그룹에 대한 사용자 ID를 만들고 이미지를 배포할 수 있는 역할을 할당합니다.

PowerShell 모듈 설치

다음 명령을 실행하여 필요한 PowerShell 모듈을 설치합니다.

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

신뢰할 수 없는 리포지토리에 대한 프롬프트에 Y 로 응답합니다.

변수 설정

두 번 이상 사용하는 정보를 저장할 변수를 만듭니다. 다음 코드를 실행하여 <resource-group>을/를 리소스 그룹 이름으로, <location>을/를 사용하려는 Azure 지역으로 교체합니다.

# Get existing context 
$currentAzContext = Get-AzContext

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

# Destination image resource group  
$imageResourceGroup="<resource-group>"

# Location
$location="<location>"

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

# Image template name  
$imageTemplateName="vscodeWinTemplate"  

Azure 리소스 공급자 등록

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

  • Microsoft.VirtualMachineImages
  • Microsoft.Compute
  • Microsoft.Network
  • Microsoft.Storage
  • Microsoft.KeyVault
  • Microsoft.ContainerInstance
  1. 다음 명령을 실행하여 공급자 등록을 확인합니다.

      Get-AzResourceProvider -ProviderNamespace "Microsoft.VirtualMachineImages", "Microsoft.Compute", "Microsoft.Network", "Microsoft.Storage", "Microsoft.KeyVault", "Microsoft.ContainerInstance" | Format-table -Property ProviderNamespace,RegistrationState
    
  2. 등록이 Registered을(를) 반환하지 않는 경우, Register-AzResourceProvider 명령을 실행하여 공급자를 등록합니다. 다음 예제에서는 리소스 공급자를 Microsoft.VirtualMachineImages 등록합니다.

      Register-AzResourceProvider -ProviderNamespace Microsoft.VirtualMachineImages
    

사용자 ID 만들기 및 할당

이미지를 배포할 수 있는 Azure 역할 정의를 만듭니다. 그런 다음 리소스 그룹에 대한 사용자 할당 ID를 만들고 사용자 ID에 역할을 할당합니다. VM Image Builder는 사용자 ID를 사용하여 Azure Compute 갤러리에 이미지를 저장합니다.

  1. 다음 코드를 실행하여 Azure 역할 정의 및 사용자 ID를 만듭니다.

    # Set up a unique role definition name
    $timeInt=$(get-date -UFormat "%s") 
    $imageRoleDefName="Azure Image Builder Image Def"+$timeInt 
    $identityName="aibIdentity"+$timeInt 
    
    # Create an identity 
    New-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName -Location $location
    
    $identityNameResourceId=$(Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).Id 
    $identityNamePrincipalId=$(Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).PrincipalId
    
  2. 다음 코드를 실행하여 이미지를 배포할 수 있는 Azure 역할 정의 템플릿을 다운로드하고, 매개 변수로 템플릿을 업데이트하고, 사용자 ID에 역할을 할당합니다.

    $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" 
    

Azure Compute 갤러리에서 VM Image Builder를 사용하려면 갤러리와 이미지 정의가 필요합니다. 다음 단계에서는 새 갤러리 및 이미지 정의를 만들고 VM Image Builder 템플릿을 사용자 지정합니다.

  1. 다음 명령을 실행하여 Windows 365 이미지에 필요한 신뢰할 수 있는 시작 보안 형식이 있는 새 갤러리 및 이미지 정의를 만듭니다.

    # Gallery name 
    $galleryName= "devboxGallery" 
    
    # Image definition name 
    $imageDefName ="vscodeImageDef" 
    
    # Second replication region 
    $replRegion2="eastus" 
    
    # Create the gallery 
    New-AzGallery -GalleryName $galleryName -ResourceGroupName $imageResourceGroup -Location $location 
    
    $SecurityType = @{Name='SecurityType';Value='TrustedLaunch'} 
    $features = @($SecurityType) 
    
    # Create the image definition
    New-AzGalleryImageDefinition -GalleryName $galleryName -ResourceGroupName $imageResourceGroup -Location $location -Name $imageDefName -OsState generalized -OsType Windows -Publisher 'myCompany' -Offer 'vscodebox' -Sku '1-0-0' -Feature $features -HyperVGeneration "V2" 
    
  2. VM Image Builder용 다음 Azure Resource Manager 템플릿을 복사하여 새 파일에 붙여넣습니다. c:\temp\mytemplate.js 같은 위치에 파일을 저장한 다음 파일을 닫습니다.

    템플릿은 적용된 원본 이미지 및 사용자 지정을 정의하고 Chocolatey 및 Visual Studio Code를 설치하며 이미지 배포 위치를 나타냅니다.

    {
       "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
       "contentVersion": "1.0.0.0",
       "parameters": {
         "imageTemplateName": {
          "type": "string"
         },
         "api-version": {
          "type": "string"
         },
         "svclocation": {
          "type": "string"
         }
       },
       "variables": {},
       "resources": [
         {
          "name": "[parameters('imageTemplateName')]",
          "type": "Microsoft.VirtualMachineImages/imageTemplates",
          "apiVersion": "[parameters('api-version')]",
          "location": "[parameters('svclocation')]",
          "dependsOn": [],
          "tags": {
            "imagebuilderTemplate": "win11multi",
            "userIdentity": "enabled"
          },
          "identity": {
            "type": "UserAssigned",
            "userAssignedIdentities": {
             "<imgBuilderId>": {}
            }
          },
          "properties": {
            "buildTimeoutInMinutes": 100,
            "vmProfile": {
             "vmSize": "Standard_DS2_v2",
             "osDiskSizeGB": 127
            },
          "source": {
             "type": "PlatformImage",
             "publisher": "MicrosoftWindowsDesktop",
             "offer": "Windows-11",
             "sku": "win11-21h2-ent",
             "version": "latest"
          },
            "customize": [
             {
                "type": "PowerShell",
                "name": "Install Choco and VS Code",
                "inline": [
                   "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))",
                   "choco install -y vscode"
                ]
             }
            ],
             "distribute": 
             [
                {   
                   "type": "SharedImage",
                   "galleryImageId": "/subscriptions/<subscriptionID>/resourceGroups/<rgName>/providers/Microsoft.Compute/galleries/<sharedImageGalName>/images/<imageDefName>",
                   "runOutputName": "<runOutputName>",
                   "artifactTags": {
                      "source": "azureVmImageBuilder",
                      "baseosimg": "win11multi"
                   },
                   "replicationRegions": [
                     "<region1>",
                     "<region2>"
                   ]
                }
             ]
          }
         }
       ]
      }
    
  3. 다음 코드를 실행하여 원하는 설정으로 새 템플릿을 구성하고, 템플릿 파일 위치와 이름으로 바꿉니다.<template-location>

    $templateFilePath = "<template-location>"
    
    (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>',$galleryName| 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 
    

이미지 빌드 및 보기

사용자 지정된 템플릿을 VM Image Builder 서비스에 제출하고 이미지를 빌드합니다.

  1. 다음 명령을 실행하여 템플릿을 서비스에 제출합니다. 이 명령은 스크립트와 같은 종속 아티팩트를 다운로드하고 접두사 IT_로 지정된 준비 리소스 그룹에 저장합니다.

    New-AzResourceGroupDeployment  -ResourceGroupName $imageResourceGroup  -TemplateFile $templateFilePath  -Api-Version "2020-02-14"  -imageTemplateName $imageTemplateName  -svclocation $location 
    
  2. 템플릿에서 작업을 호출하여 Run 이미지를 빌드합니다. 확인 프롬프트에서 Y 를 입력합니다 Yes.

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

중요합니다

이미지를 만들고 두 지역에 복제하는 데 다소 시간이 걸릴 수 있습니다. PowerShell과 Azure Portal 간에 다른 진행률 보고가 표시될 수 있습니다. 이미지에서 개발 상자 정의를 만들기 시작하기 전에 프로세스가 완료될 때까지 기다립니다.

이미지에 대한 정보 가져오기

다음 명령을 실행하여 실행 상태 및 프로비전 상태를 포함하여 새로 빌드된 이미지에 대한 정보를 가져옵니다.

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

샘플 출력:

Name              LastRunStatusRunState LastRunStatusMessage ProvisioningState
----              --------------------- -------------------- -----------------
vscodeWinTemplate Running                                    Succeeded

Azure Portal에서 이미지의 프로비저닝 상태를 확인할 수도 있습니다. 갤러리로 이동하여 이미지 정의를 봅니다.

사용자 지정된 이미지 버전의 프로비저닝 상태를 보여 주는 스크린샷.

사용자 지정 이미지가 갤러리에 저장되면 Microsoft Dev Box 개발자 센터에서 해당 이미지를 사용하도록 갤러리를 구성할 수 있습니다. 자세한 내용은 Microsoft Dev Box용 Azure Compute Gallery 구성을 참조하세요.

개발자 센터에서 갤러리 이미지를 사용할 수 있게 만든 후에는 사용자 지정 이미지를 개발 상자 프로젝트에 연결하고 이를 사용하여 개발 상자를 만들 수 있습니다. 자세한 내용은 빠른 시작: Microsoft Dev Box 구성을 참조하시기 바랍니다.