Repository: YannickRe/azuredevops-buildagents Branch: main Commit: 4979f673ebf2 Files: 13 Total size: 48.4 KB Directory structure: gitextract_4lk35mmf/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── buildagent-generation-template.yml ├── buildagent-generation.yml ├── managedimage-cleanup-template.yml ├── managedimage-cleanup.yml └── scripts/ ├── cleanup-gallery-temporaryimage.ps1 ├── cleanup-gallery-vmimageversion.ps1 └── get-latestgithubrelease.ps1 ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: YannickRe ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore !ConsoleApp2.exe !ConsoleApp2.dll # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # .NET Core project.lock.json project.fragment.lock.json artifacts/ **/Properties/launchSettings.json *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Typescript v1 declaration files typings/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # Ignore files generated by packer InstalledSoftware.md # Desktop Service Store .DS_Store # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # next.js build output .next # nuxt.js build output .nuxt # gatsby files .cache/ public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # visual studio code launch configuration launch.json ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at reekmans.yannick@gmail.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Guidance If you'd like to contribute to this repository, please read the following guidelines. We want to make sure that everyone gets the most out of their efforts. ## Code of Conduct This project has adopted the [Contributor Covenant Code of Conduct](https://github.com/YannickRe/ContosoUniversitySPA-TeamsTab/blob/main/CODE_OF_CONDUCT.md). For more information, see the [Contributor Covenant](https://www.contributor-covenant.org/). ## Question or Problem? Please use proper issues for bug reports, documentation fix, feature requests and general feedback. This way we can more easily track actual bugs from the code and help get things fixed. ## Typos, Issues, Bugs and contributions Please follow these recommendations. * Always fork repository to your own account for applying modifications * Do not combine multiple changes to one PR * If you are submitting typo or documentation fix, you can combine modifications to single PR where suitable ## Submitting changes as pull requests Here's a high level process for PR's: 1. Fork the main repository to your GitHub account 2. Include your changes to your branch 3. Commit your changes using descriptive commit message 4. Create a pull request in your own fork and target 'main' branch 5. Fill up the provided PR template with the requested details > note. Delete the feature specific branch only AFTER your PR has been processed. ================================================ FILE: LICENSE.md ================================================ MIT License Copyright (c) 2022 Yannick Reekmans Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # DevOps Build Agents This project generates self-hosted build agents based on the [official Microsoft-hosted build agents images](https://github.com/actions/runner-images), in an Azure DevOps Pipeline. The resulting Azure Managed Image will be add to an Azure Compute Gallery so that it can be used by a Virtual Machine Scale Set. This Virtual Machine Scale Set is managed by Azure DevOps as a [Azure Virtual Machine Scale Set Agent](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=azure-devops&tabs=browser&WT.mc_id=M365-MVP-5003400#azure-virtual-machine-scale-set-agents). Currently supports Windows Server 2022, Windows Server 2025, Ubuntu 2204 and Ubuntu 2404 images. ## Available pipelines - __[buildagent-generation.yml](./buildagent-generation.yml)__ - Checkout the latest `main` branch from [actions/runner-images](https://github.com/actions/runner-images) - Build the VM with Packer and add to Azure Compute Gallery - Clean up remaining temporary Azure resources - __[managedimage-cleanup.yml](./managedimage-cleanup.yml)__ - Remove old Gallery image versions ## Preparation The pipeline requires Azure resources for the temporary building of the VM image, Azure resources for running the resulting Agent Pool, and some configuration in Azure DevOps. ## Azure Compute Gallery Create (if you don´t have one) an Azure Compute Gallery in your Azure subscription, and create the following VM Image Definitions: - ubuntu2204-agentpool-full (OS: Linux) - ubuntu2404-agentpool-full (OS: Linux) - windows2022-agentpool-full (OS: Windows) - windows2025-agentpool-full (OS: Windows) ### Azure Resources for Packer execution The Azure resources are created with the [Azure PowerShell Module](https://docs.microsoft.com/en-us/powershell/azure/new-azureps-module-az?WT.mc_id=M365-MVP-5003400) 1. Connect to Azure ``` Connect-AzAccount -UseDeviceAuthentication ``` 2. Create resource group that will store the Packer temporary resources ``` New-AzResourceGroup -Name "DevOps-PackerResources" -Location "West Europe" ``` 3. Create Azure AD Service Principal, output client secret and client id ``` $sp = New-AzADServicePrincipal -DisplayName "DevOps-Packer" $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sp.Secret) $plainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $plainPassword $sp.ApplicationId ``` 4. Make the Service Principal a Contributor on the subscription ``` New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ApplicationId ``` ### Azure Virtual Machine Scale Set To use an Azure Virtual Machine Scale Set as an Azure DevOps Scale Set Agent it has to adhere to a certain set of requirements. [The documentation](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/scale-set-agents?view=azure-devops&WT.mc_id=M365-MVP-5003400#create-the-scale-set) contains all the required information, but at the time of writing the following things were important: - __VM size__: at least *Standard_D4s_v4* - __Overprovisioning__: *no*, Azure DevOps will decide whether or not new VM's (and thus Agents) need to be provisioned - __Upgrade policy__: *manual* ### Azure DevOps Scale Set Agent The Virtual Machine Scale Set from the previous step needs to be registered as an Agent Pool in Azure DevOps. [The instructions are very clear](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/scale-set-agents?view=azure-devops&WT.mc_id=M365-MVP-5003400#create-the-scale-set-agent-pool): - Add an Agent Pool of type "Azure virtual machine scale set" - Use a service connection to select the scale set from the previous step (only supported via `Secret` authentication, not `Certificate` or `Managed Identity` authentication) - Give the agent pool a name - Enter the required configuration values ### Azure DevOps Variable Group Create a Variable Group in the Azure DevOps project running the pipeline, and give it a name. It needs to contain the following variables with their appropriate value: | Variable | Description | |---|---| | DOBA-LOCATION | Azure location where Packer will create the temporary resources | | DOBA-RESOURCE-GROUP | Resource group that will be used by Packer to put the resulting Azure Managed Image. | | DOBA-SUBSCRIPTION-ID | Subscription ID of the Azure Subscription that is used to host the temporary resources. | | DOBA-TENANT-ID | Tenant ID of the Azure tenant that has the Azure Resource Groups and Subscription. | | DOBA-CLIENT-ID | Id of the Azure AD application that has appropriate permissions on the Subscription to create temporary resources and finalizing the Scale Set configuration. See output from scripts above. | | DOBA-CLIENT-SECRET | Application secret to be used fot the connection in combination with the Client Id. See output from scripts above. | | DOBA-GALLERY-NAME | Name of the Azure Compute Gallery to store images for Agent Pool VM Scale Sets. | | DOBA-GALLERY-RESOURCE-GROUP | Name of the resource group containing the Azure Compute Gallery. | | DOBA-GALLERY-STORAGE-ACCOUNT-TYPE | Storage account type used to storage Gallery Image Versions. Accepted values: Standard_LRS, Premium_LRS, Standard_ZRS | If you want to use your own existing Virtual Network for the temporary VM, add the following variables: | Variable | Description | |---|---| | DOBA-VNET-NAME | Name of the existing VNet to use for the VM created by Packer | | DOBA-VNET-RESOURCE-GROUP | Name of the resource group containing the existing VNet to use for the VM created by Packer | | DOBA-VNET-SUBNET | Name of the existing subnet to use for the VM created by Packer | ## Pipeline runtime parameters ### Build Agent Generation ![Runtime parameters for Build Agent Generation](./assets/BuildAgentGeneration-Queue.png) - __Build Agent Image__: which image to build - __runner-images Version__: which source code of the runner-images to build, choice between `alpha` (latest main branch), `prerelease` (latest prerelease version), and `release` (latest stable release) - __Variable Group__: name of the Variable Group containing the variables necessary for execution - __Agent Pool__: the Agent Pool to use for running the pipeline ### Managed Image Cleanup ![Runtime parameters for Managed Images Cleanup](./assets/ManagedImageCleanup-Queue.png) - __Variable Group__: name of the Variable Group containing the variables necessary for execution ## How to use ### Templated version Both YML file are designed in a way that allows anyone to simply include them using the "template" instruction. You will need to create a service connection under your Azure DevOps instance before moving with the configuration. Assuming the service connection has been setup, under your own repository, within an Azure Pipeline YML file, include the following resource: ``` resources: repositories: - repository: azuredevops-buildagents type: github name: YannickRe/azuredevops-buildagents endpoint: ref: refs/heads/main ``` This will tell your pipeline that you're dependent upon this repository. Then, the following instructions can be freely customized to your needs. If you need some stages to be ran before the steps within this repository, then include them inside your pipeline, then call the desired template from the repository. Calling a template is easy as doing the following: ``` stages: - stage: InsertAnyCustomStageHere displayName: 'My Stage' [...] - stage: BuildImage displayName: Build Image pool: name: jobs: - template: buildagent-generation-template.yml@azuredevops-buildagents parameters: image_type: runner_images_version: variable_group: agent_pool: repository_base_path: ``` ### Template parameters When calling a template, you must provide certain parameters. For reference, please open the file which interests you: - __[buildagent-generation.yml](./buildagent-generation.yml)__ - __[managedimage-cleanup.yml](./managedimage-cleanup.yml)__ There is one important element you must be aware of: - repository_base_path - This variable dictates how the agent should resolve the assets within this repository. When used, two things will happen: - First, it will clone the repository resource specified within your YML file, which represents _this_ repository - It will also use it to properly resolve the path where this repository resides on your pipeline agent - When a remote template is referenced within an Azure Pipeline YML file, it doesn't clone the repository. Providing this parameter will make sure these templates understands they need to clone it before being able to run any of the scripts. Optional parameter: - depends_on - You can force the jobs within this repository to depend upon your own set of tasks. To use it, simply provide the name of the job which the next job within the template should depend on. The rest is quite self explanatory. Use the other parameters to provide the remaining required details for building / cleaning the images. ## Good to know ### Agent Pool Usage See documentation for [YAML-based pipelines](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/pools-queues?view=azure-devops&tabs=yaml%2cbrowser&WT.mc_id=M365-MVP-5003400#choosing-a-pool-and-agent-in-your-pipeline) and [Classic pipelines](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/pools-queues?view=azure-devops&tabs=classic%2cbrowser&WT.mc_id=M365-MVP-5003400#choosing-a-pool-and-agent-in-your-pipeline) ### Azure CLI access denied error on Windows Host Pool Please make sure to disable the "Configure VMs to run interactive tests" in your Windows Agent pool setting, otherwise the Azure CLI will generate access denied errors when running a pipeline. ## Version notes ### 5.0.0 - breaking change * Removed support for directly updating a VMSS with a new image. This version only supports Azure Compute Gallery. * Switched to packer native support for updating an Azure Compute Gallery with a new version of an image. * Removed unused variables. * Renamed variables with main goal to avoid overlap with runner-images environment variable declaration, using `DOBA` as a prefix (stands for **D**ev**O**ps **B**uild **A**gents). This also solves #76 by switching from `_` to `-` * Rename `AZURE_LOCATION` to `DOBA-LOCATION` * Rename `AZURE_RESOURCE_GROUP` to `DOBA-RESOURCE-GROUP` * Rename `AZURE_SUBSCRIPTION` to `DOBA-SUBSCRIPTION-ID` * Rename `AZURE_TENANT` to `DOBA-TENANT-ID` * Rename `CLIENT_ID` to `DOBA-CLIENT-ID` * Rename `CLIENT_SECRET` to `DOBA-CLIENT-SECRET` * Rename `SHARED_GALLERY_NAME` to `DOBA-GALLERY-NAME` * Rename `SHARED_GALLERY_RESOURCE_GROUP` to `DOBA-GALLERY-RESOURCE-GROUP` * Rename `SHARED_GALLERY_STORAGE_ACCOUNT_TYPE` to `DOBA-GALLERY-STORAGE-ACCOUNT-TYPE` * Remove `AZURE_AGENTS_RESOURCE_GROUP` * Remove `RUN_VALIDATION_FLAG` * Remove `VMSS_Windows2022` * Remove `VMSS_Windows2025` * Remove `VMSS_Ubuntu2204` * Remove `VMSS_Ubuntu2404` * If you use your own existing Virtual Network for creating the temporary VM, you have to rename those variables too. If you don't use this (current value is set to `$null`), you can now remove these variables. * Rename `BUILD_AGENT_VNET_NAME` to `DOBA-VNET-NAME` * Rename `BUILD_AGENT_VNET_RESOURCE_GROUP` to `DOBA-VNET-RESOURCE-GROUP` * Rename `BUILD_AGENT_SUBNET_NAME` to `DOBA-VNET-SUBNET` ### 4.0.0 * Fixed image generation after breaking changes from Microsoft * This is the last version (normally) to support Managed Images directly on a VMSS. We will move towards the native support for Azure Compute Gallery updating that exists in packer and the source repository. ### 3.0.0 * Rename all `GALLERY_*` variables to be `SHARED_GALLERY_*` to not conflict with new features coming in the templates by Microsoft. * Removed support for Ubuntu 20.04 and Windows Server 2019 * Added support for Windows Server 2025 ================================================ FILE: buildagent-generation-template.yml ================================================ parameters: - name: image_type displayName: Build Agent Image type: string default: windows2022 values: - windows2022 - windows2025 - ubuntu2204 - ubuntu2404 - name: agent_pool displayName: Agent Pool type: object default: name: 'ci-agent-pool' - name: variable_group_name displayName: Variable Group type: string default: 'Image Generation Variables' - name: runner_images_version displayName: Runner-Images Version type: string default: alpha values: - alpha - prerelease - release - name: depends_on displayName: First Stage Depends On type: object default: ' ' - name: repository_base_path displayName: Scripts Path type: string default: . stages: - stage: buildagent_template_vm_${{ parameters.image_type }} displayName: 'Build Agent Template VM (${{ parameters.image_type }})' ${{ if ne(parameters.depends_on, ' ') }}: dependsOn: ${{ parameters.depends_on }} jobs: - job: generate_image displayName: Image Generation (${{ parameters.image_type }}) timeoutInMinutes: '600' cancelTimeoutInMinutes: '30' variables: - group: ${{ parameters.variable_group_name }} pool: name: ${{ parameters.agent_pool }} steps: - checkout: self - ${{ if ne(parameters.repository_base_path, '.') }}: - checkout: ${{ parameters.repository_base_path }} - task: PowerShell@2 name: setVars displayName: 'Set image template variables' inputs: targetType: 'inline' script: | $runner_images_version = '${{ parameters.runner_images_version }}' $repository_base_path = '${{ parameters.repository_base_path }}' $image_type = '${{ parameters.image_type }}' switch ($image_type) { 'windows2022' { $os = "windows" $image_os = "win22" $image_readme_name = "Windows2022-Readme.md" $build_template_name = "build.windows-2022.pkr.hcl" } 'windows2025' { $os = "windows" $image_os = "win25" $image_readme_name = "Windows2025-Readme.md" $build_template_name = "build.windows-2025.pkr.hcl" } 'ubuntu2204' { $os = "ubuntu" $image_os = "ubuntu22" $image_readme_name = "Ubuntu2204-Readme.md" $build_template_name = "build.ubuntu-22_04.pkr.hcl" } 'ubuntu2404' { $os = "ubuntu" $image_os = "ubuntu24" $image_readme_name = "Ubuntu2404-Readme.md" $build_template_name = "build.ubuntu-24_04.pkr.hcl" } } $template_path = Join-Path (Join-Path (Join-Path "runner-images" "images") $os) "templates" $image_name = "$image_type-$(Build.BuildId)" $temp_rg_name = "packer-temp-$image_name" $gallery_image_name = "$image_type-agentpool-full" $gallery_image_version = "$((Get-Date).ToString("yyyyMMdd")).$(Build.BuildId).0" Write-Host "##vso[task.setvariable variable=repository_base_path]$repository_base_path" Write-Host "##vso[task.setvariable variable=runner_images_version]$runner_images_version" Write-Host "##vso[task.setvariable variable=image_type]$image_type" Write-Host "##vso[task.setvariable variable=image_os]$image_os" Write-Host "##vso[task.setvariable variable=image_readme_name]$image_readme_name" Write-Host "##vso[task.setvariable variable=build_template_name]$build_template_name" Write-Host "##vso[task.setvariable variable=template_path]$template_path" Write-Host "##vso[task.setvariable variable=image_name]$image_name" Write-Host "##vso[task.setvariable variable=temp_rg_name]$temp_rg_name" Write-Host "##vso[task.setvariable variable=gallery_image_name]$gallery_image_name" Write-Host "##vso[task.setvariable variable=gallery_image_version]$gallery_image_version" $client_id = "$(DOBA-CLIENT-ID)" $client_secret = "$(DOBA-CLIENT-SECRET)" $location = "$(DOBA-LOCATION)" $tenant_id = "$(DOBA-TENANT-ID)" $subscription_id = "$(DOBA-SUBSCRIPTION-ID)" $image_rg_name = "$(DOBA-RESOURCE-GROUP)" $gallery_name = "$(DOBA-GALLERY-NAME)" $gallery_rg_name = "$(DOBA-GALLERY-RESOURCE-GROUP)" $gallery_storage_account_type = "$(DOBA-GALLERY-STORAGE-ACCOUNT-TYPE)" try { $vnet_name = "$(DOBA-VNET-NAME)" } catch { $vnet_name = $null } if ($vnet_name -eq '$(DOBA-VNET-NAME)') { $vnet_name = $null } try { $vnet_rg = "$(DOBA-VNET-RESOURCE-GROUP)" } catch { $vnet_rg = $null } if ($vnet_rg -eq '$(DOBA-VNET-RESOURCE-GROUP)') { $vnet_rg = $null } try { $vnet_subnet = "$(DOBA-VNET-SUBNET)" } catch { $vnet_subnet = $null } if ($vnet_subnet -eq '$(DOBA-VNET-SUBNET)') { $vnet_subnet = $null } Write-Host "##vso[task.setvariable variable=client_id]$client_id" Write-Host "##vso[task.setvariable variable=client_secret;isSecret=true]$client_secret" Write-Host "##vso[task.setvariable variable=location]$location" Write-Host "##vso[task.setvariable variable=tenant_id]$tenant_id" Write-Host "##vso[task.setvariable variable=subscription_id]$subscription_id" Write-Host "##vso[task.setvariable variable=image_rg_name]$image_rg_name" Write-Host "##vso[task.setvariable variable=gallery_name]$gallery_name" Write-Host "##vso[task.setvariable variable=gallery_rg_name]$gallery_rg_name" Write-Host "##vso[task.setvariable variable=gallery_storage_account_type]$gallery_storage_account_type" Write-Host "##vso[task.setvariable variable=vnet_name]$vnet_name" Write-Host "##vso[task.setvariable variable=vnet_rg]$vnet_rg" Write-Host "##vso[task.setvariable variable=vnet_subnet]$vnet_subnet" - task: PowerShell@2 name: gitCheckout displayName: 'Checkout the GitHub repository' inputs: targetType: 'inline' script: | $github_owner = 'actions' $repo_name = 'runner-images' if (Test-Path ".\$repo_name\") { Remove-Item -Recurse -Force ".\$repo_name\" } git clone "https://github.com/$github_owner/$repo_name.git" if ('$(runner_images_version)' -ne 'alpha') { $include_prerelease = if ('$(runner_images_version)' -eq 'prerelease') { $true } else { $false } Write-Output "include_prerelease = $include_prerelease" $latest_release = ${{ parameters.repository_base_path }}/scripts/get-latestgithubrelease.ps1 -OSTagPrefix '$(image_os)' -GitHubOwner $github_owner -RepoName $repo_name -IncludePrerelease $include_prerelease Write-Output "latest_release = $latest_release" cd runner-images git checkout ($latest_release.tag_name) } - task: PowerShell@2 name: fixBuildImageScript displayName: 'Fix Build Image Script' inputs: targetType: 'inline' script: | $buildImageScriptPath = Join-Path (Join-Path (Join-Path "runner-images" "images.CI") "linux-and-win") "build-image.ps1" (Get-Content $buildImageScriptPath).Replace('"$buildName*"', '"$buildName.azure-arm.image"') | Set-Content $buildImageScriptPath - task: PowerShell@2 name: buildVm displayName: "Build VM" inputs: targetType: filePath filePath: ./runner-images/images.CI/linux-and-win/build-image.ps1 arguments: -TemplatePath '$(template_path)' ` -BuildTemplateName '$(build_template_name)' ` -ClientId '$(client_id)' ` -ClientSecret '$(client_secret)' ` -Location '$(location)' ` -ImageName '$(image_name)' ` -ImageResourceGroupName '$(image_rg_name)' ` -TempResourceGroupName '$(temp_rg_name)' ` -SubscriptionId '$(subscription_id)' ` -TenantId '$(tenant_id)' ` -ImageOs '$(image_os)' ` -VirtualNetworkName '$(vnet_name)' ` -VirtualNetworkRG '$(vnet_rg)' ` -VirtualNetworkSubnet '$(vnet_subnet)' ` -Tags @{ExcludeMdeAutoProvisioning = $true} env: PACKER_LOG: 1 PACKER_LOG_PATH: "$(Agent.TempDirectory)/packer-log.txt" GALLERY_NAME: "$(gallery_name)" GALLERY_RG_NAME: "$(gallery_rg_name)" GALLERY_IMAGE_NAME: "$(gallery_image_name)" GALLERY_IMAGE_VERSION: "$(gallery_image_version)" GALLERY_STORAGE_ACCOUNT_TYPE: "$(gallery_storage_account_type)" - task: PowerShell@2 displayName: 'Copy image artifacts to the separate directory' inputs: targetType: 'inline' script: | $rootDirectoryName = if ("$(image_type)".StartsWith("ubuntu")) { "ubuntu" } else { "windows" } $rootDirectoryPath = Join-Path (Join-Path "runner-images" "images") $rootDirectoryName | Resolve-Path $readmePath = Join-Path $rootDirectoryPath "$(image_readme_name)" $softwareReportPath = Join-Path $rootDirectoryPath "software-report.json" Copy-Item -Path $readmePath -Destination "$(Build.ArtifactStagingDirectory)/" if (Test-Path $softwareReportPath) { Copy-Item -Path $softwareReportPath -Destination "$(Build.ArtifactStagingDirectory)/" } - task: PowerShell@2 displayName: 'Print markdown software report' inputs: targetType: 'inline' script: | Get-Content -Path "$(Build.ArtifactStagingDirectory)/$(image_readme_name)" - task: PowerShell@2 displayName: 'Print json software report' inputs: targetType: 'inline' script: | $softwareReportPath = "$(Build.ArtifactStagingDirectory)/software-report.json" if (Test-Path $softwareReportPath) { Get-Content -Path $softwareReportPath } - task: PublishBuildArtifacts@1 inputs: ArtifactName: 'Built_VM_Artifacts' displayName: Publish Artifacts - task: PowerShell@2 displayName: 'Print provisioners duration' inputs: targetType: 'filePath' filePath: ./runner-images/images.CI/measure-provisioners-duration.ps1 arguments: -PackerLogPath "$(Agent.TempDirectory)/packer-log.txt" ` -PrefixToPathTrim "$(template_path)" ` -PrintTopNLongest 25 - task: PowerShell@2 displayName: 'Authenticate to Azure in Azure CLI' condition: always() inputs: targetType: 'inline' script: | az login --service-principal --username '$(client_id)' --password '$(client_secret)' --tenant '$(tenant_id)' | Out-Null az account set --subscription '$(subscription_id)' | Out-Null - task: PowerShell@2 displayName: "Clean up resources" condition: always() inputs: targetType: filePath filePath: ./runner-images/images.CI/linux-and-win/cleanup.ps1 arguments: -TempResourceGroupName "$(temp_rg_name)" - task: PowerShell@2 displayName: "Clean up temporary image" condition: always() inputs: targetType: filePath filePath: ${{ parameters.repository_base_path }}/scripts/cleanup-gallery-temporaryimage.ps1 arguments: -ManagedImageName '$(image_name)' ` -ResourceGroup '$(image_rg_name)' ================================================ FILE: buildagent-generation.yml ================================================ parameters: - name: image_type displayName: Build Agent Image type: string default: windows2022 values: - windows2022 - windows2025 - ubuntu2204 - ubuntu2404 - name: runner_images_version displayName: runner-images Version type: string default: release values: - alpha - prerelease - release - name: variable_group_name displayName: Variable Group type: string default: 'Image Generation Variables' - name: agent_pool displayName: Agent Pool type: string default: 'Host Pool - Image' trigger: none stages: - template: buildagent-generation-template.yml parameters: image_type: ${{ parameters.image_type }} runner_images_version: ${{ parameters.runner_images_version }} variable_group_name: ${{ parameters.variable_group_name }} agent_pool: ${{ parameters.agent_pool }} ================================================ FILE: managedimage-cleanup-template.yml ================================================ parameters: - name: variable_group_name displayName: Variable Group type: string default: 'Image Generation Variables' - name: agent_pool displayName: Agent Pool type: string default: CI Windows2022 - name: gallery_images_to_keep displayName: Number of image versions to keep in gallery type: number default: 3 - name: repository_base_path displayName: Scripts Path type: string default: . stages: - stage: delete_gallery_imagevm displayName: 'Delete Gallery Image Version VM' jobs: - job: cleanupobsoletevmrunnerimages displayName: 'Cleanup obsolete VM Gallery runner images' pool: name: ${{ parameters.agent_pool }} variables: - group: ${{ parameters.variable_group_name }} steps: - checkout: self - ${{ if ne(parameters.repository_base_path, '.') }}: - checkout: ${{ parameters.repository_base_path }} - task: PowerShell@2 name: setVars displayName: 'Set image template variables' inputs: targetType: 'inline' script: | $client_id = "$(DOBA-CLIENT-ID)" $client_secret = "$(DOBA-CLIENT-SECRET)" $tenant_id = "$(DOBA-TENANT-ID)" $subscription_id = "$(DOBA-SUBSCRIPTION-ID)" $gallery_name = "$(DOBA-GALLERY-NAME)" $gallery_rg_name = "$(DOBA-GALLERY-RESOURCE-GROUP)" Write-Host "##vso[task.setvariable variable=client_id]$client_id" Write-Host "##vso[task.setvariable variable=client_secret;isSecret=true]$client_secret" Write-Host "##vso[task.setvariable variable=tenant_id]$tenant_id" Write-Host "##vso[task.setvariable variable=subscription_id]$subscription_id" Write-Host "##vso[task.setvariable variable=gallery_name]$gallery_name" Write-Host "##vso[task.setvariable variable=gallery_rg_name]$gallery_rg_name" - task: PowerShell@2 displayName: 'Remove obsolete VM Gallery runner Images' inputs: targetType: filePath filePath: ${{ parameters.repository_base_path }}/scripts/cleanup-gallery-vmimageversion.ps1 arguments: -ClientId $(DOBA-CLIENT-ID) ` -ClientSecret $(DOBA-CLIENT-SECRET) ` -SubscriptionId $(DOBA-SUBSCRIPTION-ID) ` -TenantId $(DOBA-TENANT-ID) ` -GalleryName $(DOBA-GALLERY-NAME) ` -GalleryResourceGroup $(DOBA-GALLERY-RESOURCE-GROUP) ` -GalleryImagesToKeep ${{ parameters.gallery_images_to_keep }} ` -ImageDefinitions @("ubuntu2204-agentpool-full", "ubuntu2404-agentpool-full", "windows2022-agentpool-full", "windows2025-agentpool-full") ================================================ FILE: managedimage-cleanup.yml ================================================ parameters: - name: variable_group_name displayName: Variable Group type: string default: 'Image Generation Variables' schedules: - cron: "0 0 * * 6" displayName: Weekly on Saturday branches: include: - main always: true trigger: none pool: vmImage: 'windows-latest' variables: - group: ${{ parameters.variable_group_name }} stages: - template: managedimage-cleanup-template.yml parameters: variable_group_name: ${{ parameters.variable_group_name }} gallery_images_to_keep: 3 agent_pool: 'Azure Pipelines' ================================================ FILE: scripts/cleanup-gallery-temporaryimage.ps1 ================================================ param( [String] [Parameter (Mandatory=$true)] $ManagedImageName, [String] [Parameter (Mandatory=$true)] $ResourceGroup ) $managedImageId=$(az image list --resource-group $ResourceGroup --query "[?name=='$ManagedImageName'].id" --output tsv) if ($managedImageId) { Write-Output "Retrieve generated managedImageId: $managedImageId" az image delete --ids $managedImageId | Out-Null Write-Output "Cleanup temporary created Managed Image" } else { Write-Output "Managed Image $ManagedImageName not found in Resource Group $ResourceGroup" } ================================================ FILE: scripts/cleanup-gallery-vmimageversion.ps1 ================================================ param( [String] [Parameter (Mandatory=$true)] $ClientId, [String] [Parameter (Mandatory=$true)] $ClientSecret, [String] [Parameter (Mandatory=$true)] $SubscriptionId, [String] [Parameter (Mandatory=$true)] $TenantId, [String] [Parameter (Mandatory=$true)] $GalleryName, [String] [Parameter (Mandatory=$true)] $GalleryResourceGroup, [int] [Parameter (Mandatory=$true)] $GalleryImagesToKeep, [Array] [Parameter (Mandatory=$true)] $ImageDefinitions ) # Variables $ImageCountThreshold = $GalleryImagesToKeep + 1 # install required modules install-module Az.Compute -Scope CurrentUser -AllowClobber -Force import-module Az.Compute # Login using service principal $securePassword = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force $credentials = New-Object -TypeName PSCredential -ArgumentList $ClientId, $securePassword Connect-AzAccount -ServicePrincipal -Tenant $TenantId -Credential $credentials -Subscription $SubscriptionId # Get the gallery try { $gallery = Get-AzGallery -Name $GalleryName -ResourceGroupName $GalleryResourceGroup } catch { Write-Host "##vso[task.logissue type=error;] Gallery '$GalleryName' not found" Write-Host "##vso[task.complete result=Failed;]Task failed!" exit 1 } $needToWait = $false $JobList = @() if ($gallery) { # Loop through the image definitions foreach ($imageDefinition in $ImageDefinitions) { # Get the image definition try { $imageDef = Get-AzGalleryImageDefinition -ResourceGroupName $GalleryResourceGroup -GalleryName $gallery.Name -GalleryImageDefinitionName $imageDefinition } catch { Write-Host "##vso[task.logissue type=error;] Imagedefinition '$imageDefinition' not found" Write-Host "##vso[task.complete result=Failed;]Task failed!" exit 1 } if ($imageDef) { # Get all images of the image definition $images = Get-AzGalleryImageVersion -ResourceGroupName $GalleryResourceGroup -GalleryImageDefinitionName $imageDef.Name -GalleryName $gallery.Name # Filter to succeeded versions only and sort by published date ascending (oldest first) $succeededImages = $images | Where-Object { $_.ProvisioningState -eq 'Succeeded' } | Sort-Object -Property { $_.PublishingProfile.PublishedDate } if ($succeededImages.Count -ge $ImageCountThreshold) { # Remove all succeeded images except the most recent ones $imagesToRemove = $succeededImages[0..($succeededImages.Count - $GalleryImagesToKeep - 1)] foreach ($imageToRemove in $imagesToRemove) { Write-Host "##[section]Removing image version for image definition '$imageDefinition': $($imageToRemove.Name) with $($imageToRemove.PublishingProfile.PublishedDate)" $JobList += Remove-AzGalleryImageVersion -ResourceGroupName $GalleryResourceGroup -GalleryName $gallery.Name -GalleryImageDefinitionName $imageDefinition -Name $imageToRemove.Name -Force -AsJob $needToWait = $true } } else { Write-Host "##[section]The number of succeeded images for image definition '$imageDefinition' is $($succeededImages.Count), which is no more than $GalleryImagesToKeep. No images will be removed." } } } } if ($needToWait) { Write-Host "##[section]Waiting for the image removal jobs to finish." $JobList | Wait-Job | Receive-Job | Format-Table -AutoSize } else { Write-Host "##[section]No image removal jobs were started." } ================================================ FILE: scripts/get-latestgithubrelease.ps1 ================================================ param( [Parameter(Mandatory = $true)] [string]$GitHubOwner, [Parameter(Mandatory = $true)] [string]$RepoName, [Parameter(Mandatory = $true)] [string]$OSTagPrefix, [Parameter(Mandatory = $true)] [bool]$IncludePreRelease ) function Get-GitHubReleases { param( [string]$GitHubOwner, [string]$RepoName ) $apiUrl = "https://api.github.com/repos/$GitHubOwner/$RepoName/releases" $headers = @{ 'User-Agent' = 'PowerShell' } try { $releases = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get return $releases } catch { Write-Host 'Error: Unable to retrieve GitHub releases.' return $null } } function Get-LatestGithubRelease { param( [Parameter(Mandatory = $true)] [string]$GitHubOwner, [Parameter(Mandatory = $true)] [string]$RepoName, [Parameter(Mandatory = $true)] [string]$OSTagPrefix, [Parameter(Mandatory = $true)] [bool]$IncludePreRelease ) $releases = Get-GitHubReleases -GitHubOwner $githubOwner -RepoName $repoName $filteredreleases = @() if ($releases) { $releases | ForEach-Object { if ($OSTagPrefix -eq $null -or $_.tag_name -like "*$OSTagPrefix*") { $filteredreleases += $_ } } if (!$IncludePreRelease) { $filteredreleases = $filteredreleases | Where-Object { $_.prerelease -eq $false } } $latest_release = $filteredreleases | Sort-Object -Property published_at -Descending | Select-Object -First 1 } else { Write-Output 'Unable to retrieve GitHub releases.' } if ($latest_release) { $output_object = @{ 'tag_name' = $latest_release.tag_name 'name' = $latest_release.name 'published_at' = $latest_release.published_at 'url' = $latest_release.url 'target_commitish' = $latest_release.target_commitish 'prerelease' = $latest_release.prerelease } Write-Output $output_object } else { Write-Output 'Unable to retrieve GitHub releases.' } } Get-LatestGithubRelease -OSTagPrefix $OSTagPrefix -GitHubOwner $GitHubOwner -RepoName $RepoName -IncludePreRelease $IncludePreRelease