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