New articles available on specification-driven development with AVM modules! Learn how to use GitHub Copilot and Spec Kit to accelerate the development of Azure infrastructure solutions with AVM. Seeend-to-end examplesfor both Bicep and Terraform.
Introduction
Value Proposition
Azure Verified Modules (AVM) is an initiative to consolidate and set the standards for what a good Infrastructure-as-Code module looks like.
Modules will then align to these standards, across languages (Bicep, Terraform etc.) and will then be classified as AVMs and available from their respective language specific registries.
AVM is a common code base, a toolkit for our Customers, our Partners, and Microsoft. It’s an official, Microsoft driven initiative, with a devolved ownership approach to develop modules, leveraging internal & external communities.
Azure Verified Modules enable and accelerate consistent solution development and delivery of cloud-native or migrated applications and their supporting infrastructure by codifying Microsoft guidance (WAF), with best practice configurations.
Modules
Azure Verified Modules provides two types of modules: Resource and Pattern modules.
AVM modules are used to deploy Azure resources and their extensions, as well as reusable architectural patterns consistently.
Modules are composable building blocks that encapsulate groups of resources dedicated to one task.
Flexible, generalized, multi-purpose
Integrates child resources
Integrates extension resources
AVM improves code quality and provides a unified customer experience.
Important
AVM is owned, developed & supported by Microsoft, you may raise a GitHub issue on this repository or the module’s repository directly to get support or log feature requests.
You can also log a support ticket and if the issue is not related to the Azure platform, you will be redirected to submit a GitHub issue for the module owner(s) or the AVM team.
Azure Verified Modules (AVM), as “One Microsoft”, we want to provide and define the single definition of what a good IaC module is;
How they should be constructed and built
Enforcing consistency and testing where possible
How they are to be consumed
What they deliver for consumers in terms of resources deployed and configured
And where appropriate aligned across IaC languages (e.g. Bicep, Terraform, etc.).
Mission Statement
Our mission is to deliver a comprehensive Azure Verified Modules library in multiple IaC languages, following the principles of the well-architected framework, serving as the trusted Microsoft source of truth. Supported by Microsoft, AVM will accelerate deployment time for Azure resources and architectural patterns, empowering every person and organization on the planet on their IaC journey.
Definition of “Verified” Summary
The modules are supported by Microsoft, across it’s many internal organizations, as described in Module Support
Modules are aligned to clear specifications that enforces consistency between all AVM modules. See the ‘Specifications & Definitions’ section in the menu
Modules will continue to stay up-to-date with product/service roadmaps owned by the module owners and contributors
Modules will provide clear documentation alongside examples to promote self-service consumption
Modules will be tested to ensure they comply with the specifications for AVM and their examples deploy as intended
Why Azure Verified Modules?
This effort to create Azure Verified Modules, with a strategy and definition, is required based on the sheer number of existing attempts from all areas across Microsoft to try and address this same area for our customers and partners. Across Microsoft there are many initiatives, projects and repositories that host and provide IaC modules in several languages, for example Bicep and Terraform. Each of these come with differing code styling and standards, consumption methods and approaches, testing frameworks, target personas, contribution guidelines, module definitions and most importantly support statements from their owners and maintainers.
However, none of these existing attempts have ever made it all the way through to becoming a brand and the go to place for IaC modules from Microsoft that consumers can trust (mainly around longevity and support), build upon and contribute back to.
Performing this effort now to create a shared single aligned strategy and definition for IaC modules from Microsoft, as One Microsoft, will allow us to accelerate existing and future projects, such as Application Landing Zone Accelerators (LZAs), as well as providing the building blocks via a library of modules, in the language of the consumers choice, that is consistent, trusted and supported by Microsoft. This all leads to consumers being able to accelerate faster, no matter what stage of their IaC journey they are on.
We also know, from our customers, that well defined support statements from Microsoft are required for initiatives like this to succeed at scale, especially in larger enterprise customers. We have seen over the past FY that this topic alone is important and is one that has led to confusion and frustration to customers who are consuming modules developed by individuals that in the end are not “officially” Microsoft supported and this unfortunately normally occurs at a critical point in time for the project being worked on, which amplifies frustrations.
How will we create, support and enforce Azure Verified Modules?
Azure Verified Modules will achieve this, and its mission statement, by implementing and enforcing the following; driven by the AVM Core Team:
Publishing AVM modules to their respective public registries for consumption
While some pipelines can momentarily show as red, a new module version cannot be published without a successful test run. A failing test may indicate a recent change to the platform that is causing a break in the module or any intermittent errors, such as a periodic test deployment attempting to create a resource with a name already taken in another Azure region.
This page contains various views of the module index (catalog) for Bicep Resource Modules. To see these views, click on the expandable sections with the “β” sign below.
To see the full, unfiltered, unformatted module catalog on GitHub, click here.
To download the source catalog JSON file, click here.
Note
Modules listed below that aren’t shown with the status of Module Available π’, are currently in development and are not yet available for use. For proposed modules, see the Proposed modules section below.
Published modules - π’ & π‘
β Published Modules - Module names, status and owners
Elastic SAN - Volume Group (Child of avm/res/elastic-san/elastic-san) SAN, ESAN, Elastic SAN, Azure Elastic Storage Area Network, iSCSI, internet Small Computer Systems Interface
Elastic SAN - Volume Group - Snapshot (Child of avm/res/elastic-san/elastic-san/volume-group) SAN, ESAN, Elastic SAN, Azure Elastic Storage Area Network, iSCSI, internet Small Computer Systems Interface
Elastic SAN - Volume Group - Volume (Child of avm/res/elastic-san/elastic-san/volume-group) SAN, ESAN, Elastic SAN, Azure Elastic Storage Area Network, iSCSI, internet Small Computer Systems Interface
Consistent Features & Extension Resources (Interfaces)
β Consistent Features & Extension Resources (Interfaces)
The following table shows which Bicep resource modules have which consistent features and extension resources (interfaces) implemented as defined in the Bicep Interfaces specification.
This section is mainly intended for module owners and contributors as it contains the module names and telemetry ID prefixes needed for module development.
Module owners obtain access through the AVM Module Contributors access package, not per-module GitHub teams. Any ModuleOwnersGHTeam values in the source CSV are legacy metadata, not teams to create.
Module name and Telemetry ID prefix
β All Modules - Module name and Telemetry ID prefix
This page contains various views of the module index (catalog) for Bicep Pattern Modules. To see these views, click on the expandable sections with the “β” sign below.
To see the full, unfiltered, unformatted module catalog on GitHub, click here.
To download the source catalog JSON file, click here.
Note
Modules listed below that aren’t shown with the status of Module Available π’, are currently in development and are not yet available for use. For proposed modules, see the Proposed modules section below.
Published modules - π’ & π‘
β Published Modules - Module names, status and owners
This section is mainly intended for module owners and contributors as it contains the module names and telemetry ID prefixes needed for module development.
Module owners obtain access through the AVM Module Contributors access package, not per-module GitHub teams. Any ModuleOwnersGHTeam values in the source CSV are legacy metadata, not teams to create.
Module name and Telemetry ID prefix
β All Modules - Module name and Telemetry ID prefix
This page contains various views of the module index (catalog) for Bicep Utility Modules. To see these views, click on the expandable sections with the “β” sign below.
To see the full, unfiltered, unformatted module catalog on GitHub, click here.
To download the source catalog JSON file, click here.
Note
Modules listed below that aren’t shown with the status of Module Available π’, are currently in development and are not yet available for use. For proposed modules, see the Proposed modules section below.
Published modules - π’ & π‘
β Published Modules - Module names, status and owners
This section is mainly intended for module owners and contributors as it contains the module names and telemetry ID prefixes needed for module development.
Module owners obtain access through the AVM Module Contributors access package, not per-module GitHub teams. Any ModuleOwnersGHTeam values in the source CSV are legacy metadata, not teams to create.
Module name and Telemetry ID prefix
β All Modules - Module name and Telemetry ID prefix
This page contains various views of the module index (catalog) for Terraform Resource Modules. To see these views, click on the expandable sections with the “β” sign below.
To see the full, unfiltered, unformatted module catalog on GitHub, click here.
To download the source catalog JSON file, click here.
Note
Modules listed below that aren’t shown with the status of Module Available π’, are currently in development and are not yet available for use. For proposed modules, see the Proposed modules section below.
Published modules - π’ & π‘
β Published Modules - Module names, status and owners
This page contains various views of the module index (catalog) for Terraform Pattern Modules. To see these views, click on the expandable sections with the “β” sign below.
To see the full, unfiltered, unformatted module catalog on GitHub, click here.
To download the source catalog JSON file, click here.
Note
Modules listed below that aren’t shown with the status of Module Available π’, are currently in development and are not yet available for use. For proposed modules, see the Proposed modules section below.
Published modules - π’ & π‘
β Published Modules - Module names, status and owners
This page contains various views of the module index (catalog) for Terraform Utility Modules. To see these views, click on the expandable sections with the “β” sign below.
To see the full, unfiltered, unformatted module catalog on GitHub, click here.
To download the source catalog JSON file, click here.
Note
Modules listed below that aren’t shown with the status of Module Available π’, are currently in development and are not yet available for use. For proposed modules, see the Proposed modules section below.
Published modules - π’ & π‘
β Published Modules - Module names, status and owners
This page is a work in progress and will be updated as we improve & finalize the content. Please check back regularly for updates.
When developing an Azure solution using AVM modules, there are several aspects to consider. This page covers important concepts and provides guidance the technical decisions. Each concept/topic referenced here will be further detailed in the corresponding Bicep or Terraform specific guidance.
Language-agnostic concepts
Topics/concepts that are relevant and applicable for both Bicep and Terraform.
Module Sourcing
Public Registry
Leveraging the public registries (i.e., the Bicep Public Registry or the Terraform Public Registry) is the most common and recommended approach.
This allows you to leverage the latest and greatest features of the AVM modules, as well as the latest security updates. While there aren’t any prerequisites for using the public registry - no extra software component or service needs to be installed and no configuration is needed - the client machine the deployment is initiated from will need to have access to the public registry.
Private Registry (synced)
A private registry - that is hosted in your own environment - can store modules originating from the public registry. Using a private registry still grants you the latest version of AVM modules while allowing you to review each version of each module before admitting them to your private registry. You also have control over who can access your own private registry. Note that using a private registry means that you’re still using each module as is, without making any changes.
Inner-sourcing
Inner-sourcing AVM means maintaining your own, synchronized copy of AVM modules in your own internal private registry, repositories or other storage option. Customers normally look to inner-source AVM modules when they have strict security and compliance requirements, or when they want to publish their own lightly wrapped versions of the modules to meet their specific needs; for example changing some allowed or default values for parameter or variable inputs.
This is a more complex approach and requires more effort to maintain, but it can be beneficial in certain scenarios, however, it should not be the default approach as it can lead to a lot of overhead and maintenance and requires significant skills and resources to set up and maintain.
There are many ways to approach inner-sourcing AVM modules for both Bicep and Terraform. The AVM team will be publishing guidance on this topic, based on customer experience and learnings.
Tip
You can see the AVM team talking about inner-sourcing on the AVM February 2025 community call on YouTube.
Solution Development
This section provides advanced guidance for developing solutions using Azure Verified Modules (AVM). It covers technical decisions and concepts that are important for building and deploying Azure solutions using AVM modules.
Planning your solution
When implementing infrastructure in Azure leveraging IaaS and PaaS services, there are multiple options for Azure deployments. In this article we assume that a decision has been made to implement your solution, using Infrastructure-as-Code (IaC). This is best suited to allow programmatic declarative control of the target infrastructure and is ideal for projects that require repeatability and idempotency.
Choosing an Infrastructure-as-Code language
There are multiple language choices when implementing your solution using IaC in Azure. The Azure Verified Modules project currently supports Bicep and Terraform. The following guidance summarizes considerations that can help choose the option that best suits your requirements.
Reasons to choose Bicep
Bicep is the Microsoft 1st party offering for IaC deployments. It supports Generally Available (GA) and preview features for all Azure resources and allows for modular composition of resources and solution templates. The use of simplified syntax makes IaC development intuitive and the use of the Bicep extension for VSCode provides IntelliSense and syntax validation to assist with coding. Finally, Bicep is well suited for infrastructure projects and teams that don’t require management of other cloud platforms or services outside of Azure. For a more detailed read on reasons to choose Bicep, read this article from the Bicep documentation.
Reasons to choose Terraform
HashiCorp’s Terraform is an extensible 3rd party platform that can be used across multiple cloud and on-premises platforms using multiple provider plugins. It has widespread adoption due to its simplified human-readable configuration files, common functionality, and the ability to allow a project to span multiple provider spaces.
Terraform can target Azure through multiple providers. New AVM Terraform module authoring requires AzAPI: every resource, pattern, and utility module MUST use AzAPI for every control-plane resource and supported data-plane operation, including supporting resources in examples and tests. AzureRM is permitted only for a documented data-plane/non-ARM operation that AzAPI cannot implement under TFFR3. AzAPI talks directly to the Azure Resource Manager REST API, providing day-zero access to new resource types, properties and API versions, built-in retry and pre-flight validation, and conceptual alignment with Bicep modules.
Projects typically choose Terraform when they bridge multiple cloud infrastructure platforms or when the development team has previous experience coding in Terraform. Modern Integrated Development Environments (IDE) - such as Visual Studio Code - include extension support for Terraform features as well as additional Azure specific extensions. These extensions enable syntax validation and highlighting as well as code formatting and HashiCorp Cloud Platform (HCP) integration for HashiCorp Cloud customers. For a more detailed read on reasons to choose Terraform, read this article from the Terraform on Azure documentation.
Architecture design
Before starting the process of codifying infrastructure, it is important to develop a detailed architecture of what will be created. This should include details for:
Organizational elements such as management groups, subscriptions, and resource groups as well as any tagging and Role Based Access (RBAC) configurations for each.
Infrastructure services that will be created along with key configuration details like sku values, network CIDR range sizes, or other solution specific configuration.
Any relationship between services that will be codified as part of the deployment.
Identify inputs to your solution for designs that are intended to be used as templates.
Note
For a production grade solution, you need to
follow the recommendations of the Cloud Adoption Framework (CAF) and have your platform and application landing zones defined, as per Azure Landing Zones (ALZ);
follow the recommendations of the Azure Well-Architected Framework (WAF) to ensure that your solution is compliant with and integrates into your organization’s policies and standards. This includes considerations for security, identity, networking, monitoring, cost management, and governance.
Sourcing content for deployment
Once the architecture is agreed upon, it is time to plan the development of your IaC code. There are several key decision points that should be considered during this phase.
Content creation methods
The two primary methods used to create your solutions module are:
Using base resources (“vanilla resources”) from scratch or
Leveraging pre-created modules from the AVM library to minimize the time to value during development.
The trade-off between the two options is primarily around control vs. speed. AVM works to provide the best of both options by providing modules with opinionated and recommended practice defaults while allowing for more detailed configuration as needed. In our sample exercise we’ll be using AVM modules to demonstrate building the example solution.
AVM module type considerations
When using AVM modules for your solution, there is an additional choice that should be considered. The AVM library includes both pattern and resource module types. If your architecture includes or follows a well-known pattern then a pattern module may be the right option for you. If you determine this is the case, then search the module index for pattern modules in your chosen language to see if an option exists for your scenario. Otherwise, using resource modules from the library will be your best option.
In cases where an AVM resource or pattern module isn’t available for use, review the Bicep or Terraform provider documentation to identify how to augment AVM modules with standalone resources. If you feel that additional resource or pattern modules would be useful, you can also request the creation of a pattern or resource module by creating a module proposal issue on the AVM github repository.
Module source considerations
Once the decision has been made to use AVM modules to help accelerate solution development, a decision about where those modules will be sourced from is the next key decision point. A detailed exploration of the different sourcing options can be found in the Module Sourcing section of the Concepts page. Take a moment to review the options discussed there.
For our solution we will leverage the Public Registry option by sourcing AVM modules directly from the respective Terraform and Bicep public registries. This will avoid the need to fork copies of the modules for private use.
Subsections of Solution Development
Bicep - Solution Development
Introduction
Azure Verified Modules (AVM) for Bicep are a powerful tool that leverage the Bicep domain-specific language (DSL), industry knowledge, and an Open Source community, which altogether enable developers to quickly deploy Azure resources that follow Microsoft’s recommended practices for Azure. In this article, we will walk through the Bicep specific considerations and recommended practices on developing your solution leveraging Azure Verified Modules. We’ll review some of the design features and trade-offs and include sample code to illustrate each discussion point.
In this tutorial, we will:
Deploy a basic Virtual Machine architecture into Azure
Explore recommended practices related to Bicep template development
Demonstrate the ease with which you can deploy AVM modules
Describe each of the development and deployment steps in detail
After completing this tutorial, you’ll have a working knowledge of:
How to discover and add AVM modules to your Bicep template
How to reference and use outputs across AVM modules
Recommended practices for parameterization and structure of your Bicep file
Configuration of AVM modules to meet Microsoft’s Well Architected Framework (WAF) principles
How to deploy your Bicep template into an Azure subscription from your local machine
Let’s get started!
Prerequisites
You will need the following tools and components to complete this guide:
Before you begin, make sure you have these tools installed in your development environment.
Solution Architecture
Before we begin coding, it is important to have details about what the infrastructure architecture will include. For our example, we will be building a solution that will host a simple application on a Linux virtual machine (VM). The solution must be secure and auditable. The VM must not be accessible from the internet and its logs should be easily accessible. All Azure services should utilize logging tools for auditing purposes.
Develop the Solution Code
Creating the main.bicep file
The architecture diagram shows all components needed for a successful solution deployment. Rather than building the complete solution at once, this tutorial takes an incremental approach building the Bicep file piece-by-piece and testing the deployment at each stage. This approach allows for discussion of each design decision along the way.
The development will start with core platform components: first the backend logging services (Log Analytics) and then the virtual network.
Let’s begin by creating our folder structure along with a main.bicep file. Your folder structure should be as follows:
VirtualMachineAVM_Example1/
βββ main.bicep
After you have your folder structure and main.bicep file, we can proceed with our first AVM resources!
Log Analytics
Let’s start by adding a logging service to our main.bicep since all other deployed resources will use this service for their logs.
Tip
Always begin template development by adding resources that create dependencies for other downstream services. This approach simplifies referencing these dependencies within your other modules as you develop them. For example, starting with Logging and Virtual Network services makes sense since all other services will depend on these.
The logging solution depicted in our Architecture Diagram shows we will be using a Log Analytics workspace. Let’s add that to our template! Open your main.bicep file and add the following:
Always click on the “Copy to clipboard” button in the top right corner of the Code sample area in order not to have the line numbers included in the copied code.
You now have a fully functional Bicep template that will deploy a working Log Analytics workspace! If you would like to try it, run the following in your console:
Note
For keeping the example below simple, we are using the traditional deployment commands, e.g., az deployment group create or New-AzResourceGroupDeployment. However, we encourage you to look into using Deployment Stacks instead by simply replacing the previous commands with az stack group create or New-AzResourceGroupDeploymentStack as well as the other required input parameters as shown here.
Deployment Stacks allow you to deploy a Bicep file as a stack, which is a collection of resources that are deployed together. This allows you to manage the lifecycle of the stack as a single unit, making it easier to deploy, update, and now even delete resources via Bicep. You can also implement RBAC Deny Assignments on your stacks deployed resources to prevent changes to the resources or specific actions on the resources to all but an excluded list of users, groups or other principals.
Deploy with
# Log in to AzureConnect-AzAccount
# Select your subscriptionSet-AzContext -SubscriptionId '<subscriptionId>'# Deploy a resource groupNew-AzResourceGroup -Name 'avm-bicep-vmexample1' -Location '<location>'# Invoke your deploymentNew-AzResourceGroupDeployment -DeploymentName 'avm-bicep-vmexample1-deployment' -ResourceGroupName 'avm-bicep-vmexample1' -TemplateFile '/<path-to>/VirtualMachineAVM_Example1/main.bicep'
# Log in to Azureaz login
# Select your subscriptionaz account set --subscription '<subscriptionId>'# Deploy a resource groupaz group create --name 'avm-bicep-vmexample1' --location '<location>'# Invoke your deploymentaz deployment group create --name 'avm-bicep-vmexample1-deployment' --resource-group 'avm-bicep-vmexample1' --template-file '/<path-to>/VirtualMachineAVM_Example1/main.bicep'
The above commands will log you in to your Azure subscription, select a subscription to use, create a resource group, then deploy the main.bicep template to your resource group.
AVM Makes the deployment of Azure resources incredibly easy. Many of the parameters you would normally be required to define are taken care of by the AVM module itself. In fact, the location parameter is not even needed in your template—when left blank, by default, all AVM modules will deploy to the location in which your target Resource Group exists.
Now we have a Log Analytics workspace in our resource group which doesn’t do a whole lot of good on its own. Let’s take our template a step further by adding a Virtual Network that integrates with the Log Analytics workspace.
Virtual Network
We will now add a Virtual Network to our main.bicep file. This VNet will contain subnets and Network Security Groups (NSGs) for any of the resources we deploy that require IP addresses.
Again, the Virtual Network AVM module requires only two things: a name and an addressPrefixes parameter.
Configure Diagnostics Settings
There is an additional parameter available in most AVM modules named diagnosticSettings. This parameter allows you to configure your resource to send its logs to any suitable logging service. In our case, we are using a Log Analytics workspace.
Let’s update our main.bicep file to have our VNet send all of its logging data to our Log Analytics workspace:
Notice how the diagnosticsSettings parameter needs a workspaceResourceId? All you need to do is add a reference to the built-in logAnalyticsWorkspaceId output of the logAnalyticsWorkspace AVM module. That’s it! Our VNet now has integrated its logging with our Log Analytics workspace. All AVM modules come with a set of built-in outputs that can be easily referenced by other modules within your template.
Info
All AVM modules have built-in outputs which can be referenced using the <moduleName>.outputs.<outputName> syntax.
When using plain Bicep, many of these outputs require multiple lines of code or knowledge of the correct object ID references to get at the desired output. AVM modules do much of this heavy lifting for you by taking care of these complex tasks within the module itself, then exposing them to you through the module’s outputs. Find out more about Bicep Outputs.
Add a Subnet and NAT Gateway
We can’t use a Virtual Network without subnets, so let’s add a subnet next. According to our Architecture, we will have three subnets: one for the Virtual Machine, one for the Bastion host, and one for Private Endpoints. We can start with the VM subnet for now. While we’re at it, let’s also add the NAT Gateway, the NAT Gateway’s Public IP, the attach the NAT Gateway to the VM subnet.
The modification adds a subnets property to our virtualNetwork module. The AVM network/virtual-network module supports the creation of subnets directly within the module itself. We can also link our NAT Gateway directly to the subnet within this submodule.
A nice feature within Bicep are the various functions available. We use the cidrSubnet() function to declare CIDR blocks without having to calculate them on your own.
Switch to Parameters and Variables
See how we are reusing the same CIDR block 10.0.0.0/16 in multiple locations? You may have noticed we are defining the same location in two different spots as well. We’re now at a point in the development where we should leverage one of our first recommended practices: using parameters and variables!
Tip
Use Bicep variables to define values that will be constant and reused with your template; use parameters anywhere you may need a modifiable value.
Let’s enhance the template by adding variables for the CIDR block and prefix, then use a location parameter with a default value. We’ll then reference those in the module:
We now have a good basis for the infrastructure to be utilized by the rest of the resources in our Architecture. We will come back to our networking in a future step, once we are ready to create some Network Security Groups. For now, let’s move on to other modules.
Key Vault
Key Vaults are one of the key components in most Azure architectures as they create a place where you can save and reference secrets in a secure manner (“secrets” in the general sense, as opposed to the secret object type in Key Vaults). The Key Vault AVM module makes it very simple to store secrets generated in your template. In this tutorial, we will use one of the most secure methods of storing and retrieving secrets by leveraging this Key Vault in our Bicep template.
The first step is easy: add the Key Vault AVM module to our main.bicep file. In addition, let’s also ensure it’s hooked into our Log Analytics workspace (we will do this for every new module from here on out).
The name of the Key Vault we will deploy uses the uniqueString() Bicep function. Key Vault names must be globally unique. We will therefore deviate from our standard naming convention thus far and make an exception for the Key Vault. Note how we are still adding a suffix to the Key Vault name, so its name remains recognizable; you can use a combination of concatenating unique strings, prefixes, or suffixes to follow your own naming standard preferences.
When we generate our unique string, we will pass in the resourceGroup().id as the seed for the uniqueString() function so that every time you deploy this main.bicep to the same resource group, it will use the same randomly generated name for your Key Vault (since resourceGroup().id will be the same).
Tip
Bicep has many built-in functions available. We used two here: uniqueString() and resourceGroup(). The resourceGroup(), subscription(), and deployment() functions are very useful when seeding uniqueString() or guid() functions. Just be cautious about name length limitations for each Azure service! Visit this page to learn more about Bicep functions.
We will use this Key Vault later on when we create a VM and need to store its password. Now that we have it, a Virtual Network, Subnet, and Log Analytics prepared, we should have everything we need to deploy a Virtual Machine!
Info
In the future, we will update this guide to show how to generate and store a certificate in the Key Vault, then use that certificate to authenticate into the Virtual Machine.
Virtual Machine
Warning
The AVM Virtual Machine module enables the EncryptionAtHost feature by default. You must enable this feature within your Azure subscription successfully deploy this example code. To do so, run the following:
Deploy with
# Wait a few minutes after running the command to allow it to propagateRegister-AzProviderFeature -FeatureName "EncryptionAtHost" -ProviderNamespace "Microsoft.Compute"
az feature register --namespace Microsoft.Compute --name EncryptionAtHost
# Propagate the changeaz provider register --namespace Microsoft.Compute
For our Virtual Machine (VM) deployment, we need to add the following to our main.bicep file:
The VM module is one of the more complex modules in AVM—behind the scenes, it takes care of a lot of heavy lifting that, without AVM, would require multiple Bicep resources to be deployed and referenced.
For example, look at the nicConfigurations parameter: normally, you would need to deploy a separate NIC resource, which itself also requires an IP resource, then attach them to each other, and finally, attach them all to your VM.
With the AVM VM module, the nicConfigurations parameter accepts an object, allowing you to create any number of NICs to attach to your VM from within the VM resource deployment itself. It handles all the naming, creation of other necessary dependencies, and attaches them all together, so you don’t have to. The osDisk parameter is similar, though slightly less complex. There are many more parameters within the VM module that you can leverage if needed, that share a similar ease-of-use.
Since this is the real highlight of our main.bicep file, we need to take a closer look at some of the other changes that were made.
VM Admin Password Parameter
1@description('Required. A password for the VM admin user.')
2@secure()
3param vmAdminPass string
First, we added a new parameter. The value of this will be provided when the main.bicep template is deployed. We don’t want any passwords stored as text in code; for our purposes, the safest way to do this is to prompt the end user for the password at the time of deployment.
Warning
The supplied password must be between 6-72 characters long and must satisfy at least 3 of password complexity requirements from the following: Contains an uppercase character; Contains a lowercase character; Contains a numeric digit; Contains a special character. Control characters are not allowed
Also note how we are using the @secure() decorator on the password parameter. This will ensure the value of the password is never displayed in any of the deployment logs or in Azure. We have also added the @description() decorator and started the description with “Required.” It’s a good habit and recommended practice to document your parameters in Bicep. This will ensure that VS Code’s built-in Bicep linter can provide end-users insightful information when deploying your Bicep templates.
Info
Always use the @secure() decorator when creating a parameter that will hold sensitive data!
The next thing we have done is save the value of our vmAdminPass parameter to our Key Vault. We have done this by adding a secrets parameter to the Key Vault module. Adding secrets to Key Vaults is very simple when using the AVM module.
By adding our password to the Key Vault, it will ensure that we never lose the password and that it is stored securely. As long as a user has appropriate permissions on the vault, the password can be fetched easily.
Here, we reference another built-in output, this time from the AVM Virtual Network module. This example shows how to use an output that is part of an array. When the Virtual Network module creates subnets, it automatically creates a set of pre-defined outputs for them, one of which is an array that contains each subnet’s subnetResourceId. Our VM Subnet was the first one created which is position [0] in the array.
Other AVM modules may make use of arrays to store outputs. If you are unsure what type of outputs a module provides, you can always reference the Outputs section of each module’s README.md.
Storage Account
The last major component we need to add is a Storage Account. Because this Storage Account will be used as a backend storage to hold blobs for the hypothetical application that runs on our VM, we’ll also create a blob container within it using the same AVM Storage Account module.
We now have all the major components of our Architecture diagram built!
The last steps we need to take to meet our requirements is to ensure our networking resources are secure and that we are using least privileged access by leveraging Role-Based Access Control (RBAC). Let’s get to it!
Network Security Groups
We’ll add a Network Security Group (NSG) to our VM subnet. This will act as a layer 3 and layer 4 firewall for networked resources. This implementation includes an appropriate inbound rule to allow SSH traffic from the Bastion host:
Since the Storage Account serves as a backend resource exclusively for the Virtual Machine, it will be secured as much as possible. This involves adding a Private Endpoint and disabling public internet access. AVM makes creation and assignment of Private Endpoints to resources incredibly easy. Take a look:
This implementation adds a dedicated subnet for Private Endpoints following the recommended practice of isolating Private Endpoints in their own subnet.
The addition of just a few lines of code in the privateEndpoints parameter handles the complex tasks of creating the Private Endpoint, associating it with the VNet, and attaching it to the resource. AVM drastically simplifies the creation of Private Endpoints for just about every Azure Resource that supports them.
The implementation also disables all public network connectivity to the Storage Account, ensuring it only accepts traffic via the Private Endpoint.
Finally, a Private DNS zone is added and linked to the VNet, enabling the VM to resolve the Private IP address associated with the Storage Account.
Bastion
To securely access the Virtual Machine without exposing its SSH port to the public internet, we’ll create an Azure Bastion host. The Bastion Host requires a subnet with the exact name AzureBastionSubnet which cannot contain anything other than Bastion Hosts.
This simple addition of the bastion-host AVM module completes the secure access component of our architecture. You can now access the Virtual Machine by way of the Bastion Host in the Azure Portal.
Role-Based Access Control
To complete our solution, we have one final task: to apply Role-Based Access Control (RBAC) restrictions on our services, namely the Key Vault and Storage Account. The goal is to explicitly allow only the Virtual Machine to have Create, Read, Update, or Delete (CRUD) permissions on these two services.
This is accomplished by enabling a System-assigned Managed Identity on the Virtual Machine, then granting the VM’s Managed Identity appropriate permissions on the Storage Account and Key Vault:
The Azure Subscription owner will have CRUD permissions for the Storage Account but not for the Key Vault. The Key Vault requires explicit RBAC permissions assigned to a user to grant them access: Provide access to Key Vaults using RBAC. Important!: at this point, you will only be able to access the Storage Account from the Bastion Host. Remember, public internet access has been disabled!
The RBAC policies have been successfully applied using a System-assigned Managed Identity on the Virtual Machine. This identity has been granted permissions on both the Key Vault and Storage Account. Now the VM can read secrets from the Key Vault and Read, Create, or Delete blobs in the Storage Account.
In a real production environment, the principle of least privileged access should be applied, providing only the exact permissions each service needs to carry out its functions. Learn more about Microsoft’s recommendations for identity and access management.
Conclusion
In this tutorial, we’ve explored how to leverage Azure Verified Modules (AVM) to build a secure, well-architected solution in Azure. AVM modules significantly simplify the deployment of Azure resources by abstracting away much of the complexity involved in configuring individual resources.
Your final, deployable Bicep template file should now look like this:
AVM modules provide several key advantages over writing raw Bicep templates:
Simplified Resource Configuration: AVM modules handle much of the complex configuration work behind the scenes
Built-in Recommended Practices: The modules implement many of Microsoft’s recommended practices by default
Consistent Outputs: Each module exposes a consistent set of outputs that can be easily referenced
Reduced Boilerplate Code: What would normally require hundreds of lines of Bicep code can be accomplished in a fraction of the space
As you continue your journey with Azure and AVM, remember that this approach can be applied to more complex architectures as well. The modular nature of AVM allows you to mix and match components to build solutions that meet your specific needs while adhering to Microsoft’s Well-Architected Framework.
By using AVM modules as building blocks, you can focus more on your solution architecture and less on the intricacies of individual resource configurations, ultimately leading to faster development cycles and more reliable deployments.
Clean up your environment
When you are ready, you can remove the infrastructure deployed in this example. Key Vaults are set to a soft-delete state so you will also need to purge the one we created in order to fully delete it. The following commands will remove all resources created by your deployment:
Clean up with
# Delete the resource groupRemove-AzResourceGroup -Name "avm-bicep-vmexample1" -Force
# Purge the Key VaultRemove-AzKeyVault -VaultName "<keyVaultName>" -Location "<location>" -InRemovedState -Force
# Delete the resource groupaz group delete --name 'avm-bicep-vmexample1' --yes --no-wait
# Purge the Key Vaultaz keyvault purge --name '<keyVaultName>' --no-wait
Congratulations, you have successfully leveraged AVM Bicep modules to deploy resources in Azure!
Tip
We welcome your contributions and feedback to help us improve the AVM modules and the overall experience for the community!
Terraform - Solution Development
Introduction
Azure Verified Modules (AVM) for Terraform are a powerful tool that leverage the Terraform domain-specific language (DSL), industry knowledge, and an Open Source community, which altogether enable developers to quickly deploy Azure resources that follow Microsoft’s recommended practices for Azure. In this article, we will walk through the Terraform specific considerations and recommended practices on developing your solution leveraging Azure Verified Modules. We’ll review some of the design features and trade-offs and include sample code to illustrate each discussion point.
Warning
This is a solution-composition lab, not a template for authoring an AVM module. Every new AVM Terraform module MUST use AzAPI for every control-plane resource and supported data-plane operation it declares. In a new AVM module repository, AzureRM is permitted only for a specific documented data-plane/non-ARM operation that AzAPI cannot implement. It must not be used for control-plane resources in the root module, submodules, examples/end-to-end tests, Terraform tests, fixtures, or documentation snippets. A solution root may configure AzureRM only when a currently published AVM dependency requires it; direct supporting Azure resources must still use AzAPI. Current modules expose parent_id instead of resource_group_name (per TFRMFR1), name their primary resource this (per TFRMNFR2), and source the AzAPI resource type from var.resource_types (per TFFR6). For a concise current example, use the Terraform quickstart and follow TFFR3.
Prerequisites
You will need the following tools and components to complete this guide:
Before you begin, ensure you have these tools installed in your development environment.
Planning
Good module development should start with a good plan. Let’s first review the architecture and module design prior to developing our solution.
Solution Architecture
Before we begin coding, it is important to have details about what the infrastructure architecture will include. For our example, we will be building a solution that will host a simple application on a Linux virtual machine (VM).
In our design, the resource group for our solution will require appropriate tagging to comply with our corporate standards. Resources that support Diagnostic Settings must also send metric data to a Log Analytics workspace, so that the infrastructure support teams can get metric telemetry. The virtual machine will require outbound internet access to allow the application to properly function. A Key Vault will be included to store any secrets and key artifacts, and we will include a Bastion instance to allow support personnel to access the virtual machine if needed. Finally, the VM is intended to run without interaction, so we will auto-generate an SSH private key and store it in the Key Vault for the rare event of someone needing to log into the VM.
Based on this narrative, we will create the following resources:
A resource group to contain all the resources with tagging
A random string resource for use in resources with global naming (Key Vault)
A Log Analytics workspace for diagnostic data
A Key Vault with:
Role-Based Access Control (RBAC) to allow data access
Logging to the Log Analytics workspace
A virtual network with:
A virtual machine subnet
A Bastion subnet
Network Security Group on the VM subnet allowing SSH traffic
Logging to the Log Analytics workspace
A NAT Gateway for enabling outbound internet access
Associated to the virtual machine subnet
A Bastion service for secure remote access to the Virtual Machine
Logging to the Log Analytics workspace
A virtual machine resource with
A single private IPv4 interface attached to the VM subnet
A randomly generated admin account private key stored in the Key Vault
Metrics sent to the log Analytics workspace
Solution template (root module) design
Since our solution template (root module) is intended to be deployed multiple times, we want to develop it in a way that provides flexibility while minimizing the amount of input necessary to deploy the solution. For these reasons, we will create our module with a small set of variables that allow for deployment differentiation while still populating solution-specific defaults to minimize input. We will also separate our content into variables.tf, outputs.tf, terraform.tf, and main.tf files to simplify future maintenance.
Based on this, our file system will take the following structure:
Module Directory
terraform.tf - This file holds the provider definitions and versions.
variables.tf - This file contains the input variable definitions and defaults.
outputs.tf - This file contains the outputs and their descriptions for use by any external modules calling this root module.
main.tf - This file contains the core module code for creating the solutions infrastructure.
development.tfvars - This file will contain the inputs for the instance of the module that is being deployed. Content in this file will vary from instance to instance.
Note
Terraform will merge content from any file ending in a .tf extension in the module folder to create the full module content. Because of this, using different files is not required. We encourage file separation to allow for organizing code in a way that makes it easier to maintain. While the naming structure we’ve used is common, there are many other valid file naming and organization options that can be used.
In our example, we will use the following variables as inputs to allow for customization:
location - The location where our infrastructure will be deployed.
name_prefix - This will be used to preface all of the resource naming.
virtual_network_prefix - This will be used to ensure IP uniqueness for the deployment.
tags - The custom tags to use for each deployment.
Finally, we will export the following outputs:
resource_group_name - This will allow for finding this deployment if there are multiples.
virtual_machine_name - This can be used to find and login to the vm if needed.
Identifying AVM modules that match our solution
Now that we’ve determined our architecture and module configurations, we need to see what AVM modules exist for use in our solution. To do this, we will open the AVM Terraform pattern module index and check if there are any existing pattern modules that match our requirement. In this case, no pattern modules fit our needs. If this was a common pattern, we could open an issue on the AVM github repository to get assistance from the AVM project to create a pattern module matching our requirements. Since our architecture isn’t common, we’ll continue to the next step.
When a pattern module fitting our needs doesn’t exist for a solution, leveraging AVM resource modules to build our own solution is the next best option. Review the AVM Terraform published resource module index for each of the resource types included in your architecture. For each AVM module, capture a link to the module to allow for a review of the documentation details on the Terraform Registry website.
Note
Some of the published pattern modules cover multi-resource configurations that can sometimes be interpreted as a single resource. Be sure to check the pattern index for groups of resources that may be part of your architecture and that don’t exist in the resource module index. (e.g., Virtual WAN)
For our sample architecture, we have the following AVM resource modules at our disposal. Click on each module to explore its documentation on the Terraform Registry.
We can now begin coding our solution. We will create each element individually, to allow us to test our deployment as we build it out. This will also allow us to correct any bugs incrementally, so that we aren’t troubleshooting a large number of resources at the end.
Creating the terraform.tf file
Let’s begin by configuring the provider details necessary to build our solution. Since this is a root module, we want to include any provider and Terraform version constraints for this module. We’ll periodically come back and add any needed additional providers if our design includes a resource from a new provider.
Open up your development IDE (Visual studio code in our example) and create a file named terraform.tf in your root directory.
Always click on the “Copy to clipboard” button in the top right corner of the Code sample area in order not to have the line numbers included in the copied code.
This specifies that the required Terraform binary version to run your module can be any version between 1.9 and 2.0. This is a good compromise for allowing a range of binary versions while also ensuring support for any required features that are used as part of the module. This can include things like newly introduced functions or support for new key words.
Since we are developing our solution incrementally, we should validate our code. To do this, we will take the following steps:
Open up a terminal window if it is not already open. In some IDE’s this can be done as a function of the IDE.
Change directory to the module directory by typing cd and then the path to the module. As an example, if the module directory was named example we would run cd example.
Run terraform init to initialize your provider file.
You should now see a message indicating that Terraform has been successfully initialized. This indicates that our code is error free and we can continue on. If you get errors, examine the provider syntax for typos, missing quotes, or missing brackets.
Creating a variables.tf file
Because our module is intended to be reusable, we want to provide the capability to customize each module call with those items that will differ between them. This is done by using variables to accept inputs into the module. We’ll define these inputs in a separate file named variables.tf.
Go back to the IDE, and create a file named variables.tf in the working directory.
Add the following code to your variables.tf file to configure the inputs for our example:
β Expand Code
1variable"name_prefix" {
2description = "Prefix for the name of the resources" 3type = string 4default = "example" 5}
6 7variable"location" {
8description = "The Azure location to deploy the resources" 9type = string10default = "East US"11}
1213variable"virtual_network_cidr" {
14description = "The CIDR prefix for the virtual network. This should be at least a /22. Example 10.0.0.0/22"15type = string16}
1718variable"tags" {
19description = "Tags to be applied to all resources"20type = map(string)
21default = {}
22}
Note
Note that each variable definition includes a type definition to guide module users on how to properly define an input. Also note that it is possible to set a default value. This allows module consumers to avoid setting a value if they find the default to be acceptable.
We should now test the new content we’ve created for our module. To do this, first re-run terraform init on your command line. Note that nothing has changed and the initialization completes successfully. Since we now have module content, we will attempt to run the plan as the next step of the workflow.
Type terraform plan on your command line. Note that it now asks for us to provide a value for the var.virtual_network_cidr variable. This is because we don’t provide a default value for that input so Terraform must have a valid input before it can continue. Type 10.0.0.0/22 into the input and press enter to allow the plan to complete. You should now see a message indicating that Your infrastructure matches the configuration and that no changes are needed.
Creating a development.tfvars file
There are multiple ways to provide input to the module we’re creating. We will create a tfvars file that can be supplied during plan and apply stages to minimize the need for manual input. tfvars files are a nice way to document inputs as well as allow for deploying different versions of your module. This is useful if you have a pipeline where infrastructure code is deployed first for development, and then is deployed for QA, staging, or production with different input values.
In your IDE, create a new file named development.tfvars in your working directory.
Now add the following content to your development.tfvars file.
Note that each variable has a value defined. Although, only inputs without default values are required, we include values for all of the inputs for clarity. Consider doing this in your environments so that someone looking at the tfvars files has a full picture of what values are being set.
Re-run the terraform apply, but this time, reference the .tfvars file by using the following command: terraform plan -var-file=development.tfvars. You should get a successful completion without needing to manually provide inputs.
Creating the main.tf file
Now that we’ve created the supporting files, we can start building the actual infrastructure code in our main file. We will add one AVM resource module at a time so that we can test each as we implement them.
Return to your IDE and create a new file named main.tf.
Add a resource group
In Azure, we need a resource group to hold any infrastructure resources we create. This is a simple resource that typically wouldn’t require an AVM module, but we’ll include the AVM module so we can take advantage of the Role-Based Access Control (RBAC) interface if we need to restrict access to the resource group in future versions.
Note the Provision Instructions box on the right-hand side of the page. This contains the module source and version details which allows us to copy the latest version syntax without needing to type everything ourselves.
Now review the Readme tab in the middle of the page. It contains details about all required and optional inputs, resources that are created with the module, and any outputs that are defined. If you want to explore any of these items in detail, each element has a tab that you can review as needed.
Finally, in the middle of the page, there is a drop-down menu named Examples that contains functioning examples for the AVM module. These showcase a good example of using copy/paste to bootstrap module code and then modify it for your specific purpose.
Now that we’ve explored the registry content, let’s add a resource group to our module.
First, copy the content from the Provision Instructions box into our main.tf file.
β Expand Code
1module"avm-res-resources-resourcegroup" {
2source = "Azure/avm-res-resources-resourcegroup/azurerm"3version = "0.2.1"4 # insert the 2 required variables here
5}
On the modules documentation page, go to the inputs tab. Review the Required Inputs tab. These are the values that don’t have defaults and are the minimum required values to deploy the module. There are additional inputs in the Optional Inputs section that can be used to configure additional module functionality. Review these inputs and determine which values you would like to define in your AVM module call.
Now, replace the # insert the 2 required variables here comment with the following code to define the module inputs. Our main.tf code should look like the following:
Note how we’ve used the prefix variable and Terraform interpolation syntax to dynamically name the resource group. This allows for module customization and re-use. Also note that even though we chose to use the default module name of avm-res-resources-resourcegroup, we could modify the name of the module if needed.
After saving the file, we want to test our new content. To do this, return to the command line and first run terraform init. Notice how Terraform has downloaded the module code and its providers. Currently published modules in this solution still require AzureRM, while direct Azure resources should use AzAPI.
Let’s now deploy our resource group. First, let’s run a plan operation to review what will be created. Type terraform plan -var-file=development.tfvars and press enter to initiate the plan.
Configure the providers
Configure AzAPI explicitly and enable preflight validation. The published AVM modules used by this solution also require an AzureRM provider configuration. This is a dependency of those existing modules and does not permit direct AzureRM resources in a new AVM module repository.
Return to the terraform.tf file and add the following content:
Run terraform init -upgrade to install AzAPI and update the lock file, then re-run terraform plan -var-file=development.tfvars.
Select the subscription
AzAPI uses the active Azure authentication context. Confirm that Azure CLI is signed in to the subscription where the resources should be created.
First, we need to get the subscription ID value. We will use the portal for this exercise, but using the Azure CLI, PowerShell, or the resource graph will also work to retrieve this value.
Enter Subscriptions in the search field at the top middle of the page.
Select Subscriptions from the services menu in the search drop-down.
Select the subscription you wish to deploy to, from the list of subscriptions.
Find the Subscription ID field on the overview page and click the copy button to copy it to the clipboard.
Set the environment variable required by AzureRM v4 for the currently published AVM dependencies, then select the same subscription in Azure CLI:
$env:ARM_SUBSCRIPTION_ID = "<subscription-id>"az account set --subscription "<subscription-id>"az account show --query "{name:name,id:id}" --output table
Finally, we should now be able to complete our plan operation by re-running terraform plan -var-file=development.tfvars. Note that the plan will create three resources, two for telemetry and one for the resource group.
Deploy the resource group
We can complete testing by implementing the resource group. Run terraform apply -var-file="development.tfvars" and type yes and press enter when prompted to accept the changes. Terraform will create the resource group and notify you with a Apply complete message and a summary of the resources that were added, changed, and destroyed.
Deploy the Log Analytics Workspace
We can now continue by adding the Log Analytics Workspace to our main.tf file. We will follow a workflow similar to what we did with the resource group.
Copy the module content from the Provision Instructions portion of the page into the main.tf file.
This time, instead of manually supplying module inputs, we will copy module content from one of the examples to minimize the amount of typing required. In most examples, the AVM module call is located at the bottom of the example.
Navigate to the Examples drop-down menu in the documentation and select the default example from the menu. You will see a fully functioning example code which includes the module and any supporting resources. Since we only care about the workspace resource from this example, we can scroll to the bottom of the code block and find the module "log_analytics_workspace" line.
Copy the content between the module brackets with the exception of the line defining the module source. Because these examples are part of the testing methodology for the module, they use a dot reference value (../..) for the module source value which will not work in our module call. To work around this, we copied those values from the provision instructions section of the module documentation in a previous step.
Update the location and resource group name values to reference outputs from the resource group module. Using implicit references such as these allow Terraform to determine the order in which resources should be built.
Update the name field using the prefix variable to allow for customization using a similar pattern to what we used on the resource group.
The Log Analytics module content should look like the following code block. For simplicity, you can also copy this directly to avoid multiple copy/paste actions.
Again, we will need to run terraform init to allow Terraform to initialize a copy of the AVM Log Analytics module.
Now, we can deploy the Log Analytics workspace by running terraform apply -var-file="development.tfvars", typing yes and pressing enter. Note that Terraform will only create the new Log Analytics resources since the resource group already exists. This is one of the key benefits of deploying using Infrastructure as Code (IAC) tools like Terraform.
Note
Note that we ran the terraform apply command without first running terraform plan. Because terraform apply runs a plan before prompting for the apply, we opted to shorten the instructions by skipping the explicit plan step. If you are testing in a live environment, you may want to run the plan step and save the plan as part of your governance or change control processes.
Deploy the Azure Key Vault
Our solution calls for a simple Key Vault implementation to store virtual machine secrets. We’ll follow the same workflow for deploying the Key Vault as we used for the previous resource group and Log Analytics workspace resources. However, since Key Vaults require data roles to manage secrets and keys, we will need to use the RBAC interface and a data resource to configure Role-Based Access Control (RBAC) during the deployment.
Note
For this exercise, we will provision the deployment user with data rights on the Key Vault. In your environment, you will likely want to either provide additional roles as inputs or statically assign users, or groups to the Key Vault data roles. For simplicity we also set the Key Vault to have public access enabled due to us not being able to dictate a private deployment environment. In your environment where your deployment machine will be on a private network it is recommended to restrict public access for the Key Vault.
Before we implement the AVM module for the Key Vault, we want to use a data resource to read the client details about the user context of the current Terraform deployment.
Add the following line to your main.tf file and save it.
Key vaults use a global namespace which means that we will also need to add a randomization resource to allow us to randomize the name to avoid any potential name intersection issues with other Key Vault deployments. We will use Terraform’s random provider to generate the random string which we will append to the Key Vault name. Add the following code to your main module to create the random_string resource we will use for naming.
Copy the module content from the Provision Instructions portion of the page into the main.tf file.
This time, we’re going to select relevant content from the Create secret example to fill out our module.
Copy the name, location, enable_telemetry, resource_group_name, tenant_id, and role_assignments value content from the example and paste it into the new Key Vault module in your solution.
Update the name value to be "${var.prefix}-kv-${random_string.name_suffix.result}"
Update the location and resource_group_name values to the same implicit resource group module references we used in the Log Analytics workspace.
Set the enable_telemetry value to true.
Leave the tenant_id and role_assignments values to the same values that are in the example.
Our architecture calls for us to include a diagnostic settings configuration for each resource that supports it. We’ll use the diagnostic-settings example to copy this content.
Return to the documentation page and select the diagnostic-settings option from the examples drop-down.
Locate the Key Vault resource in the example’s code block and copy the diagnostic_settings value and paste it into the Key Vault module block we’re building in main.tf.
Update the name value to use our prefix variable to allow for name customization.
Update the workspace_resource_id value to be an implicit reference to the output from the previously implemented Log Analytics module (module.avm-res-operationalinsights-workspace.resource_id in our code).
Finally, we will allow public access, so that our deployer machine can add secrets to the Key Vault. If your environment doesn’t allow public access for Key Vault deployments, locate the public IP address of your deployer machine (this may be an external NAT IP for your network) and add it to the network_acls.ip_rules list value using CIDR notation.
Set the network_acls input to null in your module block for the Key Vault.
Your Key Vault module definition should now look like the following:
One of the core values of AVM is the standard configuration for interfaces across modules. The Role Assignments interface we used as part of the Key Vault deployment is a good example of this.
Continue the incremental testing of your module by running another terraform init and terraform apply -var-file="development.tfvars" sequence.
Deploy the NAT Gateway
Our architecture calls for a NAT Gateway to allow virtual machines to access the internet. We will use the NAT Gateway resource_id output in future modules to link the virtual machine subnet.
Copy the module definition and source from the Provision Instructions card from the module main page.
Copy the remaining module content from the default example excluding the subnet associations map, as we will do the association when we build the vnet.
Update the location and resource_group_nameusing implicit references from our resource group module.
Then update each of the name values to use the name_prefix variables.
Review the following code to see each of these changes.
Continue the incremental testing of your module by running another terraform init and terraform apply -var-file="development.tfvars" sequence.
Deploy the Network Security Group
Our architecture calls for a Network Security Group (NSG) allowing SSH access to the virtual machine subnet. We will use the NSG AVM resource module to accomplish this task.
Copy the module definition and source from the Provision Instructions card from the module main page.
Copy the remaining module content from the example_with_NSG_rule example.
Update the location and resource_group_nameusing implicit references from our resource group module.
Update the name value using the name_prefix variable interpolation as we did with the other modules.
Copy the map entry labeled rule02 from the locals nsg_rules map and paste it between two curly braces to create the security_rules attribute in the NSG module we’re building.
Make the following updates to the rule details:
Rename the map key to "rule01" from "rule02".
Update the name to use the var.prefix interpolation and SSH to describe the rule.
Update the destination_port_ranges list to be ["22"].
Upon completion the code for the NSG module should be as follows:
Continue the incremental testing of your module by running another terraform init and terraform apply -var-file="development.tfvars" sequence.
Deploy the Virtual Network
We can now continue the build-out of our architecture by configuring the virtual network (vnet) deployment. This will follow a similar pattern as the previous resource modules, but this time, we will also add some network functions to help us customize the subnet configurations.
Copy the module definition and source from the Provision Instructions card from the module main page.
After looking through the examples, this time, we’ll use the complete example as a source to copy our content.
Copy the resource_group_name, location, name, and address_space lines and replace their values with our deployment specific variables or module references.
We’ll copy the subnets map and duplicate the subnet0 map for each subnet.
Now we will update the map key and name values for each subnet so that they are unique.
Then we’ll use the cidrsubnet function to dynamically generate the CIDR range for each subnet. You can explore the function documentation for more details on how it can be used.
We will also populate the nat_gateway object on subnet0 with the resource_id output from our NAT Gateway module.
To configure the NSG on the VM subnet we need to link it. Add a network_security_group attribute to the subnet0 definition and replace the value with the resource_id output from the NSG module.
Finally, we’ll copy the diagnostic settings from the example and update the implicit references to point to our previously deployed Log Analytics workspace.
After making these changes our virtual network module call code will be as follows:
Note how the Log Analytics workspace reference ends in resource_id. Each AVM module is required to export its Azure resource ID with the resource_id name to allow for consistent references.
Continue the incremental testing of your module by running another terraform init and terraform apply -var-file="development.tfvars" sequence.
Deploy the Bastion service
We want to allow for secure remote access to the virtual machine for configuration and troubleshooting tasks. We’ll use Azure Bastion to accomplish this objective following a similar workflow to our other resources.
Copy the module definition and source from the Provision Instructions card from the module main page.
Copy the remaining module content from the Simple Deployment example.
Update the location and resource_group_nameusing implicit references from our resource group module.
Update the name value using the name_prefix variable interpolation as we did with the other modules.
Finally, update the subnet_id value to include an implicit reference to the bastion keyed subnet from our virtual network module.
Our architecture calls for diagnostic settings to be configured on the Azure Bastion resource. In this case, there aren’t any examples that include this configuration. However, since the diagnostic settings interface is one of the standard interfaces in Azure Verified Modules, we can just copy the interface definition from our virtual network module.
Locate the virtual network module and copy the diagnostic_settings value from it.
Paste the diagnostic_settings value into the code for our Bastion module.
Update the diagnostic setting’s name value from vnet to Bastion.
The new code we added for the Bastion resource will be as follows:
Pay attention to the subnet_id syntax. In the virtual network module, the subnets are created as a sub-module allowing us to reference each of them using the map key that was defined in the subnets input. Again, we see the consistent output naming with the resource_id output for the sub-module.
Continue the incremental testing of your module by running another terraform init and terraform apply -var-file="development.tfvars" sequence.
Deploy the virtual machine
The final step in our deployment will be our application virtual machine. We’ve had good success with our workflow so far, so we’ll use it for this step as well.
Copy the module definition and source from the Provision Instructions card from the module main page.
Copy the remaining module content from the linux_default example.
Update the location and resource_group_nameusing implicit references from our resource group module.
To be compliant with Well Architected Framework guidance we encourage defining a zone if your region supports it. Update the zone input to 1.
Update the sku_size input to “Standard_D2s_v5”.
Update the name values using the name_prefix variable interpolation as we did with the other modules and include the output from the random_string.name_suffix resource to add uniqueness.
Set the account_credentials.key_vault_configuration.resource_id value to reference the resource_id output from the Key Vault module.
Update the private_ip_subnet_resource_id value to an implicit reference to the subnet0 subnet output from the virtual network module.
Because the default Linux example doesn’t include diagnostic settings, we need to add that content in a different way. Since the diagnostic settings interface has a standard schema, we can copy the diagnostic_settings input from our virtual network module.
Locate the virtual network module in your code and copy the diagnostic_settings map from it.
Paste the diagnostic_settings content into your virtual machine module code.
Update the name value to reflect that it applies to the virtual machine.
The new code we added for the virtual machine resource will be as follows:
Continue the incremental testing of your module by running another terraform init and terraform apply -var-file="development.tfvars" sequence.
Creating the outputs.tf file
The final piece of our module is to export any values that may need to be consumed by module users. From our architecture, we’ll export the resource group name and the virtual machine resource name.
Create an outputs.tf file in your IDE.
Create an output named resource_group_name and set the value to an implicit reference to the resource group modules name output. Include a brief description for the output.
Create an output named virtual_machine_name and set the value to an implicit reference to the virtual machine module’s name output. Include a brief description for the output.
The new code we added for the outputs will be as follows:
β Expand Code
1output"resource_group_name" {
2value = module.avm-res-resources-resourcegroup.name3description = "The resource group name where the resources are deployed"4}
56output"virtual_machine_name" {
7value = module.avm-res-compute-virtualmachine.name8description = "The name of the virtual machine"9}
Because no new modules were created, we don’t need to run terraform init to test this change. Run terraform apply -var-file="development.tfvars" to see the new outputs that have been created.
Update the terraform.tf file
It is a recommended practice to define the required versions of the providers for your module to ensure consistent behavior when it is being run. In this case we are going to be slightly permissive and allow increases in minor and patch versions to fluctuate, since those are not supposed to include breaking changes. In a production environment, you would likely want to pin on a specific version to guarantee behavior.
Run terraform init to review the providers and versions that are currently installed.
Update your terraform.tf file’s required providers field for each provider listed in the downloaded providers.
The updated code we added for the providers in the terraform.tf file will be as follows:
Congratulations on successfully implementing a solution using Azure Verified Modules! You were able to build out our sample architecture using module documentation and taking advantage of features like standard interfaces and pre-defined defaults to simplify the development experience.
Note
This was a long exercise and mistakes can happen. If you’re getting errors or a resource is incomplete and you want to see the final main.tf, expand the following code block to see the full file.
AVM modules provide several key advantages over writing raw Terraform templates:
Simplified Resource Configuration: AVM modules handle much of the complex configuration work behind the scenes
Built-in Recommended Practices: The modules implement many of Microsoft’s recommended practices by default
Consistent Outputs: Each module exposes a consistent set of outputs that can be easily referenced
Reduced Boilerplate Code: What would normally require hundreds of lines of Terraform code can be accomplished in a fraction of the space
As you continue your journey with Azure and AVM, remember that this approach can be applied to more complex architectures as well. The modular nature of AVM allows you to mix and match components to build solutions that meet your specific needs while adhering to Microsoft’s Well-Architected Framework.
By using AVM modules as building blocks, you can focus more on your solution architecture and less on the intricacies of individual resource configurations, ultimately leading to faster development cycles and more reliable deployments.
Additional exercises
For additional learning, it can be helpful to experiment with modifying this solution. Here are some ideas you can try if you have time and would like to experiment further.
Use the managed_identities interface to add a system assigned managed identity to the virtual machine and give it Key Vault Administrator rights on the Key Vault.
Use the tags interface to assign tags directly to one or more resources.
Add an Azure Monitoring Agent extension to the virtual machine resource.
Add additional inputs like VM sku to your module to make it more customizable. Be sure to update the code and tfvars files to match.
Clean up your environment
Once you have completed this set of exercises, it is a good idea to clean up your resources to avoid incurring costs for them. This can be done typing terraform destroy -var-file=development.tfvars and entering yes when prompted.
Solution Development
Considerations and steps of Solution Development
Decide on the IaC language (Bicep or Terraform)
Decide on the module sourcing method (public registry, private registry, inner-sourcing)
Decide on the orchestration method (template or pipeline)
Identify the resources needed for the solution (are they all available in AVM?)
Implement, validate, deploy, test the solution
Questions to cover on this page
Pick a realistically complex solution and demonstrate how to build it using AVM modules
Best practices for coding (link to official language specific guidance AND AVM specs where/if applicable)
Best practices for input and output parameters
Next steps
To be covered in separate, future articles.
To make this solution enterprise-ready, you need to consider the following:
Deploy with DevOps tools and practices (e.g., CI/CD in Azure DevOps, GitHub Actions, etc.)
Deploy into Azure Landing Zones (ALZ)
Make sure the solution follows the recommendations of the Well-Architected Framework (WAF) and it’s compliant with and integrates into your organization’s policies and standards, e.g.:
Don’t use latest, but a specific version of the module
Don’t expose secrets in output parameters/command line/logs/etc.
Don’t use hard-coded values, but use parameters and variables
Quickstart Guide
This QuickStart guide offers step-by-step instructions for integrating Azure Verified Modules (AVM) into your solutions. It includes the initial setup, essential tools, and configurations required to deploy and manage your Azure resources efficiently using AVM.
The AVM Key Vault resource module, used as an example in this chapter, simplifies the deployment and management of Azure Key Vaults, ensuring secure storage and access to your secrets, keys, and certificates.
Leveraging Azure Verified Modules
Using AVM ensures that your infrastructure-as-code deployments follow Microsoft’s best practices and guidelines, providing a consistent and reliable foundation for your cloud solutions. AVM helps accelerate your development process, reduce the risk of misconfigurations, and enhance the security and compliance of your applications.
Using default values
The default values provided by AVM are generally safe, as they follow best practices and ensure a secure and reliable setup. However, it is important to review these values to ensure they meet your specific requirements and compliance needs. Customizing the default values may be necessary to align with your organization’s policies and the specific needs of your solution.
Exploring examples and module features
You can find examples and detailed documentation for each AVM module in their respective code repository’s README.MD file, which details features, input parameters, and outputs. The module’s documentation also provides comprehensive usage examples, covering various scenarios and configurations. Additionally, you can explore the module’s source code repository. This information will help you understand the full capabilities of the module and how to effectively integrate it into your solutions.
Subsections of Quickstart
Bicep Quickstart Guide
Introduction
This guide explains how to use an Azure Verified Modules (AVM) in your Bicep workflow. By leveraging AVM modules, you can rapidly deploy and manage Azure infrastructure without having to write extensive code from scratch.
In this guide, you will deploy a Key Vault resource and a Personal Access Token as a secret.
This article is intended for a typical ‘infra-dev’ user (cloud infrastructure professional) who has a basic understanding of Azure and Bicep but is new to Azure Verified Modules and wants to learn how to deploy a module in the easiest way using AVM.
Make sure you have these tools set up before proceeding.
Module Discovery
Find your module
In this scenario, you need to deploy a Key Vault resource and some of its child resources, such as a secret. Let’s find the AVM module that will help us achieve this.
There are two primary ways for locating published Bicep Azure Verified Modules:
Option 1 (preferred): Using IntelliSense in the Bicep extension of Visual Studio Code, and
Start typing module, then give your module a symbolic name, such as myModule.
Use IntelliSense to select br/public.
The list of all AVM modules published in the Bicep Public Registry will show up. Use this to explore the published modules.
Note
The Bicep VSCode extension is reading metadata through this JSON file. All modules are added to this file, as part of the publication process. This lists all the modules marked as Published or Orphaned on the AVM Bicep module index pages.
Select the module you want to use and the version you want to deploy. Note how you can type full or partial module names to filter the list.
Right click on the module’s path and select Go to definition or hit F12 to see the module’s source code. You can toggle between the Bicep and the JSON view.
Hover over the module’s symbolic name to view its documentation URL. By clicking on it, you will be directed to the module’s GitHub folder in the bicep-registry-modules (BRM) repository. There, you can access the source code and documentation, as illustrated below.
Option 2: Use the AVM Bicep Module Index
Searching the Azure Verified Modules indexes is the most complete way to discover published as well as planned (proposed) modules. As shown in the video above, use the following steps to locate a specific module on the AVM website:
Expand the Module Indexes menu item and select the Bicep sub-menu item.
Select the menu item for the module type you are searching for: Resource, Pattern, or Utility.
Note
Since the Key Vault module used as an example in this guide is published as an AVM resource module, it can be found under the resource modules section in the AVM Bicep module index.
A detailed description of module classification types can be found under the related section here.
Select the Published modules link from the table of contents at the top of the page.
Use the in-page search feature of your browser. In most Windows browsers you can access it using the CTRL + F keyboard shortcut.
Enter a search term to find the module you are looking for - e.g., Key Vault.
Move through the search results until you locate the desired module. If you are unable to find a published module, return to the table of contents and expand the All modules link to search both published and proposed modules - i.e., modules that are planned, likely in development but not published yet.
In the module’s documentation, you can find detailed information about the module’s functionality, components, input parameters, outputs and more. The documentation also provides comprehensive usage examples, covering various scenarios and configurations.
Explore the Key Vault module’s documentation for usage examples and to understand its functionality, input parameters, and outputs.
Note the mandatory and optional parameters in the Parameters section.
Review the Usage examples section. AVM modules include multiple tests that can be found under the tests folder. These tests are also used as the basis of the usage examples ensuring they are always up-to-date and deployable.
In this example, you will deploy a secret in a new Key Vault instance with minimal input. AVM provides default parameter values with security and reliability being core principles. These settings apply the recommendations of the Well Architected Framework where possible and appropriate.
Note how Example 2 does most of what you need to achieve.
Create your new solution using AVM
In this section, you will develop a Bicep template that references the AVM Key Vault module and its child resources and features. These include secret and role based access control configurations that grant permissions to a user.
Start VSCode (make sure the Bicep extension is installed) and open a folder in which you want to work.
Create a main.bicep and a dev.bicepparam file, which will hold parameters for your Key Vault deployment.
Copy the content below into your main.bicep file. We have included comments to distinguish between the two different occurrences of the names attribute.
module myKeyVault 'br/public:avm/res/key-vault/vault:0.11.0' = {
name: // the name of the module's deployment params: {
name: '<keyVaultName>'// the name of the Key Vault instance - length and character limits apply }
}
Note
For Azure Key Vaults, the name must be globally unique. When you deploy the Key Vault, ensure you select a name that is alphanumeric, twenty-four characters or less, and unique enough to ensure no one else has used the name for their Key Vault. If the name has been previously taken, you will get an error.
After setting the values for the required properties, the module can be deployed. This minimal configuration automatically applies the security and reliability recommendations of the Well Architected Framework where possible and appropriate. These settings can be overridden if needed.
Bicep-specific configuration
It is recommended to create a bicepconfig.json file, and enable use-recent-module-versions, which warns you to use the latest available version of the AVM module.
// This is a Bicep configuration file. It can be used to control how Bicep operates and to customize
// validation settings for the Bicep linter. The linter relies on these settings when evaluating your
// Bicep files for best practices. For further information, please refer to the official documentation at:
// https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/bicep-config
{
"analyzers": {
"core": {
"rules": {
"use-recent-module-versions": {
"level": "warning",
"message": "The module version is outdated. Please consider updating to the latest version." }
}
}
}
}
Define the Key Vault instance
In this scenario - and every other real-world setup - there is more that you need to configure. You can open the module’s documentation by hovering over its symbolic name to see all of the module’s capabilities - including supported parameters.
Note
The Bicep extension facilitates code-completion, enabling you to easily locate and utilize the Azure Verified Module. This feature also provides the necessary properties for a module, allowing you to begin typing and leverage IntelliSense for completion.
Add parameters and values to the main.bicep file to customize your configuration. These parameters are used for passing in the Key Vault name and enabling purge protection. You might not want to enable the latter in a non-production environment, as it makes it harder to delete and recreate resources.
The main.bicep file will now look like this:
// the scope, the deployment deploys resources totargetScope = 'resourceGroup'// parameters and default valuesparam keyVaultName string
@description('Disable for development deployments.')
param enablePurgeProtection bool = true// the resources to deploymodule myKeyVault 'br/public:avm/res/key-vault/vault:0.11.0' = {
name: 'key-vault-deployment' params: {
name: keyVaultName
enablePurgeProtection: enablePurgeProtection
// more properties are not needed, as AVM provides default values }
}
Note that the Key Vault instance will be deployed within a resource group scope in our example.
Create a dev.bicepparam file (this is optional) and set parameter values for your environment. You can now pass these values by referencing this file at the time of deployment (using PowerShell or Azure CLI).
using'main.bicep'// environment specific valuesparam keyVaultName = '<keyVaultName>'param enablePurgeProtection = false
Create a secret and set permissions
Add a secret to the Key Vault instance and grant permissions to a user to work with the secret. Sample role assignments can be found in Example 3: Using large parameter set. See Parameter: roleAssignments for a list of pre-defined roles that you can reference by name instead of a GUID. This is a key benefit of using AVM, as the code is easy to read and increases the maintainability.
You can also leverage User-defined data types and simplify the parameterization of the modules instead of guessing or looking up parameters. Therefore, first import UDTs from the Key Vault and common types module and leverage the UDTs in your Bicep and parameter files.
For a role assignment, the principal ID is needed, that will be granted a role (specified by its name) on the resource. Your own ID can be found out with az ad signed-in-user show --query id.
// the scope, the deployment deploys resources totargetScope = 'resourceGroup'// parameters and default valuesparam keyVaultName string
// the PAT token is a secret and should not be stored in the Bicep(parameter) file.// It can be passed via the commandline, if you don't use a parameter file.@secure()
param patToken string = newGuid()
@description('Enabled by default. Disable for development deployments')
param enablePurgeProtection bool = trueimport { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:0.4.0'// the role assignments are optional in the Key Vault moduleparam roleAssignments roleAssignmentType[]?
// the resources to deploymodule myKeyVault 'br/public:avm/res/key-vault/vault:0.11.0' = {
name: 'key-vault-deployment' params: {
name: keyVaultName
enablePurgeProtection: enablePurgeProtection
secrets: [
{
name: 'PAT' value: patToken
}
]
roleAssignments: roleAssignments
}
}
The secrets parameter references a UDT (User-defined data type) that is part of the Key Vault module and enables code completion for easy usage. There is no need to look up what attributes the secret object might have. Start typing and tab-complete what you need from the content offered by the Bicep extension’s integration with AVM.
The bicep parameter file now looks like this:
// reference to the Bicep file to set the contextusing'main.bicep'// environment specific valuesparam keyVaultName = '<keyVaultName>'param enablePurgeProtection = false// for security reasons, the secret value must not be stored in this file.// You can change it later in the deployed Key Vault instance, where you also renew it after expiration.param roleAssignments = [
{
principalId: '<principalId>'// using the name of the role instead of looking up the GUID (which can also be used) roleDefinitionIdOrName: 'Key Vault Secrets Officer' }
]
Note
The display names for roleDefinitionIdOrName can be acquired the following two ways:
From the builtInRoleNames variable in the module’s source code. To get there, hit F12 while the cursor is on the part of the module path starting with br/public:.
Boost your development with VS Code IntelliSense
Leverage the IntelliSense feature in VS Code to speed up your development process. IntelliSense provides code completion, possible parameter values and structure. It helps you write code more efficiently by providing context-aware suggestions as you type.
Here is how quickly you can deliver the solution detailed in this section:
Deploy your solution
Now that your template and parameter file is ready, you can deploy your solution to Azure. Use PowerShell or the Azure CLI to deploy your solution.
Deploy with
# Log in to AzureConnect-AzAccount
# Select your subscriptionSet-AzContext -SubscriptionId '<subscriptionId>'# Deploy a resource groupNew-AzResourceGroup -Name 'avm-quickstart-rg' -Location 'germanywestcentral'# Invoke your deploymentNew-AzResourceGroupDeployment -DeploymentName 'avm-quickstart-deployment' -ResourceGroupName 'avm-quickstart-rg' -TemplateParameterFile 'dev.bicepparam' -TemplateFile 'main.bicep'
# Log in to Azureaz login
# Select your subscriptionaz account set --subscription '<subscriptionId>'# Deploy a resource groupaz group create --name 'avm-quickstart-rg' --location 'germanywestcentral'# Invoke your deploymentaz deployment group create --name 'avm-quickstart' --resource-group 'avm-quickstart-rg' --template-file 'main.bicep' --parameters 'dev.bicepparam'
Use the Azure portal, Azure PowerShell, or the Azure CLI to verify that the Key Vault instance and secret have been successfully created with the correct configuration.
Clean up your environment
When you are ready, you can remove the infrastructure deployed in this example. The following commands will remove all resources created by your deployment:
Clean up with
# Delete the resource groupRemove-AzResourceGroup -Name "avm-quickstart-rg" -Force
# Purge the Key VaultRemove-AzKeyVault -VaultName "<keyVaultName>" -Location "germanywestcentral" -InRemovedState -Force
# Delete the resource groupaz group delete --name 'avm-quickstart-rg' --yes --no-wait
# Purge the Key Vaultaz keyvault purge --name '<keyVaultName>' --no-wait
Congratulations, you have successfully leveraged an AVM Bicep module to deploy resources in Azure!
Tip
We welcome your contributions and feedback to help us improve the AVM modules and the overall experience for the community!
This guide explains how to use an Azure Verified Modules (AVM) in your Terraform workflow. With AVM modules, you can quickly deploy and manage Azure infrastructure without writing extensive code from scratch.
In this guide, you will deploy a Key Vault resource and generate and store a key.
This article is intended for a typical ‘infra-dev’ user (cloud infrastructure professional) who is new to Azure Verified Modules and wants to learn how to deploy a module in the easiest way using AVM. The user has a basic understanding of Azure and Terraform.
Before you begin, ensure you have these tools installed in your development environment.
Module Discovery
Find your module
In this scenario, you need to deploy a Key Vault resource and some of its child resources, such as a key. Let’s find the AVM module that will help us achieve this.
There are two primary ways for locating published Terraform Azure Verified Modules:
The easiest way to find published AVM Terraform modules is by searching the Terraform Registry. Follow these steps to locate a specific module, as shown in the video above.
In the search bar at the top of the screen type avm. Optionally, append additional search terms to narrow the search results. (e.g., avm key vault for AVM modules with Key Vault in the name.)
Select see all to display the full list of published modules matching your search criteria.
Find the module you wish to use and select it from the search results.
Note
It is possible to discover other unofficial modules with avm in the name using this search method. Look for the Partner tag in the module title to determine if the module is part of the official set.
Use the AVM Terraform Module Index
Searching the Azure Verified Modules indexes is the most complete way to discover published as well as planned modules - shown as proposed. As presented in the video above, use the following steps to locate a specific module on the AVM website:
Expand the Module Indexes menu item and select the Terraform sub-menu item.
Select the menu item for the module type you are searching for: Resource, Pattern, or Utility.
Note
Since the Key Vault module used as an example in this guide is published as an AVM resource module, it can be found under the resource modules section in the AVM Terraform module index.
A detailed description of each module classification type can be found under the related section here.
Select the Published modules link from the table of contents at the top of the page.
Use the in-page search feature of your browser (in most Windows browsers you can access it using the CTRL + F keyboard shortcut).
Enter a search term to find the module you are looking for - e.g., Key Vault.
Move through the search results until you locate the desired module. If you are unable to find a published module, return to the table of contents and expand the All modules link to search both published and proposed modules - i.e., modules that are planned, likely in development but not published yet.
After finding the desired module, click on the module’s name. This link will lead you to the official HashiCorp Terraform Registry page for the module where you can find the module’s documentation and examples.
Module details and examples
Once you have identified the AVM module in the Terraform Registry you can find detailed information about the module’s functionality, components, input parameters, outputs and more. The documentation also provides comprehensive usage examples, covering various scenarios and configurations.
Explore the Key Vault module’s documentation and usage examples to understand its functionality, input variables, and outputs.
Note the Examples drop-down list and explore each example
Review the Readme tab to see module provider minimums, a list of resources and data sources used by the module, a nicely formatted version of the inputs and outputs, and a reference to any submodules that may be called.
Explore the Inputs tab and observe how each input has a detailed description and a type definition for you to use when adding input values to your module configuration.
Explore the Outputs tab and review each of the outputs that are exported by the AVM module for use by other modules in your deployment.
Finally, review the Resources tab to get a better understanding of the resources defined in the module.
In this example, you will deploy a secret in a new Key Vault instance without needing to provide other parameters. The AVM Key Vault resource module provides these capabilities and does so with security and reliability being core principles. The default settings of the module also apply the recommendations of the Well Architected Framework where possible and appropriate.
Note how the create-key example seems to do what you need to achieve.
Create your new solution using AVM
Now that you have found the module details, you can use the content from the Terraform Registry to speed up your development in the following ways:
Option 1: Create a solution using AVM module examples: duplicate a module example and edit it for your needs. This is useful if you are starting without any existing infrastructure and need to create supporting resources like resource groups as part of your deployment.
Option 2: Create a solution by changing the AVM module input values: add the AVM module to an existing solution that already includes other resources. This method requires some knowledge of the resource(s) being deployed so that you can make choices about optional features configured in your solution’s version of the module.
Each deployment method includes a section below so that you can choose the method which best fits your needs.
Note
For Azure Key Vaults, the name must be globally unique. When you deploy the Key Vault, ensure you select a name that is alphanumeric, twenty-four characters or less, and unique enough to ensure no one else has used the name for their Key Vault. If the name has been used previously, you will get an error.
Option 1: Create a solution using AVM module examples
Leverage the following steps as a template for how to leverage examples for bootstrapping your new solution code. The Key Vault resource module is used here as an example, but in practice you may choose any module that applies to your scenario.
Locate and select the Examples drop down menu in the middle of the Key Vault module page.
From the drop-down list select an example whose name most closely aligns with your scenario - e.g., create-key.
When the example page loads, read the example description to determine if this is the desired example. If it is not, return to the module main page, and select a different example until you are satisfied that the example covers the scenario you are trying to deploy. If you are unable to find a suitable example, leverage the last two steps in the option 2 instructions to modify the inputs of the selected example to match your requirements.
Scroll to the code block for the example and select the Copy button on the top right of the block to copy the content to the clipboard.
β Click here to copy the sample code from the video.
provider"azapi" {}
terraform {
required_version = "~> 1.9"required_providers {
azapi = {
source = "Azure/azapi"version = "~> 2.9" }
http = {
source = "hashicorp/http"version = "~> 3.4" }
random = {
source = "hashicorp/random"version = "~> 3.5" }
}
}
module"regions" {
source = "Azure/avm-utl-regions/azure"version = "0.5.0"}# This allows us to randomize the region for the resource group.
resource"random_integer""region_index" {
max = length(module.regions.regions) -1min = 0}
data"azapi_client_config""current" {}# Deploy the resource group via the AVM resource module.
module"resource_group" {
source = "Azure/avm-res-resources-resourcegroup/azure"name = "<your-resource-group-name>"location = module.regions.regions[random_integer.region_index.result].name}# Get current IP address for use in KV firewall rules
data"http""ip" {
url = "https://api.ipify.org/"retry {
attempts = 5max_delay_ms = 1000min_delay_ms = 500 }
}
module"key_vault" {
source = "Azure/avm-res-keyvault-vault/azure"name = "<your-keyvault-name>"location = module.resource_group.resource.locationenable_telemetry = var.enable_telemetryparent_id = module.resource_group.resource_idtenant_id = data.azapi_client_config.current.tenant_idpublic_network_access_enabled = truekeys = {
cmk_for_storage_account = {
key_opts = [
"decrypt",
"encrypt",
"sign",
"unwrapKey",
"verify",
"wrapKey" ]
key_type:"RSA"name = "cmk-for-storage-account"key_size = 2048 }
}
role_assignments = {
deployment_user_kv_admin = {
role_definition_id_or_name = "Key Vault Administrator"principal_id = data.azapi_client_config.current.object_id }
}
wait_for_rbac_before_key_operations = {
create = "60s" }
network_acls = {
bypass = "AzureServices"ip_rules = ["${data.http.ip.response_body}/32"]
}
}
In your IDE - Visual Studio Code in our example - create the main.tf file for your new solution.
Paste the content from the clipboard into main.tf.
AVM examples frequently use naming and/or region selection AVM utility modules to generate deployment region and/or naming values as well as any default values for required fields. If you want to use a specific region name or other custom resource values, remove the existing region and naming module calls and replace example input values with the new desired custom input values.
Once supporting resources such as resource groups have been modified, locate the module call for the AVM module - i.e., module "keyvault".
AVM module examples use dot notation for a relative reference that is useful during module testing. However, you will need to replace the relative reference with a source reference that points to the Terraform Registry source location. In most cases, this source reference has been left as a comment in the module example to simplify replacing the existing source dot reference. Perform the following two actions to update the source:
Delete the existing source definition that uses a dot reference - i.e., source = "../../".
Uncomment the Terraform Registry source reference by deleting the # sign at the start of the commented source line - i.e., source = "Azure/avm-res-keyvault-vault/azure".
Note
If the module example does not include a commented Terraform Registry source reference, you will need to copy it from the module’s main documentation page. Use the following steps to do so:
Use the breadcrumbs to leave the example documentation and return to the module’s primary Terraform Registry documentation page.
Locate the Provision Instructions box on the right side of the module’s Terraform Registry page in your web browser.
Select the second line that starts with source = from the code block - e.g., source = "Azure/avm-res-keyvault-vault/azure". Copy it onto the clipboard.
Return to your code solution and Paste the clipboard’s content where you previously deleted the source dot reference - e.g., source = "../../".
AVM module examples use a variable to enable or disable the telemetry collection. Update the enable_telemetry input value to true or false. - e.g. enable_telemetry = true
Save your main.tf file changes and then proceed to the guide section for running your solution code.
Option 2: Create a solution by changing the AVM module input values
Click here to copy the sample code from the video.
Use the following steps as a guide for the custom implementation of an AVM Module in your solution code. This instruction path assumes that you have an existing Terraform file that you want to add the AVM module to.
Locate the Provision Instructions box on the right side of the module’s Terraform Registry page in your web browser.
Select the module template code from the code block and Copy it onto the clipboard.
Switch to your IDE and Paste the contents of the clipboard into your solution’s .tf Terraform file - main.tf in our example.
Return to the module’s Terraform Registry page in the browser and select the Inputs tab.
Review each input and add the inputs with the desired target value to the solution’s code - i.e., name = "custom_name".
Once you are satisfied that you have included all required inputs and any optional inputs, Save your file and continue to the next section.
Deploy your solution
After completing your solution development, you can move to the deployment stage. Follow these steps for a basic Terraform workflow:
Open the command line and login to Azure using the Azure cli
azlogin
If your account has access to multiple tenants, you may need to modify the command to az login --tenant <tenant id> where “<tenant id>” is the guid for the target tenant.
After logging in, select the target subscription from the list of subscriptions that you have access to.
Change the path to the directory where your completed terraform solution files reside.
Note
AVM Terraform modules use the AzAPI provider, which expects an authenticated Azure context (provided by az login above) and reads the active subscription from your environment. If you need to target a specific subscription, set ARM_SUBSCRIPTION_ID to its GUID. For Unix based systems (Linux or MacOS) you can configure this by running export ARM_SUBSCRIPTION_ID=<your subscription guid> on the command line. On Microsoft Windows, you can perform the same operation by running set ARM_SUBSCRIPTION_ID="<your subscription guid>" from the Windows command prompt or by running $env:ARM_SUBSCRIPTION_ID="<your subscription guid>" from a powershell prompt. Replace the “<your subscription id>” notation in each command with your Azure subscription’s unique id value.
Initialize your Terraform project. This command downloads the necessary providers and modules to the working directory.
terraforminit
Before applying the configuration, it is good practice to validate it to ensure there are no syntax errors.
terraformvalidate
Create a deployment plan. This step shows what actions Terraform will take to reach the desired state defined in your configuration.
terraformplan
Review the plan to ensure that only the desired actions are in the plan output.
Apply the configuration and create the resources defined in your configuration file. This command will prompt you to confirm the deployment prior to making changes. Type yes to create your solution’s infrastructure.
terraformapply
Info
If you are confident in your changes, you can add the -auto-approve switch to bypass manual approval: terraform apply -auto-approve
Once the deployment completes, validate that the infrastructure is configured as desired.
Info
A local terraform.tfstate file and a state backup file have been created during the deployment. The use of local state is acceptable for small temporary configurations, but production or long-lived installations should use a remote state configuration where possible. Configuring remote state is out of scope for this guide, but you can find details on using an Azure storage account for this purpose in the Microsoft Learn documentation.
Clean up your environment
When you are ready, you can remove the infrastructure deployed in this example. Use the following command to delete all resources created by your deployment:
terraformdestroy
Note
Most Key Vault deployment examples activate soft-delete functionality as a default. The terraform destroy command will remove the Key Vault resource but does not purge a soft-deleted vault. You may encounter errors if you attempt to re-deploy a Key Vault with the same name during the soft-delete retention window. If you wish to purge the soft-delete for this example you can run az keyvault purge -n <keyVaultName> -l <regionName> using the Azure CLI, or Remove-AzKeyVault -VaultName "<keyVaultName>" -Location "<regionName>" -InRemovedState using Azure PowerShell.
Congratulations, you have successfully leveraged Terraform and AVM to deploy resources in Azure!
Tip
We welcome your contributions and feedback to help us improve the AVM modules and the overall experience for the community!
The “Module Specifications” section uses tags to dynamically render content based on the selected attributes, such as the IaC language, module classification, category, severity and more. The tags are defined in header of each specification page.
To make it easier for module owners and contributors to navigate the documentation, the specifications are grouped to distinct pages by the IaC language (Bicep | Terraform) and module classification ( resource | pattern | utility). The specifications on each page are further ordered by the category (e.g., Composition, CodeStyle, Testing, etc.), severity of the requirements (MUST | SHOULD | MAY) and at what stage of the module’s lifecycle the specification is typically applicable (Initial | BAU | EOL).
To find what you need, simply decide which IaC language you’d like develop in and what classification your module falls under, then navigate to the respective page to find the specifications that are relevant to you.
Info
All specifications have a 4-9 character long unique ID - a combination of letters and numbers. These letters only carry legacy meaning only leveraged by the AVM core team and are no longer used to group the specifications in any visible way. The ID is used to reference the specification in the code, documentation, and discussions.
Specification Tags
The following tags are used to qualify the specifications:
Each tag is a concatenation of exactly one of the keys and one of the values, e.g., Language-Bicep, Class-Resource, Type-Functional, etc. When it’s marked as Multiple, it means that the tag can have multiple values, e.g., Language-Bicep, Language-Terraform, or Persona-Owner, Persona-Contributor, etc. When it’s marked as Single, it means that the tag can have only one value, e.g., Type-Functional, Lifecycle-Initial, etc.
β Click here to see the definition of the Severity, Persona, Lifecycle and Validation tags...
Who is this specification for? The Owner is the module owner, while the Contributor is anyone who contributes to the module.
Lifecycle
When is this specification mostly relevant?
The Initial stage is when the module is being developed first - e.g., naming related specs are labeled with Lifecycle-Initial as the naming of the module only happens once: at the beginning of their life.
The BAU (business as usual) stage is at any time during the module’s typical lifecycle - e.g., specs that describe coding standards are relevant throughout the module’s life, for any time a new module version is released.
The EOL (end of life) stage is when the module is being decommissioned - e.g., specs describing how a module should be retired are labeled with Lifecycle-EOL.
Validation
How is this specification checked/validated/enforced?
Manual means that the specification is manually enforced at the time of the module review (at the time of the first or any subsequent module version release).
CI/Informational means that the module is checked against the specification by a CI pipeline, but the failure is only informational and doesn’t block the module release.
CI/Enforced means that the specification is automatically enforced by a CI pipeline, and the failure blocks the module release.
Note: the BCP/ or TF/ prefix is required as shared (language-agnostic) specifications may have different level of validation/enforcement per each language - e.g., it is possible that a specification is enforced by a CI pipeline for Bicep modules, while it is manually enforced for Terraform modules.
Why are there language specific specifications?
While every effort is being made to standardize requirements and implementation details across all languages (and most specifications in fact, are applicable to all), it is expected that some of the specifications will be different between their respective languages to ensure we follow the best practices and leverage features of each language.
How to read the specifications?
Important
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDEDβ, βMAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119.
As you’re developing/maintaining a module as a module owner or contributor, you need to ensure that your module adheres to the specifications outlined in this section. The specifications are designed to ensure that all AVM modules are consistent, secure, and compliant with best practices.
There are 3 levels of specifications:
MUST: These are mandatory requirements that MUST be followed.
SHOULD: These are recommended requirements that SHOULD be followed, unless there are good reasons for not to.
MAY: These are optional requirements that MAY be followed at the module owner’s/contributor’s discretion.
Subsections of Module Specifications
Bicep Specifications
Specifications by Category and Module Classification
This chapter details the interfaces/schemas for the AVM Resource Modules features/extension resources as referenced in RMFR4 and RMFR5.
Diagnostic Settings
Important
Allowed values for logs and metric categories or category groups MUST NOT be specified to keep the module implementation evergreen for any new categories or category groups added by RPs, without module owners having to update a list of allowed values and cut a new release of their module.
Diagnostic Settings
// ============== //// Parameters //// ============== //import { diagnosticSettingFullType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('Optional. The diagnostic settings of the service. If neither metrics nor logs are specified, all metrics & logs are configured by default. If only one of them is specified, the other one will not be configured.')
param diagnosticSettings diagnosticSettingFullType[]?
// ============= //// Resources //// ============= //resource>singularMainResourceType<_diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = [for (diagnosticSetting, index) in (diagnosticSettings ?? []): {
name: diagnosticSetting.?name ??'${name}-diagnosticSettings' properties: {
storageAccountId: diagnosticSetting.?storageAccountResourceId
workspaceId: diagnosticSetting.?workspaceResourceId
eventHubAuthorizationRuleId: diagnosticSetting.?eventHubAuthorizationRuleResourceId
eventHubName: diagnosticSetting.?eventHubName
metrics: [
for group in (diagnosticSetting.?metricCategories ?? (empty(diagnosticSetting.?logCategoriesAndGroups)
? [{ category: 'AllMetrics' }]
: [])): {
category: group.category
enabled: group.?enabled ??true timeGrain: null }
]
logs: [
for group in (diagnosticSetting.?logCategoriesAndGroups ?? (empty(diagnosticSetting.?metricCategories)
? [{ categoryGroup: 'allLogs' }]
: [])): {
categoryGroup: group.?categoryGroup
category: group.?category
enabled: group.?enabled ??true }
]
marketplacePartnerId: diagnosticSetting.?marketplacePartnerResourceId
logAnalyticsDestinationType: diagnosticSetting.?logAnalyticsDestinationType
}
scope: >singularMainResourceType< }]
In the provided example for Diagnostic Settings, both logs and metrics are enabled for the associated resource. However, it is IMPORTANT to note that certain resources may not support both diagnostic setting types/categories. In such cases, the resource configuration MUST be modified accordingly to ensure proper functionality and compliance with system requirements.
Role Assignments
// ============== //// Parameters //// ============== //import { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('Optional. Array of role assignments to create.')
param roleAssignments roleAssignmentType[]?
// ============= //// Variables //// ============= //var builtInRoleNames = {
// Add other relevant built-in roles here for your resource as per BCPNFR5 Contributor: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
Owner: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')
Reader: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')
'Role Based Access Control Administrator (Preview)': subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'f58310d9-a9f6-439a-9e8d-f62e7b41a168')
'User Access Administrator': subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '18d7d88d-d35e-4fb5-a5c3-7773c20a72d9')
}
var formattedRoleAssignments = [
for (roleAssignment, index) in (roleAssignments ?? []): union(roleAssignment, {
roleDefinitionId: builtInRoleNames[?roleAssignment.roleDefinitionIdOrName] ?? (contains(roleAssignment.roleDefinitionIdOrName, '/providers/Microsoft.Authorization/roleDefinitions/')
? roleAssignment.roleDefinitionIdOrName
: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleAssignment.roleDefinitionIdOrName))
})
]
// ============= //// Resources //// ============= //resource>singularMainResourceType<_roleAssignments 'Microsoft.Authorization/roleAssignments@2022-04-01' = [
for (roleAssignment, index) in (formattedRoleAssignments ?? []): {
name: roleAssignment.?name ??guid(>singularMainResourceType<.id, roleAssignment.principalId, roleAssignment.roleDefinitionId)
properties: {
roleDefinitionId: roleAssignment.roleDefinitionId
principalId: roleAssignment.principalId
description: roleAssignment.?description
principalType: roleAssignment.?principalType
condition: roleAssignment.?condition
conditionVersion: !empty(roleAssignment.?condition) ? (roleAssignment.?conditionVersion ??'2.0') : null// Must only be set if condtion is set delegatedManagedIdentityResourceId: roleAssignment.?delegatedManagedIdentityResourceId
}
scope: >singularMainResourceType< }
]
Details on child, extension and cross-referenced resources:
Modules MUST support Role Assignments on child, extension and cross-referenced resources as well as the primary resource via parameters/variables
Resource Locks
// ============== //// Parameters //// ============== //import { lockType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('Optional. The lock settings of the service.')
param lock lockType?
// ============= //// Resources //// ============= //resource>singularMainResourceType<_lock 'Microsoft.Authorization/locks@2020-05-01' = if (!empty(lock ?? {}) && lock.?kind !='None') {
name: lock.?name ??'lock-${name}' properties: {
level: lock.?kind ??'' notes: lock.?notes ?? (lock.?kind =='CanNotDelete' ? 'Cannot delete resource or child resources.' : 'Cannot delete or modify the resource or child resources.')
}
scope: >singularMainResourceType< }
lock: {
kind: 'CanNotDelete' name: 'myCustomLockName' notes: 'This is a custom lock note.' }
Details on child and extension resources:
Locks SHOULD be able to be set for child resources of the primary resource in resource modules
Details on cross-referenced resources:
Locks MUST be automatically applied to cross-referenced resources if the primary resource has a lock applied.
This MUST also be able to be turned off for each of the cross-referenced resources by the module consumer via a parameter/variable if they desire
An example of this is a Key Vault module that has a Private Endpoints enabled. If a lock is applied to the Key Vault via the lock parameter/variable then the lock should also be applied to the Private Endpoint automatically, unless the privateEndpointLock/private_endpoint_lock (example name) parameter/variable is set to None
Tags
@description('Optional. Tags of the resource.')
param tags object?
Details on child, extension and cross-referenced resources:
Tags MUST be automatically applied to child, extension and cross-referenced resources, if tags are applied to the primary resource.
By default, all tags set for the primary resource will automatically be passed down to child, extension and cross-referenced resources.
This MUST be able to be overridden by the module consumer so they can specify alternate tags for child, extension and cross-referenced resources, if they desire via a parameter/variable
If overridden by the module consumer, no merge/union of tags will take place from the primary resource and only the tags specified for the child, extension and cross-referenced resources will be applied
Managed Identities
// ============== //// Parameters //// ============== //import { managedIdentityAllType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('Optional. The managed identity definition for this resource.')
param managedIdentities managedIdentityAllType?
// ============= //// Variables //// ============= //var formattedUserAssignedIdentities = reduce(map((managedIdentities.?userAssignedResourceIds ?? []), (id) => { '${id}': {} }), {}, (cur, next) => union(cur, next)) // Converts the flat array to an object like { '${id1}': {}, '${id2}': {} }var identity = !empty(managedIdentities) ? {
type: (managedIdentities.?systemAssigned ??false) ? (!empty(managedIdentities.?userAssignedResourceIds ?? {}) ? 'SystemAssigned,UserAssigned' : 'SystemAssigned') : (!empty(managedIdentities.?userAssignedResourceIds ?? {}) ? 'UserAssigned' : null)
userAssignedIdentities: !empty(formattedUserAssignedIdentities) ? formattedUserAssignedIdentities : null } : null// ============= //// Resources //// ============= //resource>singularMainResourceType<'>providerNamespace</>resourceType<@>apiVersion<' = {
name: name
identity: identity
properties: {
... // other properties }
}
// =========== //// Outputs //// =========== // @description('The principal ID of the system assigned identity.')
output systemAssignedMIPrincipalId string? = >singularMainResourceType<.?identity.?principalId
Reason for differences in User Assigned data type in languages:
We do not foresee the Managed Identity Resource Provider team to ever add additional properties within the empty object ({}) value required on the input of a User Assigned Managed Identity.
In Bicep we therefore have removed the need for this to be declared and just converted it to a simple array of Resource IDs
Private Endpoints
Private Endpoints
E.g., for services that only have one private endpoint type.
// ============== //// Parameters //// ============== //import { privateEndpointSingleServiceType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('Optional. Configuration details for private endpoints. For security reasons, it is recommended to use private endpoints whenever possible.')
param privateEndpoints privateEndpointSingleServiceType[]?
var enableReferencedModulesTelemetry = false// resource module// ============= //// Resources //// ============= //module>singularMainResourceType<_privateEndpoints 'br/public:avm/res/network/private-endpoint:>version<' = [for (privateEndpoint, index) in (privateEndpoints ?? []): {
name: '${uniqueString(deployment().name, location)}->singularMainResourceType<-PrivateEndpoint-${index}' scope: resourceGroup(
split(privateEndpoint.?resourceGroupResourceId ??resourceGroup().id, '/')[2],
split(privateEndpoint.?resourceGroupResourceId ??resourceGroup().id, '/')[4]
)
params: {
// Variant 1: A default service can be assumed (i.e., for services that only have one private endpoint type) name: privateEndpoint.?name ??'pep-${last(split(>singularMainResourceType<.id, '/'))}-${privateEndpoint.?service ??'>defaultServiceName<'}-${index}' privateLinkServiceConnections: privateEndpoint.?isManualConnection !=true ? [
{
name: privateEndpoint.?privateLinkServiceConnectionName ??'${last(split(>singularMainResourceType<.id, '/'))}-${privateEndpoint.?service ??'>defaultServiceName<'}-${index}' properties: {
privateLinkServiceId: >singularMainResourceType<.id
groupIds: [
privateEndpoint.?service ??'>defaultServiceName<' ]
}
}
] : null manualPrivateLinkServiceConnections: privateEndpoint.?isManualConnection ==true ? [
{
name: privateEndpoint.?privateLinkServiceConnectionName ??'${last(split(>singularMainResourceType<.id, '/'))}-${privateEndpoint.?service ??'>defaultServiceName<'}-${index}' properties: {
privateLinkServiceId: >singularMainResourceType<.id
groupIds: [
privateEndpoint.?service ??'>defaultServiceName<' ]
requestMessage: privateEndpoint.?manualConnectionRequestMessage ??'Manual approval required.' }
}
] : null subnetResourceId: privateEndpoint.subnetResourceId
enableTelemetry: enableReferencedModulesTelemetry // resource module enableTelemetry: privateEndpoint.?enableTelemetry ?? enableTelemetry // pattern / utility module location: privateEndpoint.?location ??reference(split(privateEndpoint.subnetResourceId, '/subnets/')[0], '2020-06-01', 'Full').location
lock: privateEndpoint.?lock ?? lock
privateDnsZoneGroup: privateEndpoint.?privateDnsZoneGroup
roleAssignments: privateEndpoint.?roleAssignments
tags: privateEndpoint.?tags ?? tags
customDnsConfigs: privateEndpoint.?customDnsConfigs
ipConfigurations: privateEndpoint.?ipConfigurations
applicationSecurityGroupResourceIds: privateEndpoint.?applicationSecurityGroupResourceIds
customNetworkInterfaceName: privateEndpoint.?customNetworkInterfaceName
}
}]
@description('The private endpoints of the resource.')
output privateEndpoints privateEndpointOutputType[] = [
for (pe, index) in (privateEndpoints ?? []): {
name: >singularMainResourceType<_privateEndpoints[index].outputs.name
resourceId: >singularMainResourceType<_privateEndpoints[index].outputs.resourceId
groupId: >singularMainResourceType<_privateEndpoints[index].outputs.?groupId! customDnsConfigs: >singularMainResourceType<_privateEndpoints[index].outputs.customDnsConfigs
networkInterfaceResourceIds: >singularMainResourceType<_privateEndpoints[index].outputs.networkInterfaceResourceIds
}
]
// =============== //// Definitions //// =============== // @export()
type privateEndpointOutputType = {
@description('The name of the private endpoint.')
name: string
@description('The resource ID of the private endpoint.')
resourceId: string
@description('The group Id for the private endpoint Group.')
groupId: string?
@description('The custom DNS configurations of the private endpoint.')
customDnsConfigs: {
@description('FQDN that resolves to private endpoint IP address.')
fqdn: string?
@description('A list of private IP addresses of the private endpoint.')
ipAddresses: string[]
}[]
@description('The IDs of the network interfaces associated with the private endpoint.')
networkInterfaceResourceIds: string[]
}
The properties defined in the schema above are the minimum amount of properties expected to be exposed for Private Endpoints in AVM Resource Modules.
A module owner MAY chose to expose additional properties of the Private Endpoint resource
However, module owners considering this SHOULD contact the AVM core team first to consult on how the property should be exposed to avoid future breaking changes to the schema that may be enforced upon them
Module owners MAY chose to define a list of allowed value for the ‘service’ (a.k.a. groupIds) property
However, they should do so with caution as should a new service appear for their resource module, a new release will need to be cut to add this new service to the allowed values
Whereas not specifying allowed values will allow flexibility from day 0 without the need for any changes and releases to be made
Since version Bicep 0.35.1, it is possible to export secrets securely using the secure() annotation.
As this approach is fairly simple compared with the below workaround it is highly recommended to use it instead.
Example
@secure()
@description('The primary connection string of the service bus namespace.')
output primaryConnectionString string = listkeys(
'${serviceBusNamespace.id}/AuthorizationRules/RootManageSharedAccessKey',
'2024-01-01').primaryConnectionString
@secure()
@description('The primary key of the service bus namespace.')
output primaryKey string = listkeys(
'${serviceBusNamespace.id}/AuthorizationRules/RootManageSharedAccessKey',
'2024-01-01').primaryKey
Secrets used inside a module can be exported to a Key Vault reference provided as per the below schema. This implementation provides a secure way around the current limitation of Bicep on providing a secure template output (that can be used for secrets).
The user MUST
provide the resource Id to a Key Vault. The principal used for the deployment MUST be allowed to set secrets in this Key Vault.
provide a name for each secret they want to store (opt-in). The module will suggest which secrets are available via the implemented user-defined type.
The module returns an output table where the key is the name of the secret the user provided, and the value contains both the secret’s resource Id and URI.
Important
The feature MUST be implemented as per the below schema. Diversions are only allowed in places marked as >text< to ensure a consistent user experience across modules.
User Defined Type, Parameter & Resource Example
// ============== //// Parameters //// ============== // @description('Optional. Key vault reference and secret settings for the module\'s secrets export.')
param secretsExportConfiguration secretsExportConfigurationType?
// ============= //// Resources //// ============= //module secretsExport 'modules/keyVaultExport.bicep' = if (secretsExportConfiguration !=null) {
name: '${uniqueString(deployment().name, location)}-secrets-kv' scope: resourceGroup(
split(secretsExportConfiguration.?keyVaultResourceId, '/')[2],
split(secretsExportConfiguration.?keyVaultResourceId, '/')[4]
)
params: {
keyVaultName: last(split(secretsExportConfiguration.?keyVaultResourceId, '/'))
secretsToSet: union(
[],
contains(secretsExportConfiguration!, '>secretToExport1<Name')
? [
{
name: secretsExportConfiguration!.?>secretToExport1<Name
value: >secretReference1<// e.g., >singularMainResourceType<.listKeys().primaryMasterKey }
]
: [],
contains(secretsExportConfiguration!, '>secretToExport2<Name')
? [
{
name: secretsExportConfiguration!.?>secretToExport2<Name
value:>secretReference2<// e.g., >singularMainResourceType<.listKeys().secondaryMasterKey }
]
: []
// (...) )
}
}
// =========== //// Outputs //// =========== //import { secretsOutputType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('A hashtable of references to the secrets exported to the provided Key Vault. The key of each reference is each secret\'s name.')
output exportedSecrets secretsOutputType = (secretsExportConfiguration !=null)
? toObject(secretsExport.outputs.secretsSet, secret => last(split(secret.secretResourceId, '/')), secret => secret)
: {}
// =============== //// Definitions //// =============== // @export()
type secretsExportConfigurationType = {
@description('Required. The resource ID of the key vault where to store the secrets of this module.')
keyVaultResourceId: string
@description('Optional. The >secretToExport1< secret name to create.')
>secretToExport1<Name: string?
@description('Optional. The >secretToExport2< secret name to create.')
>secretToExport2<Name: string?
// (...) }
Input Example with Values
// ============== //// Parameters //// ============== // @description('Optional. Key vault reference and secret settings for the module\'s secrets export.')
param secretsExportConfiguration secretsExportConfigurationType?
// ============= //// Resources //// ============= //module secretsExport 'modules/keyVaultExport.bicep' = if (secretsExportConfiguration !=null) {
name: '${uniqueString(deployment().name, location)}-secrets-kv' scope: resourceGroup(
split(secretsExportConfiguration.?keyVaultResourceId, '/')[2],
split(secretsExportConfiguration.?keyVaultResourceId, '/')[4]
)
params: {
keyVaultName: last(split(secretsExportConfiguration.?keyVaultResourceId, '/'))
secretsToSet: union(
[],
contains(secretsExportConfiguration!, '>secretToExport1<Name')
? [
{
name: secretsExportConfiguration!.?>secretToExport1<Name
value: >secretReference1<// e.g., >singularMainResourceType<.listKeys().primaryMasterKey }
]
: [],
contains(secretsExportConfiguration!, '>secretToExport2<Name')
? [
{
name: secretsExportConfiguration!.?>secretToExport2<Name
value:>secretReference2<// e.g., >singularMainResourceType<.listKeys().secondaryMasterKey }
]
: []
// (...) )
}
}
// =========== //// Outputs //// =========== //import { secretsOutputType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('A hashtable of references to the secrets exported to the provided Key Vault. The key of each reference is each secret\'s name.')
output exportedSecrets secretsOutputType = (secretsExportConfiguration !=null)
? toObject(secretsExport.outputs.secretsSet, secret => last(split(secret.secretResourceId, '/')), secret => secret)
: {}
// =============== //// Definitions //// =============== // @export()
type secretsExportConfigurationType = {
@description('Required. The resource ID of the key vault where to store the secrets of this module.')
keyVaultResourceId: string
@description('Optional. The >secretToExport1< secret name to create.')
>secretToExport1<Name: string?
@description('Optional. The >secretToExport2< secret name to create.')
>secretToExport2<Name: string?
// (...) }
[modules/keyVaultExport.bicep] file
// ============== //// Parameters //// ============== // @description('Required. The name of the Key Vault to set the secrets in.')
param keyVaultName string
import { secretToSetType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('Required. The secrets to set in the Key Vault.')
param secretsToSet secretToSetType[]
// ============= //// Resources //// ============= //resource keyVault 'Microsoft.KeyVault/vaults@2022-07-01'existing = {
name: keyVaultName
}
resource secrets 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = [
for secret in secretsToSet: {
name: secret.name
parent: keyVault
properties: {
value: secret.value
}
}
]
// =========== //// Outputs //// =========== //import { secretSetOutputType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('The references to the secrets exported to the provided Key Vault.')
output secretsSet secretSetOutputType[] = [
#disable-next-line outputs-should-not-contain-secrets // Only returning the references, not a secret valuefor index inrange(0, length(secretsToSet ?? [])): {
secretResourceId: secrets[index].id
secretUri: secrets[index].properties.secretUri
secretUriWithVersion: secrets[index].properties.secretUriWithVersion
}
]
Output Usage Example
When using a module that implements the above interface, you can access its outputs for example in the following ways:
// ============== //// Parameters //// ============== // @description('Optional. Key vault reference and secret settings for the module\'s secrets export.')
param secretsExportConfiguration secretsExportConfigurationType?
// ============= //// Resources //// ============= //module secretsExport 'modules/keyVaultExport.bicep' = if (secretsExportConfiguration !=null) {
name: '${uniqueString(deployment().name, location)}-secrets-kv' scope: resourceGroup(
split(secretsExportConfiguration.?keyVaultResourceId, '/')[2],
split(secretsExportConfiguration.?keyVaultResourceId, '/')[4]
)
params: {
keyVaultName: last(split(secretsExportConfiguration.?keyVaultResourceId, '/'))
secretsToSet: union(
[],
contains(secretsExportConfiguration!, '>secretToExport1<Name')
? [
{
name: secretsExportConfiguration!.?>secretToExport1<Name
value: >secretReference1<// e.g., >singularMainResourceType<.listKeys().primaryMasterKey }
]
: [],
contains(secretsExportConfiguration!, '>secretToExport2<Name')
? [
{
name: secretsExportConfiguration!.?>secretToExport2<Name
value:>secretReference2<// e.g., >singularMainResourceType<.listKeys().secondaryMasterKey }
]
: []
// (...) )
}
}
// =========== //// Outputs //// =========== //import { secretsOutputType } from 'br/public:avm/utl/types/avm-common-types:>version<' @description('A hashtable of references to the secrets exported to the provided Key Vault. The key of each reference is each secret\'s name.')
output exportedSecrets secretsOutputType = (secretsExportConfiguration !=null)
? toObject(secretsExport.outputs.secretsSet, secret => last(split(secret.secretResourceId, '/')), secret => secret)
: {}
// =============== //// Definitions //// =============== // @export()
type secretsExportConfigurationType = {
@description('Required. The resource ID of the key vault where to store the secrets of this module.')
keyVaultResourceId: string
@description('Optional. The >secretToExport1< secret name to create.')
>secretToExport1<Name: string?
@description('Optional. The >secretToExport2< secret name to create.')
>secretToExport2<Name: string?
// (...) }
This interface is a SHOULD instead of a MUST and therefore the AVM core team have not mandated a interface schema to use.
Zonal & zone-redundant resources
Many Azure resources can be deployed into specific availability zones. Depending on whether a resource is ‘zonal’ (i.e., deploys a single instance into a single zone) or ‘zone-redundant’ (i.e., spreads multiple of its instances across the configured zones), implementing a different interface is required. Simply put, the zone of a zonal resource must be a required parameter (but give the user the option to ‘opt-out’), while zone-redundant resources must span all available zones by default, but still give the user the option to ‘opt-out’. Please note that the support for Availability Zones may differ from region to region.
// ============== //// Parameters //// ============== // @description('Required. If set to 1, 2 or 3, the availability zone is hardcoded to that value. If set to -1, no zone is defined. Note that the availability zone numbers here are the logical availability zone in your Azure subscription. Different subscriptions might have a different mapping of the physical zone and logical zone. To understand more, please refer to [Physical and logical availability zones](https://learn.microsoft.com/en-us/azure/reliability/availability-zones-overview?tabs=azure-cli#physical-and-logical-availability-zones).')
@allowed([
-1
1
2
3
])
param availabilityZone int
// ============= //// Resources //// ============= //resource>singularMainResourceType<'>providerNamespace</>resourceType<@>apiVersion<' = {
name: '>exampleResource<' properties: {
... // other properties zones: availabilityZone !=-1 ? array(string(availabilityZone)) : null// If expecting an array// Or availabilityZone: availabilityZone !=-1 ? string(availabilityZone) : null// If expecting a single value }
}
availabilityZone: -1 // Deploy into no zone availabilityZone: 1 // Deploy into zone 1
// ============== //// Parameters //// ============== // @description('Optional. The list of Availability zones to use for the zone-redundant resources.')
@allowed([
1
2
3
])
param availabilityZones int[] = [1, 2, 3]
// ============= //// Resources //// ============= //resource>singularMainResourceType<'>providerNamespace</>resourceType<@>apiVersion<' = {
name: '>exampleResource<' properties: {
... // other properties zones: map(availabilityZones, zone => '${zone}')
}
}
availabilityZones: [] // Deploy into no zone availabilityZones: [1, 2] // Deploy into zone 1 & 2
Bicep Pattern Module Specifications
Contribution / Support
The content below is listed based on the following tags
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
The module-name-dropdown in the BRM AVM Module Issue templateMUST list top-level Bicep modules with Available or Orphaned status, sorted by module class and name. Proposed, deprecated, and child modules are excluded.
The module list sync workflow compares the dropdown with the published module catalog and updates it through a verified, auto-merged bot pull request. Module owners maintain root metadata and the required publication or deprecation evidence instead of editing the dropdown directly.
Telemetry
The content below is listed based on the following tags
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
To comply with specifications outlined in SFR3 & SFR4 you MUST incorporate the following code snippet into your modules. Place this code sample in the “top level” main.bicep file; it is not necessary to include it in any nested Bicep files (child modules), unless they are marked for direct publishing (Ref Child module publishing).
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
ID: SFR5 - Category: Composition - Availability Zones
Modules that deploy zone-redundant resources MUST enable the spanning across as many zones as possible by default, typically all 3.
Modules that deploy zonal resources MUST provide the ability to specify a zone for the resources to be deployed/pinned to. However, they MUST NOT default to a particular zone by default, e.g. 1 in an effort to make the consumer aware of the zone they are selecting to suit their architecture requirements.
For both scenarios the modules MUST expose these configuration options via configurable parameters/variables.
ID: SFR6 - Category: Composition - Data Redundancy
Modules that deploy resources or patterns that support data redundancy SHOULD enable this to the highest possible value by default, e.g. RA-GZRS. When a resource or pattern doesn’t provide the ability to specify data redundancy as a simple property, e.g. GRS etc., then the modules MUST provide the ability to enable data redundancy for the resources or pattern via parameters/variables.
For example, a Storage Account module can simply set the sku.name property to Standard_RAGZRS. Whereas a SQL DB or Cosmos DB module will need to expose more properties, via parameters/variables, to allow the specification of the regions to replicate data to as per the consumers requirements.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
Pattern Modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Example: avm/ptn/compute/app-tier-vmss or avm/ptn/avd-lza/management-plane or avm/ptn/3-tier/web-app
Segments:
ptn defines this as a pattern module
<hyphenated grouping/category name> is a hierarchical grouping of pattern modules by category, with each word separated by dashes, such as:
project name, e.g., avd-lza,
primary resource provider, e.g., compute or network, or
architecture, e.g., 3-tier
<hyphenated pattern module name> is a term describing the module’s function, with each word separated by dashes, e.g., app-tier-vmss = Application Tier VMSS; management-plane = Azure Virtual Desktop Landing Zone Accelerator Management Plane
Terraform Pattern Module Naming
Naming convention:
avm-ptn-<pattern module name> (Module name for registry)
terraform-<provider>-avm-ptn-<pattern module name> (GitHub repository name to meet registry naming requirements)
Example: avm-ptn-apptiervmss or avm-ptn-avd-lza-managementplane
Segments:
<provider> is a legacy requirement of the Terraform registry. This must be set to azure
ptn defines this as a pattern module
<pattern module name> is a term describing the module’s function, e.g., apptiervmss = Application Tier VMSS; avd-lza-managementplane = Azure Virtual Desktop Landing Zone Accelerator Management Plane
ID: PMNFR2 - Category: Composition - Use Resource Modules to Build a Pattern Module
A Pattern Module SHOULD be built from AVM Resources Modules to establish a standardized code base and improve maintainability. If a valid reason exists, a pattern module MAY contain native resources (“vanilla” code) where it’s necessary. A Pattern Module MUST NOT contain references to non-AVM modules.
Valid reasons for not using a Resource Module for a resource required by a Pattern Module include but are not limited to:
When using a Resource Module would result in hitting scaling limitations and/or would reduce the capabilities of the Pattern Module due to the limitations of Azure Resource Manager.
Developing a Pattern Module under time constraint, without having all required Resource Modules readily available.
Note
In the latter case, the Pattern Module SHOULD be updated to use the Resource Module when the required Resource Module becomes available, to avoid accumulating technical debt. Ideally, all required Resource Modules SHOULD be developed first, and then leveraged by the Pattern Module.
Module owners MAY cross-reference other modules to build either Resource or Pattern modules.
However, they MUST be referenced only by a public registry reference to a pinned version e.g. br/public:avm/[res|ptn|utl]/<publishedModuleName>:>version<. They MUST NOT use local parent path references to a module e.g. ../../xxx/yyy.bicep.
The only exception to this rule are child modules as documented in BCPFR6.
Modules MUST NOT contain references to non-AVM modules.
ID: BCPFR2 - Category: Composition - Role Assignments Role Definition Mapping
Module owners MAY define common RBAC Role Definition names and IDs within a variable to allow consumers to define a RBAC Role Definition by their name rather than their ID, this should be self contained within the module themselves.
However, they MUST use only the official RBAC Role Definition name within the variable and nothing else.
To meet the requirements of BCPFR2, BCPNFR5 and BCPNFR6 you MUST use the below code sample in your AVM Modules to achieve this.
@description('''Required. You can provide either the display name (note not all roles are supported, check module documentation) of the role definition, or its fully qualified ID in the following format: `/providers/Microsoft.Authorization/roleDefinitions/c2f4ef07-c644-48eb-af81-4b1b4947fb11`.''')
param roleDefinitionIdOrName string
var builtInRbacRoleNames = {
Owner: '/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635' Contributor: '/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c' Reader: '/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7''Role Based Access Control Administrator (Preview)': '/providers/Microsoft.Authorization/roleDefinitions/f58310d9-a9f6-439a-9e8d-f62e7b41a168''User Access Administrator': '/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9'//Other RBAC Role Definitions Names & IDs can be added here as needed for your module }
var roleDefinitionIdMappedResult = (contains(builtInRbacRoleNames, roleDefinitionIdOrName) ? builtInRbacRoleNames[roleDefinitionIdOrName] : roleDefinitionIdOrName)
resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
//Other properties removed for ease of reading properties: {
roleDefinitionId: roleDefinitionIdMappedResult
//Other properties removed for ease of reading }
}
Parent templates MUST reference all their direct child-templates to allow for an end-to-end deployment experience. For example, the SQL server template must reference its child database module and encapsulate it in a loop to allow for the deployment of multiple databases.
@description('Optional. The databases to create in the server')
param databases databaseType[]?
resource server 'Microsoft.Sql/servers@(...)' = { (...) }
module server_databases 'database/main.bicep' = [for (database, index) in (databases ?? []): {
name: '${uniqueString(server.id, location)}-Sql-DB-${index}' params: {
serverName: server.name
(...)
}
}]
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
Each Bicep AVM module that lives within the Azure/bicep-registry-modules (BRM) repository in the avm directory MUST have the following directories and files:
/tests - (for unit tests and additional E2E/integration if required - e.g. Pester etc.)
/e2e - (all examples must deploy successfully - these will be used to automatically generate the examples in the README.md for the module)
/src - (for scripts and other files - e.g., scripts used by the template)
exampleFile.ps1
/modules - (for sub-modules only if used and NOT children of the primary resource - e.g. RBAC role assignments)
exampleTemplate.bicep
/main.bicep (AVM Module main .bicep file and entry point/orchestration module)
/main.json (auto generated and what is published to the MCR via BRM)
When a module references child, utility, or other modules, the deployment name MUST be deterministic. This means the deployment name must produce the same value for the same set of inputs across repeated deployments.
Why deterministic?
Azure Resource Manager has an 800-deployment limit per scope (resource group, subscription, management group, tenant). Non-deterministic names (e.g., those incorporating timestamps or utcNow()) create a new deployment object on every run, which can lead to this limit being reached over time.
While an automatic cleanup process exists for resource group and subscription scopes, it can take some time to take effect. Due to eventual consistency in the backend, the deployment count may not reflect the cleanup immediately, which can lead to failed deployments even when the actual number of deployments is below the 800 limit. Additionally, automatic cleanup does not apply to management group or tenant scopes.
We are actively working with the product team to enhance the cleanup process. In the meantime, deterministic deployment names provide a reliable way to keep deployment counts stable by overwriting previous deployment objects rather than creating new ones.
Deterministic deployment names cause Azure to overwrite the previous deployment object, keeping the deployment count stable regardless of how many times the module is deployed.
Requirement
Module owners MUST construct deployment names for referenced modules using uniqueString() seeded with the parent resource’s ID (<parentResource>.id) and location, rather than deployment().name, subscription().id, resourceGroup().id, utcNow(), or other non-deterministic or scope-level values.
A deterministic hash derived from the parent resource’s resource ID and deployment location. This is both unique per resource instance and stable across deployments.
<ChildModuleDescriptor>
A short, human-readable label identifying the child module being deployed (e.g., DB, Subnet, FederatedIdentityCred).
${index}
The loop index variable, included when deploying in a loop. Omit for single (non-looped) deployments.
location parameter
If location is not available, for example when deploying a global resource that does not have a location property, it is acceptable to omit it. However, the <parentResource>.idMUST always be included as the primary seed for uniqueString.
Why parent resource ID?
Using the parent resource’s ID as the uniqueString seed provides two critical properties:
Deterministic β the same parent resource always produces the same hash, so repeated deployments overwrite rather than accumulate.
Collision-free β different parent resource instances produce different hashes, so deploying multiple instances of the same module type within the same scope does not cause naming collisions.
Why not subscription().id and resourceGroup().id separately?
The parent resource’s ID (e.g., /subscriptions/.../resourceGroups/.../providers/.../resourceName) already contains the subscription ID and resource group ID as segments. Using <parentResource>.id as a single input to uniqueString captures all of this context in one value, keeping the code concise and readable rather than passing multiple scope-level values separately.
Supporting multiple deployments of the same module at the same scope
A common scenario is deploying the same module type more than once within the same scope β for example, two different SQL servers each with their own set of databases, or two user-assigned identities each with their own federated credentials. Because the parent resource ID is unique per resource instance, the resulting deployment names will differ even when the child module type and index are identical. This ensures that parallel deployments of the same module at the same scope do not collide.
Other approaches fail on one or both of these properties:
Approach
Deterministic?
Collision-free?
Issue
deployment().name
β
β
Changes every deployment; hits 800-limit
utcNow() / timestamps
β
β
Changes every deployment; hits 800-limit
subscription().id + resourceGroup().id
β
β
Same hash for all resources in the same RG; collisions when deploying multiple instances
ID: BCPNFR5 - Category: Composition - Role Assignments Role Definition Mapping Limits
As per BCPFR2, module owners MAY define common RBAC Role Definition names and IDs within a variable to allow consumers to define a RBAC Role Definition by their name rather than their ID.
Module owners SHOULD NOT map every RBAC Role Definition within this variable as it can cause the module to bloat in size and cause consumption issues later when stitched together with other modules due to the 4MB ARM Template size limit.
Therefore module owners SHOULD only map the most applicable and common RBAC Role Definition names for their module and SHOULD NOT exceed 15 RBAC Role Definitions in the variable.
Important
Remember if the RBAC Role Definition name is not included in the variable this does not mean it cannot be declared, used and assigned to an identity via an RBAC Role Assignment as part of a module, as any RBAC Role Definition can be specified via its ID without being in the variable.
The version value is in the form of MAJOR.MINOR. The PATCH version will be incremented by the CI automatically when publishing the module to the Public Bicep Registry once the corresponding pull request is merged. Therefore, contributions that would only require an update of the patch version, can keep the version.json file intact.
For example, the version value should be:
0.1 for new modules, so that they can be released as v0.1.0.
1.0 once the module owner signs off the module is stable enough for it’s first Major release of v1.0.0.
0.x for all feature updates between the first release v0.1.0 and the first Major release of v1.0.0.
Inputs / Outputs
The content below is listed based on the following tags
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
ID: BCPNFR1 - Category: Inputs - Complex data types - General
To simplify the consumption experience for module consumers when interacting with complex data types input parameters, mainly objects and arrays, the Bicep features of Resource-Derived Types or User-Defined TypesMUST be used and declared.
Tip
User-Defined Types are GA in Bicep as of version v0.21.1, Resource-Derived Types are GA as of version v0.34.1, please ensure you have this version(s) installed as a minimum.
Resource-Derived Types and User-Defined Types allow intellisense support in supported IDEs (e.g. Visual Studio Code) for complex input parameters using objects and array of objects.
v0.x Exemption
While we allow the release of major versions, starting with v1.0.0, retrofitting Resource-Derived Types and User-Defined Types for all modules will take a considerable amount of time.
Therefore, the addition of these features is currently NOT mandated/enforced. However, all modules MUST implement Resource-Derived Types and User-Defined Types prior to the release of their v1.0.0 version.
Similar to BCPNFR21, input parameters MUST implement decorators such as description & secure (if sensitive).
Further, input parameters SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
param threshold: int?
@description('Required. The SKU of your resource.')
@allowed([
'Basic''Premium''Standard'])
param sku string
User-defined types (UDTs) MUST always be singular and non-nullable. The configuration of either should instead be done directly at the parameter or output that uses the type.
For example, instead of
param subnets subnetsType
type subnetsType = { ... }[]?
the type should be defined like
param subnets subnetType[]?
type subnetType = { ... }
The primary reason for this requirement is clarity. If not defined directly at the parameter or output, a user would always be required to check the type to understand how e.g., a parameter is expected.
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
User-defined types (UDTs) SHOULD always be exported via the @export() annotation in every template they’re implemented in.
@export()
type subnetType = { ... }
Doing so has the benefit that other (e.g., parent) modules can import them and as such reduce code duplication. Also, if the module itself is published, users of the Public Bicep Registry can import the types independently of the module itself. One example where this can be useful is a pattern module that may re-use the same interface when referencing a module from the registry.
Similar to BCPNFR9, User-defined types (UDTs) MUST implement decorators such as description & secure (if sensitive). This is true for every property of the UDT, as well as the UDT itself.
Further, User-defined types SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('My type''s description.')
type myType = {
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
threshold: int?
@description('Required. The SKU of your resource.')
sku: ('Basic' | 'Premium' | 'Standard')
}
Modules will have lots of parameters that will differ in their requirement type (required, optional, etc.). To help consumers understand what each parameter’s requirement type is, module owners MUST add the requirement type to the beginning of each parameter’s description. Below are the requirement types with a definition and example for the description decorator:
Parameter Requirement Type
Definition
Example Description Decorator
Required
The parameter value must be provided. The parameter does not have a default value and hence the module expects and requires an input.
The parameter value can be optional or required based on a condition, mostly based on the value provided to other parameters. Should contain a sentence starting with ‘Required if (…).’ to explain the condition.
The parameter value is generated within the module and should not be specified as input in most cases. A common example of this is the utcNow() function that is only supported as the input for a parameter value, and not inside a variable.
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
Module owners MUST test that child and extension resources and those Bicep or Terreform interface resources that are supported by their modules, are validated in E2E tests as per SNFR2 to ensure they deploy and are configured correctly.
These MAY be tested in a separate E2E test and DO NOT have to be tested in each E2E test.
ID: BCPNFR10 - Category: Testing - Test Bicep File Naming
Module owners MUST name their test .bicep files in the /tests/e2e/<defaults/waf-aligned/max/etc.> directories: main.test.bicep as the test framework (CI) relies upon this name.
ID: BCPNFR13 - Category: Testing - Test file metadata
By default, the ReadMe-generating utility will create usage examples headers based on each e2e folder’s name. Module owners MAY provide a custom name & description by specifying the metadata blocks name & description in their main.test.bicep test files.
For example:
metadata name = 'Using Customer-Managed-Keys with System-Assigned identity'metadata description = 'This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.'
would lead to a header in the module’s readme.md file along the lines of
### Example 1: _Using Customer-Managed-Keys with System-Assigned identity_
This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.
For each test case in the e2e folder, you can optionally add post-deployment Pester tests that are executed once the corresponding deployment completed and before the removal logic kicks in.
To leverage the feature you MUST:
Use Pester as a test framework in each test file
Name the file with the suffix "*.tests.ps1"
Place each test file the e2e test’s folder or any subfolder (e.g., e2e/max/myTest.tests.ps1 or e2e/max/tests/myTest.tests.ps1)
Implement an input parameter TestInputData in the following way:
Through this parameter you can make use of every output the main.test.bicep file returns, as well as the path to the test template file in case you want to extract data from it directly.
For example, with an output such as output resourceId string = testDeployment[1].outputs.resourceId defined in the main.test.bicep file, the $TestInputData would look like:
$TestInputData = @{
DeploymentOutputs = @{
resourceId = @{
Type = "String" Value = "/subscriptions/***/resourceGroups/dep-***-keyvault.vaults-kvvpe-rg/providers/Microsoft.KeyVault/vaults/***kvvpe001" }
}
ModuleTestFolderPath = "/home/runner/work/bicep-registry-modules/bicep-registry-modules/avm/res/key-vault/vault/tests/e2e/private-endpoint"}
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
The above formats are currently automatically taken & generated from the tests/e2e tests. It is enough to run the Set-ModuleReadMe or Set-AVMModule functions (from the utilities folder) to update the usage examples in the readme(s).
Note
Bicep Parameter Files (.bicepparam) are being reviewed and considered by the AVM team for the usability and features at this time and will likely be added in the future.
It is planned that these examples are automatically added to the module readme’s parameter descriptions when running either the Set-ModuleReadMe or Set-AVMModule scripts (available in the utilities folder).
Release / Publishing
The content below is listed based on the following tags
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
When a module to be published (i.e., that has a version.json file) is changed, an entry MUST be created in the CHANGELOG.md file in the module folder. A link to the latest version of the changelog file has to be included at the top of the file, just below the # Changelog line. It is surrounded by empty lines.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/<ptn|res|utl>/<namespace/modulename[/submodulePath]>/CHANGELOG.md).
For each new version, an entry MUST be created above all existing versions in the CHANGELOG.md file of the module.
## <version>
### Changes
- This changed
- And this also
### Breaking Changes
- None
Each version’s entry:
MUST contain two sections: Changes and Breaking Changes. At least one of them must have a meaningful entry and sections must not be left empty. A - None may be added as content for a section.
MUST exist only once.
All versions appear in descending order, which puts the most recent changes at the top.
What SHOULD be listed in the (Breaking) Changes section:
A CHANGELOG.md file in the module’s root folder MUST start with the # Changelog header, followed by an empty line and a link to the latest published version of the changelog file, followed by another empty line. A section for each published version follows. Newer versions are placed above older versions.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/res/aad/domain-service/CHANGELOG.md).
## 0.2.1
### Changes
- Updated the referenced AVM common types
### Breaking Changes
- None
## 0.2.0
### Changes
- Implemented the minCPU parameter
- Updated the referenced VirtualNetwork module
- Updated the referenced AVM common types
### Breaking Changes
- The minCPU parameter is mandatory
## 0.1.0
### Changes
- Initial Release
### Breaking Changes
- None
Each bullet point should start with a capital letter.
Manual Editing
It is possible to modify the changelog content any time, e.g., to add missing versions, which will not create a new release of the module itself. Please note the following requirements in all cases:
All versions in the file, need to be valid and available as published version
Every version needs the two sections ## Changes and ## Breaking Changes with content
Note
Azure Verified Modules are artifacts in the Microsoft Container Registry (MCR). Every version of a module exists as a tag in the Container Registry and can be listed at https://mcr.microsoft.com/v2/bicep/avm/(res|ptn|utl)/<namespace/modulename>/tags/list. For example, see the FinOps hub module tags.
Code Style
The content below is listed based on the following tags
To improve the usability of primitive module properties declared as strings, you SHOULD declare them using a type which better represents them, and apply any required casting in the module on behalf of the user.
For reference, please refer to the following examples:
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
The module-name-dropdown in the BRM AVM Module Issue templateMUST list top-level Bicep modules with Available or Orphaned status, sorted by module class and name. Proposed, deprecated, and child modules are excluded.
The module list sync workflow compares the dropdown with the published module catalog and updates it through a verified, auto-merged bot pull request. Module owners maintain root metadata and the required publication or deprecation evidence instead of editing the dropdown directly.
Telemetry
The content below is listed based on the following tags
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
To comply with specifications outlined in SFR3 & SFR4 you MUST incorporate the following code snippet into your modules. Place this code sample in the “top level” main.bicep file; it is not necessary to include it in any nested Bicep files (child modules), unless they are marked for direct publishing (Ref Child module publishing).
A variable named enableReferencedModulesTelemetry is created in the main.bicep file of the module, that cross-references other published modules, and set to false. This variable is used to set the enableTelemetry parameter of cross-referenced modules.
var enableReferencedModulesTelemetry = false// local referencingmodule virtualNetwork_subnets 'subnet/main.bicep' = [
for (subnet, index) in (subnets ?? []): {
name: '${uniqueString(virtualNetwork.id, location)}-subnet-${index}' params: {
(...)
enableTelemetry: enableReferencedModulesTelemetry
}
}
]
// published module referencemodule virtualNetwork_subnet 'br/public:avm/res/network/virtual-network/subnet:0.1.0' = {
name: '${uniqueString(virtualNetwork.id, location)}-subnet-${index}' params: {
(...)
enableTelemetry: enableReferencedModulesTelemetry
}
}
Naming / Composition
The content below is listed based on the following tags
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
ID: SFR5 - Category: Composition - Availability Zones
Modules that deploy zone-redundant resources MUST enable the spanning across as many zones as possible by default, typically all 3.
Modules that deploy zonal resources MUST provide the ability to specify a zone for the resources to be deployed/pinned to. However, they MUST NOT default to a particular zone by default, e.g. 1 in an effort to make the consumer aware of the zone they are selecting to suit their architecture requirements.
For both scenarios the modules MUST expose these configuration options via configurable parameters/variables.
ID: SFR6 - Category: Composition - Data Redundancy
Modules that deploy resources or patterns that support data redundancy SHOULD enable this to the highest possible value by default, e.g. RA-GZRS. When a resource or pattern doesn’t provide the ability to specify data redundancy as a simple property, e.g. GRS etc., then the modules MUST provide the ability to enable data redundancy for the resources or pattern via parameters/variables.
For example, a Storage Account module can simply set the sku.name property to Standard_RAGZRS. Whereas a SQL DB or Cosmos DB module will need to expose more properties, via parameters/variables, to allow the specification of the regions to replicate data to as per the consumers requirements.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
ID: RMFR3 - Category: Composition - Resource Groups
A resource module MUST NOT create a Resource Group for resources that require them.
In the case that a Resource Group is required, a module MUST have an input (scope or variable):
In Bicep the targetScopeMUST be set to resourceGroup or not specified (which means default to resourceGroup scope).
For Terraform, the resource group is supplied via the parent_id variable defined by TFRMFR1. Terraform resource modules MUST NOT expose a resource_group_name (or resource_group_resource_id) variable.
Scopes will be covered further in the respective language specific specifications.
Resource modules support the following optional features/extension resources, as specified, if supported by the primary resource. The top-level variable/parameter names MUST be:
Optional Features/Extension Resources
Bicep Parameter Name
Terraform Variable Name
MUST/SHOULD
Diagnostic Settings
diagnosticSettings
diagnostic_settings
MUST
Role Assignments
roleAssignments
role_assignments
MUST
Resource Locks
lock
lock
MUST
Tags
tags
tags
MUST
Managed Identities (System / User Assigned)
managedIdentities
managed_identities
MUST
Private Endpoints
privateEndpoints
private_endpoints
MUST
Customer Managed Keys
customerManagedKey
customer_managed_key
MUST
Azure Monitor Alerts
alerts
alerts
SHOULD
Resource modules MUST NOT deploy required/dependent resources for the optional features/extension resources specified above. For example, for Diagnostic Settings the resource module MUST NOT deploy the Log Analytics Workspace, this is expected to be already in existence from the perspective of the resource module deployed via another method/module etc.
Note
Please note that the implementation of Customer Managed Keys from an ARM API perspective is different across various RPs that implement Customer Managed Keys in their service. For that reason you may see differences between modules on how Customer Managed Keys are handled and implemented, but functionality will be as expected.
Module owners MAY choose to utilize cross repo dependencies for these “add-on” resources, or MAY chose to implement the code directly in their own repo/module. So long as the implementation and outputs are as per the specifications requirements, then this is acceptable.
Tip
Make sure to checkout the language specific specifications for more info on this:
Resource modules MUST implement a common interface, e.g. the input’s data structures and properties within them (objects/arrays/dictionaries/maps), for the optional features/extension resources:
When a given version of an Azure resource used in a resource module reaches its end-of-life (EOL) and is no longer supported by Microsoft, the module owner SHOULD ensure that:
The module is aligned with these changes and only includes supported versions of the resource. This is typically achieved through the allowed values in the parameter that specifies the resource SKU or type.
The following notice is shown under the Notes section of the module’s readme.md. (If any related public announcement is available, it can also be linked to from the Notes section.):
“Certain versions of this Azure resource reached their end of life. The latest version of this module only includes supported versions of the resource. All unsupported versions have been removed from the related parameters.”
AND the related parameter’s description:
“Certain versions of this Azure resource reached their end of life. The latest version of this module only includes supported versions of the resource. All unsupported versions have been removed from this parameter.”
Resource modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Report missing or incorrect resource names to the AVM core team. Index corrections go through catalog generation and reviewed publication.
Bicep Resource Module Naming
Naming convention (module name for registry): avm/res/<hyphenated resource provider name>/<hyphenated ARM resource type>
Example: avm/res/compute/virtual-machine or avm/res/managed-identity/user-assigned-identity
Segments:
res defines this is a resource module
<hyphenated resource provider name> is the resource provider’s name after the Microsoft part, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Compute = compute, Microsoft.ManagedIdentity = managed-identity.
<hyphenated ARM resource type> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Compute/virtualMachines = virtual-machine, BUTMicrosoft.Network/trafficmanagerprofiles = trafficmanagerprofile - since trafficmanagerprofiles is all lower case as per the ARM API definition.
Bicep Child Module Naming
Naming convention (module name for registry):avm/res/<hyphenated resource provider name>/<hyphenated ARM resource type>/<hyphenated child resource type/<hyphenated grandchild resource type>/<etc.>
Example: avm/res/network/virtual-network/subnet or avm/res/storage/storage-account/blob-service/container
Segments:
res defines this is a resource module
<hyphenated resource provider name> is the resource provider’s name after the Microsoft part, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network = network.
<hyphenated ARM resource type> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network/virtualNetworks = virtual-network.
<hyphenated child resource type (to be repeated for grandchildren, etc.)> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network/virtualNetworks/subnets = subnet or Microsoft.Storage/storageAccounts/blobServices/containers = blob-service/container.
Terraform Resource Module Naming
Naming convention:
avm-res-<resource provider>-<ARM resource type> (module name for registry)
terraform-<provider>-avm-res-<resource provider>-<ARM resource type> (GitHub repository name to meet registry naming requirements)
Example: avm-res-compute-virtualmachine or avm-res-managedidentity-userassignedidentity
Segments:
<provider> is a legacy requirement of the Terraform registry. This must be set to azure
res defines this is a resource module
<resource provider> is the resource provider’s name after the Microsoft part, e.g., Microsoft.Compute = compute.
<ARM resource type> is the singular version of the word after the resource provider, e.g., Microsoft.Compute/virtualMachines = virtualmachine
ID: RMNFR3 - Category: Composition - RP Collaboration
Module owners (Microsoft FTEs) SHOULD reach out to the respective Resource Provider teams to build a partnership and collaboration on the modules creation, existence and long term maintenance.
Module owners MAY cross-reference other modules to build either Resource or Pattern modules.
However, they MUST be referenced only by a public registry reference to a pinned version e.g. br/public:avm/[res|ptn|utl]/<publishedModuleName>:>version<. They MUST NOT use local parent path references to a module e.g. ../../xxx/yyy.bicep.
The only exception to this rule are child modules as documented in BCPFR6.
Modules MUST NOT contain references to non-AVM modules.
ID: BCPFR2 - Category: Composition - Role Assignments Role Definition Mapping
Module owners MAY define common RBAC Role Definition names and IDs within a variable to allow consumers to define a RBAC Role Definition by their name rather than their ID, this should be self contained within the module themselves.
However, they MUST use only the official RBAC Role Definition name within the variable and nothing else.
To meet the requirements of BCPFR2, BCPNFR5 and BCPNFR6 you MUST use the below code sample in your AVM Modules to achieve this.
@description('''Required. You can provide either the display name (note not all roles are supported, check module documentation) of the role definition, or its fully qualified ID in the following format: `/providers/Microsoft.Authorization/roleDefinitions/c2f4ef07-c644-48eb-af81-4b1b4947fb11`.''')
param roleDefinitionIdOrName string
var builtInRbacRoleNames = {
Owner: '/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635' Contributor: '/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c' Reader: '/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7''Role Based Access Control Administrator (Preview)': '/providers/Microsoft.Authorization/roleDefinitions/f58310d9-a9f6-439a-9e8d-f62e7b41a168''User Access Administrator': '/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9'//Other RBAC Role Definitions Names & IDs can be added here as needed for your module }
var roleDefinitionIdMappedResult = (contains(builtInRbacRoleNames, roleDefinitionIdOrName) ? builtInRbacRoleNames[roleDefinitionIdOrName] : roleDefinitionIdOrName)
resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
//Other properties removed for ease of reading properties: {
roleDefinitionId: roleDefinitionIdMappedResult
//Other properties removed for ease of reading }
}
Parent templates MUST reference all their direct child-templates to allow for an end-to-end deployment experience. For example, the SQL server template must reference its child database module and encapsulate it in a loop to allow for the deployment of multiple databases.
@description('Optional. The databases to create in the server')
param databases databaseType[]?
resource server 'Microsoft.Sql/servers@(...)' = { (...) }
module server_databases 'database/main.bicep' = [for (database, index) in (databases ?? []): {
name: '${uniqueString(server.id, location)}-Sql-DB-${index}' params: {
serverName: server.name
(...)
}
}]
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
Each Bicep AVM module that lives within the Azure/bicep-registry-modules (BRM) repository in the avm directory MUST have the following directories and files:
/tests - (for unit tests and additional E2E/integration if required - e.g. Pester etc.)
/e2e - (all examples must deploy successfully - these will be used to automatically generate the examples in the README.md for the module)
/src - (for scripts and other files - e.g., scripts used by the template)
exampleFile.ps1
/modules - (for sub-modules only if used and NOT children of the primary resource - e.g. RBAC role assignments)
exampleTemplate.bicep
/main.bicep (AVM Module main .bicep file and entry point/orchestration module)
/main.json (auto generated and what is published to the MCR via BRM)
When a module references child, utility, or other modules, the deployment name MUST be deterministic. This means the deployment name must produce the same value for the same set of inputs across repeated deployments.
Why deterministic?
Azure Resource Manager has an 800-deployment limit per scope (resource group, subscription, management group, tenant). Non-deterministic names (e.g., those incorporating timestamps or utcNow()) create a new deployment object on every run, which can lead to this limit being reached over time.
While an automatic cleanup process exists for resource group and subscription scopes, it can take some time to take effect. Due to eventual consistency in the backend, the deployment count may not reflect the cleanup immediately, which can lead to failed deployments even when the actual number of deployments is below the 800 limit. Additionally, automatic cleanup does not apply to management group or tenant scopes.
We are actively working with the product team to enhance the cleanup process. In the meantime, deterministic deployment names provide a reliable way to keep deployment counts stable by overwriting previous deployment objects rather than creating new ones.
Deterministic deployment names cause Azure to overwrite the previous deployment object, keeping the deployment count stable regardless of how many times the module is deployed.
Requirement
Module owners MUST construct deployment names for referenced modules using uniqueString() seeded with the parent resource’s ID (<parentResource>.id) and location, rather than deployment().name, subscription().id, resourceGroup().id, utcNow(), or other non-deterministic or scope-level values.
A deterministic hash derived from the parent resource’s resource ID and deployment location. This is both unique per resource instance and stable across deployments.
<ChildModuleDescriptor>
A short, human-readable label identifying the child module being deployed (e.g., DB, Subnet, FederatedIdentityCred).
${index}
The loop index variable, included when deploying in a loop. Omit for single (non-looped) deployments.
location parameter
If location is not available, for example when deploying a global resource that does not have a location property, it is acceptable to omit it. However, the <parentResource>.idMUST always be included as the primary seed for uniqueString.
Why parent resource ID?
Using the parent resource’s ID as the uniqueString seed provides two critical properties:
Deterministic β the same parent resource always produces the same hash, so repeated deployments overwrite rather than accumulate.
Collision-free β different parent resource instances produce different hashes, so deploying multiple instances of the same module type within the same scope does not cause naming collisions.
Why not subscription().id and resourceGroup().id separately?
The parent resource’s ID (e.g., /subscriptions/.../resourceGroups/.../providers/.../resourceName) already contains the subscription ID and resource group ID as segments. Using <parentResource>.id as a single input to uniqueString captures all of this context in one value, keeping the code concise and readable rather than passing multiple scope-level values separately.
Supporting multiple deployments of the same module at the same scope
A common scenario is deploying the same module type more than once within the same scope β for example, two different SQL servers each with their own set of databases, or two user-assigned identities each with their own federated credentials. Because the parent resource ID is unique per resource instance, the resulting deployment names will differ even when the child module type and index are identical. This ensures that parallel deployments of the same module at the same scope do not collide.
Other approaches fail on one or both of these properties:
Approach
Deterministic?
Collision-free?
Issue
deployment().name
β
β
Changes every deployment; hits 800-limit
utcNow() / timestamps
β
β
Changes every deployment; hits 800-limit
subscription().id + resourceGroup().id
β
β
Same hash for all resources in the same RG; collisions when deploying multiple instances
ID: BCPNFR5 - Category: Composition - Role Assignments Role Definition Mapping Limits
As per BCPFR2, module owners MAY define common RBAC Role Definition names and IDs within a variable to allow consumers to define a RBAC Role Definition by their name rather than their ID.
Module owners SHOULD NOT map every RBAC Role Definition within this variable as it can cause the module to bloat in size and cause consumption issues later when stitched together with other modules due to the 4MB ARM Template size limit.
Therefore module owners SHOULD only map the most applicable and common RBAC Role Definition names for their module and SHOULD NOT exceed 15 RBAC Role Definitions in the variable.
Important
Remember if the RBAC Role Definition name is not included in the variable this does not mean it cannot be declared, used and assigned to an identity via an RBAC Role Assignment as part of a module, as any RBAC Role Definition can be specified via its ID without being in the variable.
The version value is in the form of MAJOR.MINOR. The PATCH version will be incremented by the CI automatically when publishing the module to the Public Bicep Registry once the corresponding pull request is merged. Therefore, contributions that would only require an update of the patch version, can keep the version.json file intact.
For example, the version value should be:
0.1 for new modules, so that they can be released as v0.1.0.
1.0 once the module owner signs off the module is stable enough for it’s first Major release of v1.0.0.
0.x for all feature updates between the first release v0.1.0 and the first Major release of v1.0.0.
Child resource modules MUST be stored in a subfolder of their parent resource module and named after the child resource’s singular name (ref), so that the path to the child resource folder is consistent with the hierarchy of its resource type. For example, Microsoft.Sql/servers may have dedicated child resources of type Microsoft.Sql/servers/databases. Hence, the SQL server database child module is stored in a database subfolder of the server parent folder.
sql
ββ server [module]
ββ database [child-module/resource]
In this folder, we recommend to place the child resource-template alongside a ReadMe & compiled JSON (to be generated via the default Set-AVMModule utility) and optionally further nest additional folders for its child resources.
There are several reasons to structure a module in this way. For example:
It allows a separation of concerns where each module can focus on its own properties and logic, while delegating most of a child-resource’s logic to its separate child module
It’s consistent with the provider namespace structure and makes modules easier to understand not only because they’re more aligned with set structure, but also are aligned with one another
As each module is its own ‘deployment’, it reduces limitations around nested loops
It enables module owners to publish child-modules as separate modules to the public registry, allowing consumers to make use of them directly [Ref child module publishing guidelines for details].
Note
In full transparency: The drawbacks of these additional deployments is an extended deployment period & a contribution to the 800 deployments limit. However, for AVM resource modules it was agreed that the advantages listed above outweigh these limitations.
Several resource types in Azure (e.g., role-assignments, budgets, etc.) may be deployed to more than one scope (e.g., subscription, management-group, etc.). In AVM, such modules can be implemented in one of two ways:
As pattern modules with one ‘orchestrating’ parent module using scoped sub-modules based on the input parameters provided
Note: Only the parent module is published. I.e., it is not possible to target e.g., the resource-group scoped sub-module directly.
As resource modules where each scope is implemented as a child-module of a non-published parent.
Note: Each child module is published, but not the parent. I.e., it is possible to target e.g., the resource-group scoped sub-module directly.
Tip
It is highly recommended to publish multi-scoped modules as resource modules as the solution provides the best user experience.
The following instructions consider all deployment scopes. Your module may only deploy to a subset of the same and you should map the conventions to your case.
To successfully implement a multi-scoped module as a pattern modules you have to adhere to the following convention:
The parent module MUST be implemented in the highest scope the resource provider supports (e.g., management-group)
The parent module MUST have one sub-module for each scope that the resource provider supports (e.g., management-group, subscription & resource-group)
Each sub-module MUST be implemented for the scope it is intended
The parent module MUST invoke each sub-module in the scope it is written for, using input parameters needed to target set scope (e.g., a subscription-id to invoke a module for set scope)
The parent module MUST have test cases to validate each sub-module
The parent module is the one that is versioned, published and maintains a changelog
The full folder structure may look like
πmain.bicep [Orchestrating module]
πmain.json [ARM JSON file of the module]
πversion.json [Version file of the module]
πREADME.md [Readme of the module]
πCHANGELOG.md [The changelog of the module]
β£ πmodules
β β£ πmanagement-group.bicep [Sub-module deploying to the mgmt-group scope (if applicable)]
β β£ πsubscription.bicep [Sub-module deploying to the subscription scope (if applicable)]
β β πresource-group.bicep [Sub-module deploying to the resource-group scope (if applicable)]
β πtests/e2e
β£ π mg.defaults
β β πmain.test.bicep [deploys parent template]
β£ π mg.waf-aligned
β β πmain.test.bicep [deploys parent template]
β£ π sub.defaults
β β πmain.test.bicep [deploys parent template with `subscriptionId` param]
β£ π sub.waf-aligned
β β πmain.test.bicep [deploys parent template with `subscriptionId` param]
β£ π rg.defaults
β β πmain.test.bicep [deploys parent template with `subscriptionId` & `resourceGroupName` params]
β π rg.waf-aligned
β πmain.test.bicep [deploys parent template with `subscriptionId` & `resourceGroupName` params]
Warning
Even if a consumer wants to deploy to one of the sub-scopes (e.g., subscription), the module must be deployed via its parent (e.g., management-group). This can be confusing for consumers at first and should be considered when implementing the solution.
Example: To use a role-assignment pattern module (which would be written for all scopes, with the parent targeting the management-group scope) to deploy role assignments to a resource group, a user would need to invoke New-AzManagementGroupDeployment and provide the parameters for both the subscription & resource-group to target. I.e., the user must have permissions to deploy to each scope.
Considerations when published as a resource module
The following instructions consider all deployment scopes. Your module may only deploy to a subset of the same and you should map the conventions to your case.
To successfully implement a multi-scoped module as a resource modules you have to adhere to the following convention:
The parent folder MUST contain a
main.bicep file
main.json file
README.md file
tests/e2e folder
One folder per each scope the resource provider can deploy to (either mg-scope, sub-scope or rg-scope).
Each child-module folder MUST be implemented as a proper child module, with a
main.bicep
main.json
version.json
README.md
CHANGELOG.md
file. Each child-module is maintained and versioned independently of the others.
The parent main.bicep MUST contain the following information
metadata name = '<Module Name> (Multi-Scope)'metadata description = '''
This module's child-modules deploy a <Placeholder> at a Management Group (mg-scope), Subscription (sub-scope) or Resource Group (rg-scope) scope.
> While this template is **not** published, you can find the actual published modules in the subfolders
>-`mg-scope`>-`sub-scope`>-`rg-scope`'''
targetScope = 'managementGroup'
updated with your module’s specifics
The tests/e2e folder MUST contain one instance of the require test cases per each scope, and MAY contain any additional test you see fit. In each case, the scope MUST be a prefix for the folder name. Each test case MUST reference the corresponding child module directly.
The full folder structure may look like
πmain.bicep [Skeleton module with disclaimer referring to the child-modules]
πmain.json [ARM JSON file of the module]
πREADME.md [The baseline readme, surfacing the metadata of the main.bicep file]
β£ πmg-scope
β β£πmain.bicep [Module deploying to mg-scope]
β β£πmain.json [ARM JSON file of the module]
β β£πREADME.md [Readme of the module]
β β£πversion.json [Version file of the module]
β βπCHANGELOG.md [The changelog of the module]
β£ πsub-scope
β β£πmain.bicep [Module deploying to sub-scope]
β β£πmain.json [ARM JSON file of the module]
β β£πREADME.md [Readme of the module]
β β£πversion.json [Version file of the module]
β βπCHANGELOG.md [The changelog of the module]
β£ πrg-scope
β β£πmain.bicep [Module deploying to rg-scope]
β β£πmain.json [ARM JSON file of the module]
β β£πREADME.md [Readme of the module]
β β£πversion.json [Version file of the module]
β βπCHANGELOG.md [The changelog of the module]
β πtests/e2e
β£ πmg-scope.defaults
β βπmain.test.bicep [references the 'mg-scope' child module template: '../../../mg-scope/main.bicep']
β£ πmg-scope.waf-aligned
β βπmain.test.bicep [references the 'mg-scope' child module template: '../../../mg-scope/main.bicep']
β£ πmg-scope.max
β βπmain.test.bicep [references the 'mg-scope' child module template: '../../../mg-scope/main.bicep']
β£ πsub-scope.defaults
β βπmain.test.bicep [references the 'sub-scope' child module template: '../../../sub-scope/main.bicep']
β£ πsub-scope.waf-aligned
β βπmain.test.bicep [references the 'sub-scope' child module template: '../../../sub-scope/main.bicep']
β£ πrg-scope.defaults
β βπmain.test.bicep [references the 'rg-scope' child module template: '../../../rg-scope/main.bicep']
β πrg-scope.waf-aligned
βπmain.test.bicep [references the 'rg-scope' child module template: '../../../rg-scope/main.bicep']
Important
Because each child-module is published on its own, you must ensure that each is registered in the MAR file before the modules can be published. The MAR file can only be accessed by Microsoft FTEs.
Please highlight the nature of your module in the issue when proposing it to AVM.
Inputs / Outputs
The content below is listed based on the following tags
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
Parameters/variables that pertain to the primary resource MUST NOT use the resource type in the name.
e.g., use sku, vs. virtualMachineSku/virtualmachine_sku
Another example for where RPs contain some of their name within a property, leave the property unchanged. E.g. Key Vault has a property called keySize, it is fine to leave as this and not remove the key part from the property/parameter name.
A resource module MUST use the following standard inputs:
name (no default)
location (if supported by the resource and not a global resource, then use Resource Group location, if resource supports Resource Groups, otherwise no default)
ID: BCPNFR1 - Category: Inputs - Complex data types - General
To simplify the consumption experience for module consumers when interacting with complex data types input parameters, mainly objects and arrays, the Bicep features of Resource-Derived Types or User-Defined TypesMUST be used and declared.
Tip
User-Defined Types are GA in Bicep as of version v0.21.1, Resource-Derived Types are GA as of version v0.34.1, please ensure you have this version(s) installed as a minimum.
Resource-Derived Types and User-Defined Types allow intellisense support in supported IDEs (e.g. Visual Studio Code) for complex input parameters using objects and array of objects.
v0.x Exemption
While we allow the release of major versions, starting with v1.0.0, retrofitting Resource-Derived Types and User-Defined Types for all modules will take a considerable amount of time.
Therefore, the addition of these features is currently NOT mandated/enforced. However, all modules MUST implement Resource-Derived Types and User-Defined Types prior to the release of their v1.0.0 version.
Similar to BCPNFR21, input parameters MUST implement decorators such as description & secure (if sensitive).
Further, input parameters SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
param threshold: int?
@description('Required. The SKU of your resource.')
@allowed([
'Basic''Premium''Standard'])
param sku string
User-defined types (UDTs) MUST always be singular and non-nullable. The configuration of either should instead be done directly at the parameter or output that uses the type.
For example, instead of
param subnets subnetsType
type subnetsType = { ... }[]?
the type should be defined like
param subnets subnetType[]?
type subnetType = { ... }
The primary reason for this requirement is clarity. If not defined directly at the parameter or output, a user would always be required to check the type to understand how e.g., a parameter is expected.
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
User-defined types (UDTs) SHOULD always be exported via the @export() annotation in every template they’re implemented in.
@export()
type subnetType = { ... }
Doing so has the benefit that other (e.g., parent) modules can import them and as such reduce code duplication. Also, if the module itself is published, users of the Public Bicep Registry can import the types independently of the module itself. One example where this can be useful is a pattern module that may re-use the same interface when referencing a module from the registry.
Similar to BCPNFR9, User-defined types (UDTs) MUST implement decorators such as description & secure (if sensitive). This is true for every property of the UDT, as well as the UDT itself.
Further, User-defined types SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('My type''s description.')
type myType = {
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
threshold: int?
@description('Required. The SKU of your resource.')
sku: ('Basic' | 'Premium' | 'Standard')
}
Modules will have lots of parameters that will differ in their requirement type (required, optional, etc.). To help consumers understand what each parameter’s requirement type is, module owners MUST add the requirement type to the beginning of each parameter’s description. Below are the requirement types with a definition and example for the description decorator:
Parameter Requirement Type
Definition
Example Description Decorator
Required
The parameter value must be provided. The parameter does not have a default value and hence the module expects and requires an input.
The parameter value can be optional or required based on a condition, mostly based on the value provided to other parameters. Should contain a sentence starting with ‘Required if (…).’ to explain the condition.
The parameter value is generated within the module and should not be specified as input in most cases. A common example of this is the utcNow() function that is only supported as the input for a parameter value, and not inside a variable.
When implementing any of the Bicep interface variants you MUST import their User-defined type (UDT) via the published AVM-Common-Types module.
When doing so, each type MUST be imported separately, right above the parameter or output that uses it.
import { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:*.*.*'@description('Optional. Array of role assignments to create.')
param roleAssignments roleAssignmentType[]?
import { diagnosticSettingFullType } from 'br/public:avm/utl/types/avm-common-types:*.*.*'@description('Optional. The diagnostic settings of the service.')
param diagnosticSettings diagnosticSettingFullType[]?
Importing them individually as opposed to one common block has several benefits such as
Individual versioning of types
If you must update the version for one type, you’re not exposed to unexpected changes to other types
Important
The import (...) block MUST not be added in between a parameter’s definition and its metadata. Doing so breaks the metadata’s binding to the parameter in question.
Finally, you should check for version updates regularly to ensure the resource module stays consistent with the specs. If the used AVM-Common-Types runs stale, the CI may eventually fail the module’s static tests.
Testing
The content below is listed based on the following tags
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
Module owners MUST test that child and extension resources and those Bicep or Terreform interface resources that are supported by their modules, are validated in E2E tests as per SNFR2 to ensure they deploy and are configured correctly.
These MAY be tested in a separate E2E test and DO NOT have to be tested in each E2E test.
ID: BCPNFR10 - Category: Testing - Test Bicep File Naming
Module owners MUST name their test .bicep files in the /tests/e2e/<defaults/waf-aligned/max/etc.> directories: main.test.bicep as the test framework (CI) relies upon this name.
ID: BCPNFR13 - Category: Testing - Test file metadata
By default, the ReadMe-generating utility will create usage examples headers based on each e2e folder’s name. Module owners MAY provide a custom name & description by specifying the metadata blocks name & description in their main.test.bicep test files.
For example:
metadata name = 'Using Customer-Managed-Keys with System-Assigned identity'metadata description = 'This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.'
would lead to a header in the module’s readme.md file along the lines of
### Example 1: _Using Customer-Managed-Keys with System-Assigned identity_
This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.
For each test case in the e2e folder, you can optionally add post-deployment Pester tests that are executed once the corresponding deployment completed and before the removal logic kicks in.
To leverage the feature you MUST:
Use Pester as a test framework in each test file
Name the file with the suffix "*.tests.ps1"
Place each test file the e2e test’s folder or any subfolder (e.g., e2e/max/myTest.tests.ps1 or e2e/max/tests/myTest.tests.ps1)
Implement an input parameter TestInputData in the following way:
Through this parameter you can make use of every output the main.test.bicep file returns, as well as the path to the test template file in case you want to extract data from it directly.
For example, with an output such as output resourceId string = testDeployment[1].outputs.resourceId defined in the main.test.bicep file, the $TestInputData would look like:
$TestInputData = @{
DeploymentOutputs = @{
resourceId = @{
Type = "String" Value = "/subscriptions/***/resourceGroups/dep-***-keyvault.vaults-kvvpe-rg/providers/Microsoft.KeyVault/vaults/***kvvpe001" }
}
ModuleTestFolderPath = "/home/runner/work/bicep-registry-modules/bicep-registry-modules/avm/res/key-vault/vault/tests/e2e/private-endpoint"}
ID: BCPRMNFR1 - Category: Testing - Expected Test Directories
Module owners MUST create the defaults, waf-aligned folders within their /tests/e2e/ directory in their resource module source code and SHOULD create a max folder also. Module owners CAN create additional folders as required. Each folder will be used as described for various test cases.
Note
If a module can deploy varying styles of the same resource, e.g., VMs can be Linux or Windows, each style should be tested as both defaults and waf-aligned. Each must then be used as suffixes in the directory name to denote the style, e.g., for a VM we would expect to see:
/tests/e2e/linux.defaults/main.test.bicep
/tests/e2e/linux.waf-aligned/main.test.bicep
/tests/e2e/windows.defaults/main.test.bicep
/tests/e2e/windows.waf-aligned/main.test.bicep
Defaults tests (MUST)
The defaults folder contains a test instance that deploys the module with the minimum set of required parameters.
This includes input parameters of type Required plus input parameters of type Conditional marked as required for WAF compliance.
This instance has heavy reliance on the default values for other input parameters. Parameters of type OptionalSHOULD NOT be used.
WAF aligned tests (MUST)
The waf-aligned folder contains a test instance that deploys the module in alignment with the best-practices of the Azure Well-Architected Framework.
This includes input parameters of type Required, parameters of type Conditional marked as required for WAF compliance, and parameters of type Optional useful for WAF compliance.
Parameters and dependencies which are not needed for WAF compliance, SHOULD NOT be included.
Max tests (SHOULD)
The max folder contains a test instance that deploys the module using a large parameter set, enabling most of the modules’ features.
The purpose of this instance is primarily parameter validation and not necessarily to serve as a real example scenario. Ideally, all features, extension resources and child resources should be enabled in this test, unless not possible due to conflicts, e.g., in case parameters are mutually exclusive.
Note
Please note that this test is not mandatory to have, but recommended for bulk parameter validation. It can be skipped in case the module parameter validation is covered already by additional, more scenario-specific tests.
Additional tests (CAN)
Additional folders CAN be created by module owners as required.
For example, to validate parameters not covered by the max test due to conflicts, or to provide a real example scenario for a specific use case.
Documentation
The content below is listed based on the following tags
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
The above formats are currently automatically taken & generated from the tests/e2e tests. It is enough to run the Set-ModuleReadMe or Set-AVMModule functions (from the utilities folder) to update the usage examples in the readme(s).
Note
Bicep Parameter Files (.bicepparam) are being reviewed and considered by the AVM team for the usability and features at this time and will likely be added in the future.
It is planned that these examples are automatically added to the module readme’s parameter descriptions when running either the Set-ModuleReadMe or Set-AVMModule scripts (available in the utilities folder).
Release / Publishing
The content below is listed based on the following tags
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
When a module to be published (i.e., that has a version.json file) is changed, an entry MUST be created in the CHANGELOG.md file in the module folder. A link to the latest version of the changelog file has to be included at the top of the file, just below the # Changelog line. It is surrounded by empty lines.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/<ptn|res|utl>/<namespace/modulename[/submodulePath]>/CHANGELOG.md).
For each new version, an entry MUST be created above all existing versions in the CHANGELOG.md file of the module.
## <version>
### Changes
- This changed
- And this also
### Breaking Changes
- None
Each version’s entry:
MUST contain two sections: Changes and Breaking Changes. At least one of them must have a meaningful entry and sections must not be left empty. A - None may be added as content for a section.
MUST exist only once.
All versions appear in descending order, which puts the most recent changes at the top.
What SHOULD be listed in the (Breaking) Changes section:
A CHANGELOG.md file in the module’s root folder MUST start with the # Changelog header, followed by an empty line and a link to the latest published version of the changelog file, followed by another empty line. A section for each published version follows. Newer versions are placed above older versions.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/res/aad/domain-service/CHANGELOG.md).
## 0.2.1
### Changes
- Updated the referenced AVM common types
### Breaking Changes
- None
## 0.2.0
### Changes
- Implemented the minCPU parameter
- Updated the referenced VirtualNetwork module
- Updated the referenced AVM common types
### Breaking Changes
- The minCPU parameter is mandatory
## 0.1.0
### Changes
- Initial Release
### Breaking Changes
- None
Each bullet point should start with a capital letter.
Manual Editing
It is possible to modify the changelog content any time, e.g., to add missing versions, which will not create a new release of the module itself. Please note the following requirements in all cases:
All versions in the file, need to be valid and available as published version
Every version needs the two sections ## Changes and ## Breaking Changes with content
Note
Azure Verified Modules are artifacts in the Microsoft Container Registry (MCR). Every version of a module exists as a tag in the Container Registry and can be listed at https://mcr.microsoft.com/v2/bicep/avm/(res|ptn|utl)/<namespace/modulename>/tags/list. For example, see the FinOps hub module tags.
Code Style
The content below is listed based on the following tags
To improve the usability of primitive module properties declared as strings, you SHOULD declare them using a type which better represents them, and apply any required casting in the module on behalf of the user.
For reference, please refer to the following examples:
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
The module-name-dropdown in the BRM AVM Module Issue templateMUST list top-level Bicep modules with Available or Orphaned status, sorted by module class and name. Proposed, deprecated, and child modules are excluded.
The module list sync workflow compares the dropdown with the published module catalog and updates it through a verified, auto-merged bot pull request. Module owners maintain root metadata and the required publication or deprecation evidence instead of editing the dropdown directly.
Telemetry
The content below is listed based on the following tags
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
To comply with specifications outlined in SFR3 & SFR4 you MUST incorporate the following code snippet into your modules. Place this code sample in the “top level” main.bicep file; it is not necessary to include it in any nested Bicep files (child modules), unless they are marked for direct publishing (Ref Child module publishing).
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
Utility Modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Example: avm/utl/general/get-environment or avm/utl/types/avm-common-types
Segments:
utl defines this as a utility module
<hyphenated grouping/category name> is a hierarchical grouping of utility modules by category, with each word separated by dashes, such as: general or types
<hyphenated utility module name> is a term describing the module’s function, with each word separated by dashes, e.g., get-environment = to get environmental details; avm-common-types = to use common types.
Terraform Utility Module Naming
Naming convention:
avm-utl-<utility module name> (Module name for registry)
terraform-<provider>-avm-utl-<utility module name> (GitHub repository name to meet registry naming requirements)
Example: avm-utl-sku-finder or avm-utl-naming
Segments:
<provider> is a legacy requirement of the Terraform registry. For AVM Terraform utility modules this MUST be set to azure (for example Azure/avm-utl-naming/azure). Older utility modules may still use the azurerm or azuread segments. These segments are names only and do not permit use of the AzureRM provider; TFFR3 still requires every module to be built with AzAPI.
utl defines this as a utility module
<utility module name> is a term describing the module’s function, e.g., sku-finder = to find available SKUs; naming = to handle naming conventions.
Module owners MAY cross-reference other modules to build either Resource or Pattern modules.
However, they MUST be referenced only by a public registry reference to a pinned version e.g. br/public:avm/[res|ptn|utl]/<publishedModuleName>:>version<. They MUST NOT use local parent path references to a module e.g. ../../xxx/yyy.bicep.
The only exception to this rule are child modules as documented in BCPFR6.
Modules MUST NOT contain references to non-AVM modules.
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
Each Bicep AVM module that lives within the Azure/bicep-registry-modules (BRM) repository in the avm directory MUST have the following directories and files:
/tests - (for unit tests and additional E2E/integration if required - e.g. Pester etc.)
/e2e - (all examples must deploy successfully - these will be used to automatically generate the examples in the README.md for the module)
/src - (for scripts and other files - e.g., scripts used by the template)
exampleFile.ps1
/modules - (for sub-modules only if used and NOT children of the primary resource - e.g. RBAC role assignments)
exampleTemplate.bicep
/main.bicep (AVM Module main .bicep file and entry point/orchestration module)
/main.json (auto generated and what is published to the MCR via BRM)
When a module references child, utility, or other modules, the deployment name MUST be deterministic. This means the deployment name must produce the same value for the same set of inputs across repeated deployments.
Why deterministic?
Azure Resource Manager has an 800-deployment limit per scope (resource group, subscription, management group, tenant). Non-deterministic names (e.g., those incorporating timestamps or utcNow()) create a new deployment object on every run, which can lead to this limit being reached over time.
While an automatic cleanup process exists for resource group and subscription scopes, it can take some time to take effect. Due to eventual consistency in the backend, the deployment count may not reflect the cleanup immediately, which can lead to failed deployments even when the actual number of deployments is below the 800 limit. Additionally, automatic cleanup does not apply to management group or tenant scopes.
We are actively working with the product team to enhance the cleanup process. In the meantime, deterministic deployment names provide a reliable way to keep deployment counts stable by overwriting previous deployment objects rather than creating new ones.
Deterministic deployment names cause Azure to overwrite the previous deployment object, keeping the deployment count stable regardless of how many times the module is deployed.
Requirement
Module owners MUST construct deployment names for referenced modules using uniqueString() seeded with the parent resource’s ID (<parentResource>.id) and location, rather than deployment().name, subscription().id, resourceGroup().id, utcNow(), or other non-deterministic or scope-level values.
A deterministic hash derived from the parent resource’s resource ID and deployment location. This is both unique per resource instance and stable across deployments.
<ChildModuleDescriptor>
A short, human-readable label identifying the child module being deployed (e.g., DB, Subnet, FederatedIdentityCred).
${index}
The loop index variable, included when deploying in a loop. Omit for single (non-looped) deployments.
location parameter
If location is not available, for example when deploying a global resource that does not have a location property, it is acceptable to omit it. However, the <parentResource>.idMUST always be included as the primary seed for uniqueString.
Why parent resource ID?
Using the parent resource’s ID as the uniqueString seed provides two critical properties:
Deterministic β the same parent resource always produces the same hash, so repeated deployments overwrite rather than accumulate.
Collision-free β different parent resource instances produce different hashes, so deploying multiple instances of the same module type within the same scope does not cause naming collisions.
Why not subscription().id and resourceGroup().id separately?
The parent resource’s ID (e.g., /subscriptions/.../resourceGroups/.../providers/.../resourceName) already contains the subscription ID and resource group ID as segments. Using <parentResource>.id as a single input to uniqueString captures all of this context in one value, keeping the code concise and readable rather than passing multiple scope-level values separately.
Supporting multiple deployments of the same module at the same scope
A common scenario is deploying the same module type more than once within the same scope β for example, two different SQL servers each with their own set of databases, or two user-assigned identities each with their own federated credentials. Because the parent resource ID is unique per resource instance, the resulting deployment names will differ even when the child module type and index are identical. This ensures that parallel deployments of the same module at the same scope do not collide.
Other approaches fail on one or both of these properties:
Approach
Deterministic?
Collision-free?
Issue
deployment().name
β
β
Changes every deployment; hits 800-limit
utcNow() / timestamps
β
β
Changes every deployment; hits 800-limit
subscription().id + resourceGroup().id
β
β
Same hash for all resources in the same RG; collisions when deploying multiple instances
The version value is in the form of MAJOR.MINOR. The PATCH version will be incremented by the CI automatically when publishing the module to the Public Bicep Registry once the corresponding pull request is merged. Therefore, contributions that would only require an update of the patch version, can keep the version.json file intact.
For example, the version value should be:
0.1 for new modules, so that they can be released as v0.1.0.
1.0 once the module owner signs off the module is stable enough for it’s first Major release of v1.0.0.
0.x for all feature updates between the first release v0.1.0 and the first Major release of v1.0.0.
Inputs / Outputs
The content below is listed based on the following tags
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
ID: BCPNFR1 - Category: Inputs - Complex data types - General
To simplify the consumption experience for module consumers when interacting with complex data types input parameters, mainly objects and arrays, the Bicep features of Resource-Derived Types or User-Defined TypesMUST be used and declared.
Tip
User-Defined Types are GA in Bicep as of version v0.21.1, Resource-Derived Types are GA as of version v0.34.1, please ensure you have this version(s) installed as a minimum.
Resource-Derived Types and User-Defined Types allow intellisense support in supported IDEs (e.g. Visual Studio Code) for complex input parameters using objects and array of objects.
v0.x Exemption
While we allow the release of major versions, starting with v1.0.0, retrofitting Resource-Derived Types and User-Defined Types for all modules will take a considerable amount of time.
Therefore, the addition of these features is currently NOT mandated/enforced. However, all modules MUST implement Resource-Derived Types and User-Defined Types prior to the release of their v1.0.0 version.
Similar to BCPNFR21, input parameters MUST implement decorators such as description & secure (if sensitive).
Further, input parameters SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
param threshold: int?
@description('Required. The SKU of your resource.')
@allowed([
'Basic''Premium''Standard'])
param sku string
User-defined types (UDTs) MUST always be singular and non-nullable. The configuration of either should instead be done directly at the parameter or output that uses the type.
For example, instead of
param subnets subnetsType
type subnetsType = { ... }[]?
the type should be defined like
param subnets subnetType[]?
type subnetType = { ... }
The primary reason for this requirement is clarity. If not defined directly at the parameter or output, a user would always be required to check the type to understand how e.g., a parameter is expected.
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
User-defined types (UDTs) SHOULD always be exported via the @export() annotation in every template they’re implemented in.
@export()
type subnetType = { ... }
Doing so has the benefit that other (e.g., parent) modules can import them and as such reduce code duplication. Also, if the module itself is published, users of the Public Bicep Registry can import the types independently of the module itself. One example where this can be useful is a pattern module that may re-use the same interface when referencing a module from the registry.
Similar to BCPNFR9, User-defined types (UDTs) MUST implement decorators such as description & secure (if sensitive). This is true for every property of the UDT, as well as the UDT itself.
Further, User-defined types SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('My type''s description.')
type myType = {
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
threshold: int?
@description('Required. The SKU of your resource.')
sku: ('Basic' | 'Premium' | 'Standard')
}
Modules will have lots of parameters that will differ in their requirement type (required, optional, etc.). To help consumers understand what each parameter’s requirement type is, module owners MUST add the requirement type to the beginning of each parameter’s description. Below are the requirement types with a definition and example for the description decorator:
Parameter Requirement Type
Definition
Example Description Decorator
Required
The parameter value must be provided. The parameter does not have a default value and hence the module expects and requires an input.
The parameter value can be optional or required based on a condition, mostly based on the value provided to other parameters. Should contain a sentence starting with ‘Required if (…).’ to explain the condition.
The parameter value is generated within the module and should not be specified as input in most cases. A common example of this is the utcNow() function that is only supported as the input for a parameter value, and not inside a variable.
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
ID: BCPNFR10 - Category: Testing - Test Bicep File Naming
Module owners MUST name their test .bicep files in the /tests/e2e/<defaults/waf-aligned/max/etc.> directories: main.test.bicep as the test framework (CI) relies upon this name.
ID: BCPNFR13 - Category: Testing - Test file metadata
By default, the ReadMe-generating utility will create usage examples headers based on each e2e folder’s name. Module owners MAY provide a custom name & description by specifying the metadata blocks name & description in their main.test.bicep test files.
For example:
metadata name = 'Using Customer-Managed-Keys with System-Assigned identity'metadata description = 'This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.'
would lead to a header in the module’s readme.md file along the lines of
### Example 1: _Using Customer-Managed-Keys with System-Assigned identity_
This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.
For each test case in the e2e folder, you can optionally add post-deployment Pester tests that are executed once the corresponding deployment completed and before the removal logic kicks in.
To leverage the feature you MUST:
Use Pester as a test framework in each test file
Name the file with the suffix "*.tests.ps1"
Place each test file the e2e test’s folder or any subfolder (e.g., e2e/max/myTest.tests.ps1 or e2e/max/tests/myTest.tests.ps1)
Implement an input parameter TestInputData in the following way:
Through this parameter you can make use of every output the main.test.bicep file returns, as well as the path to the test template file in case you want to extract data from it directly.
For example, with an output such as output resourceId string = testDeployment[1].outputs.resourceId defined in the main.test.bicep file, the $TestInputData would look like:
$TestInputData = @{
DeploymentOutputs = @{
resourceId = @{
Type = "String" Value = "/subscriptions/***/resourceGroups/dep-***-keyvault.vaults-kvvpe-rg/providers/Microsoft.KeyVault/vaults/***kvvpe001" }
}
ModuleTestFolderPath = "/home/runner/work/bicep-registry-modules/bicep-registry-modules/avm/res/key-vault/vault/tests/e2e/private-endpoint"}
ID: BCPRMNFR1 - Category: Testing - Expected Test Directories
Module owners MUST create the defaults, waf-aligned folders within their /tests/e2e/ directory in their resource module source code and SHOULD create a max folder also. Module owners CAN create additional folders as required. Each folder will be used as described for various test cases.
Note
If a module can deploy varying styles of the same resource, e.g., VMs can be Linux or Windows, each style should be tested as both defaults and waf-aligned. Each must then be used as suffixes in the directory name to denote the style, e.g., for a VM we would expect to see:
/tests/e2e/linux.defaults/main.test.bicep
/tests/e2e/linux.waf-aligned/main.test.bicep
/tests/e2e/windows.defaults/main.test.bicep
/tests/e2e/windows.waf-aligned/main.test.bicep
Defaults tests (MUST)
The defaults folder contains a test instance that deploys the module with the minimum set of required parameters.
This includes input parameters of type Required plus input parameters of type Conditional marked as required for WAF compliance.
This instance has heavy reliance on the default values for other input parameters. Parameters of type OptionalSHOULD NOT be used.
WAF aligned tests (MUST)
The waf-aligned folder contains a test instance that deploys the module in alignment with the best-practices of the Azure Well-Architected Framework.
This includes input parameters of type Required, parameters of type Conditional marked as required for WAF compliance, and parameters of type Optional useful for WAF compliance.
Parameters and dependencies which are not needed for WAF compliance, SHOULD NOT be included.
Max tests (SHOULD)
The max folder contains a test instance that deploys the module using a large parameter set, enabling most of the modules’ features.
The purpose of this instance is primarily parameter validation and not necessarily to serve as a real example scenario. Ideally, all features, extension resources and child resources should be enabled in this test, unless not possible due to conflicts, e.g., in case parameters are mutually exclusive.
Note
Please note that this test is not mandatory to have, but recommended for bulk parameter validation. It can be skipped in case the module parameter validation is covered already by additional, more scenario-specific tests.
Additional tests (CAN)
Additional folders CAN be created by module owners as required.
For example, to validate parameters not covered by the max test due to conflicts, or to provide a real example scenario for a specific use case.
Documentation
The content below is listed based on the following tags
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
The above formats are currently automatically taken & generated from the tests/e2e tests. It is enough to run the Set-ModuleReadMe or Set-AVMModule functions (from the utilities folder) to update the usage examples in the readme(s).
Note
Bicep Parameter Files (.bicepparam) are being reviewed and considered by the AVM team for the usability and features at this time and will likely be added in the future.
It is planned that these examples are automatically added to the module readme’s parameter descriptions when running either the Set-ModuleReadMe or Set-AVMModule scripts (available in the utilities folder).
Release / Publishing
The content below is listed based on the following tags
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
When a module to be published (i.e., that has a version.json file) is changed, an entry MUST be created in the CHANGELOG.md file in the module folder. A link to the latest version of the changelog file has to be included at the top of the file, just below the # Changelog line. It is surrounded by empty lines.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/<ptn|res|utl>/<namespace/modulename[/submodulePath]>/CHANGELOG.md).
For each new version, an entry MUST be created above all existing versions in the CHANGELOG.md file of the module.
## <version>
### Changes
- This changed
- And this also
### Breaking Changes
- None
Each version’s entry:
MUST contain two sections: Changes and Breaking Changes. At least one of them must have a meaningful entry and sections must not be left empty. A - None may be added as content for a section.
MUST exist only once.
All versions appear in descending order, which puts the most recent changes at the top.
What SHOULD be listed in the (Breaking) Changes section:
A CHANGELOG.md file in the module’s root folder MUST start with the # Changelog header, followed by an empty line and a link to the latest published version of the changelog file, followed by another empty line. A section for each published version follows. Newer versions are placed above older versions.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/res/aad/domain-service/CHANGELOG.md).
## 0.2.1
### Changes
- Updated the referenced AVM common types
### Breaking Changes
- None
## 0.2.0
### Changes
- Implemented the minCPU parameter
- Updated the referenced VirtualNetwork module
- Updated the referenced AVM common types
### Breaking Changes
- The minCPU parameter is mandatory
## 0.1.0
### Changes
- Initial Release
### Breaking Changes
- None
Each bullet point should start with a capital letter.
Manual Editing
It is possible to modify the changelog content any time, e.g., to add missing versions, which will not create a new release of the module itself. Please note the following requirements in all cases:
All versions in the file, need to be valid and available as published version
Every version needs the two sections ## Changes and ## Breaking Changes with content
Note
Azure Verified Modules are artifacts in the Microsoft Container Registry (MCR). Every version of a module exists as a tag in the Container Registry and can be listed at https://mcr.microsoft.com/v2/bicep/avm/(res|ptn|utl)/<namespace/modulename>/tags/list. For example, see the FinOps hub module tags.
Code Style
The content below is listed based on the following tags
To improve the usability of primitive module properties declared as strings, you SHOULD declare them using a type which better represents them, and apply any required casting in the module on behalf of the user.
For reference, please refer to the following examples:
Any updates to existing or new specifications for Terraform must be submitted as a draft for review by Azure Terraform PG/Engineering(@Azure/terraform-avm) and AVM core team(@Azure/avm-core-team).
AzAPI is mandatory for AVM Terraform modules
Every new AVM Terraform module β resource, pattern, or utility β MUST use the AzAPI provider for every control-plane resource and supported data-plane operation. This applies throughout the module repository, including submodules, examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets.
AzureRM is permitted only for a specific data-plane/non-ARM API operation that AzAPI cannot implement, under the narrow exception in TFFR3. It is never permitted for an ARM control-plane resource or as a convenience alternative to AzAPI.
This requirement is intentional and is driven by the following factors:
Built-in retries and error handling. AzAPI exposes first-class retry and timeouts blocks, including regex-based error matching, which lets modules handle transient failures (for example, scope locks being removed or eventual-consistency errors) deterministically and without external workarounds.
Pre-flight validation. AzAPI performs ARM API pre-flight checks at plan time, surfacing many configuration errors before an apply is attempted. This produces faster feedback loops and fewer partially-deployed resources.
Day-zero access to the latest Azure features. Because AzAPI talks directly to the Azure Resource Manager REST API, modules can adopt new resource types, properties and API versions as soon as they ship in Azure β without waiting for an AzureRM provider release.
Alignment with Bicep and ARM. AzAPI uses the same resource type identifiers (e.g. Microsoft.KeyVault/vaults@2023-07-01) and the same property shape as Bicep and ARM templates. This makes it dramatically easier to translate documentation, samples and Bicep modules into Terraform, and keeps Bicep and Terraform AVM modules conceptually aligned.
Close partnership with the Azure engineering teams. AzAPI is built and maintained in close collaboration with the Azure Resource Provider engineering teams. Issues in AzAPI can be triaged directly against the underlying ARM behavior, and the AVM team works directly with the AzAPI engineering team on roadmap and breaking changes.
Consistency across the AVM ecosystem. Standardizing on AzAPI means every AVM Terraform module uses the same patterns for identity, diagnostic settings, role assignments, locks and private endpoints β primarily through the Azure/avm-utl-interfaces/azure utility module β which simplifies authoring, review and consumer experience.
What changed recently?
See what specifications changed in the last 30 days...
This chapter details the interfaces/schemas for the AVM Resource Modules features/extension resources as referenced in RMFR4 and RMFR5.
Diagnostic Settings
Important
Allowed values for logs and metric categories or category groups MUST NOT be specified to keep the module implementation evergreen for any new categories or category groups added by RPs, without module owners having to update a list of allowed values and cut a new release of their module.
variable"diagnostic_settings" {
type = map(object({
name = optional(string, null)
logs = optional(set(object({
category = optional(string, null)
category_group = optional(string, null)
enabled = optional(bool, true)
retention_policy = optional(object({
days = optional(number, 0)
enabled = optional(bool, false)
}), {})
})), [])
metrics = optional(set(object({
category = optional(string, null)
enabled = optional(bool, true)
retention_policy = optional(object({
days = optional(number, 0)
enabled = optional(bool, false)
}), {})
})), [])
log_analytics_destination_type = optional(string, "Dedicated")
workspace_resource_id = optional(string, null)
storage_account_resource_id = optional(string, null)
event_hub_authorization_rule_resource_id = optional(string, null)
event_hub_name = optional(string, null)
marketplace_partner_resource_id = optional(string, null)
}))
default = {}
nullable = falsevalidation {
condition = alltrue([for_, vin var.diagnostic_settings: contains(["Dedicated", "AzureDiagnostics"], v.log_analytics_destination_type)])
error_message = "Log analytics destination type must be one of: 'Dedicated', 'AzureDiagnostics'." }
validation {
condition = alltrue([
for_, vin var.diagnostic_settings:alltrue([
forlinv.logs: (l.category!=null) != (l.category_group!=null)
])
])
error_message = "Each log entry must set exactly one of `category` or `category_group`." }
validation {
condition = alltrue(
[
for_, vin var.diagnostic_settings:v.workspace_resource_id!=null||v.storage_account_resource_id!=null||v.event_hub_authorization_rule_resource_id!=null||v.marketplace_partner_resource_id!=null ]
)
error_message = "At least one of `workspace_resource_id`, `storage_account_resource_id`, `marketplace_partner_resource_id`, or `event_hub_authorization_rule_resource_id`, must be set." }
validation {
condition = alltrue([
for_, vin var.diagnostic_settings:v.workspace_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.OperationalInsights/workspaces", v.workspace_resource_id))
])
error_message = "Each `workspace_resource_id` must be a valid Log Analytics workspace resource ID, or null." }
validation {
condition = alltrue([
for_, vin var.diagnostic_settings:v.storage_account_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.Storage/storageAccounts", v.storage_account_resource_id))
])
error_message = "Each `storage_account_resource_id` must be a valid storage account resource ID, or null." }
validation {
condition = alltrue([
for_, vin var.diagnostic_settings:v.event_hub_authorization_rule_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.EventHub/namespaces/authorizationRules", v.event_hub_authorization_rule_resource_id))
])
error_message = "Each `event_hub_authorization_rule_resource_id` must be a valid Event Hub namespace authorization rule resource ID, or null." }
description = <<DESCRIPTION A map of diagnostic settings to create on the resource. The map key is deliberately arbitrary to avoid issues where map keys maybe unknown at plan time.
- `name` - (Optional) The name of the diagnostic setting. One will be generated if not set, however this will not be unique if you want to create multiple diagnostic setting resources.
- `logs` - (Optional) A set of log entries to send to the destination. Each entry has the following attributes:
- `category` - (Optional) The name of a specific log category to enable. Mutually exclusive with `category_group`.
- `category_group` - (Optional) The name of a log category group to enable (for example, `allLogs` or `audit`). Mutually exclusive with `category`.
- `enabled` - (Optional) Whether the log entry is enabled. Defaults to `true`.
- `retention_policy` - (Optional) The retention policy for the log entry.
- `days` - (Optional) The retention period in days. Defaults to `0` (retain indefinitely).
- `enabled` - (Optional) Whether the retention policy is enabled. Defaults to `false`.
- `metrics` - (Optional) A set of metric entries to send to the destination. Each entry has the following attributes:
- `category` - (Optional) The name of the metric category to enable.
- `enabled` - (Optional) Whether the metric entry is enabled. Defaults to `true`.
- `retention_policy` - (Optional) The retention policy for the metric entry, with the same `days` and `enabled` attributes as `logs.retention_policy`.
- `log_analytics_destination_type` - (Optional) The destination type for the diagnostic setting. Possible values are `Dedicated` and `AzureDiagnostics`. Defaults to `Dedicated`.
- `workspace_resource_id` - (Optional) The resource ID of the log analytics workspace to send logs and metrics to.
- `storage_account_resource_id` - (Optional) The resource ID of the storage account to send logs and metrics to.
- `event_hub_authorization_rule_resource_id` - (Optional) The resource ID of the event hub authorization rule to send logs and metrics to.
- `event_hub_name` - (Optional) The name of the event hub. If none is specified, the default event hub will be selected.
- `marketplace_partner_resource_id` - (Optional) The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs.
DESCRIPTION }
module"avm_interfaces" {
source = "Azure/avm-utl-interfaces/azure"version = "0.6.0" # check latest version at the time of use
diagnostic_settings_v2 = var.diagnostic_settingsdiagnostic_settings_scope = azapi_resource.this.id } # Sample resource
resource"azapi_resource""diagnostic_settings" {
for_each = module.avm_interfaces.diagnostic_settings_azapi_v2type = each.value.typename = each.value.nameparent_id = each.value.parent_idbody = each.value.body }
In the provided example for Diagnostic Settings, both logs and metrics are enabled for the associated resource. However, it is IMPORTANT to note that certain resources may not support both diagnostic setting types/categories. In such cases, the resource configuration MUST be modified accordingly to ensure proper functionality and compliance with system requirements.
Role Assignments
variable"role_assignments" {
type = map(object({
name = optional(string, null)
role_definition_id_or_name = stringprincipal_id = stringdescription = optional(string, null)
skip_service_principal_aad_check = optional(bool, false)
condition = optional(string, null)
condition_version = optional(string, null)
delegated_managed_identity_resource_id = optional(string, null)
principal_type = optional(string, null)
}))
default = {}
nullable = falsedescription = <<DESCRIPTION A map of role assignments to create on the <RESOURCE>. The map key is deliberately arbitrary to avoid issues where map keys maybe unknown at plan time.
- `name` - (Optional) The name of the role assignment. If not set, a random UUID will be generated. Changing this forces the creation of a new resource.
- `role_definition_id_or_name` - The ID or name of the role definition to assign to the principal.
- `principal_id` - The ID of the principal to assign the role to.
- `description` - (Optional) The description of the role assignment.
- `skip_service_principal_aad_check` - (Optional) If set to true, skips the Azure Active Directory check for the service principal in the tenant. Defaults to false.
- `condition` - (Optional) The condition which will be used to scope the role assignment.
- `condition_version` - (Optional) The version of the condition syntax. Leave as `null` if you are not using a condition, if you are then valid values are '2.0'.
- `delegated_managed_identity_resource_id` - (Optional) The delegated Azure Resource Id which contains a Managed Identity. Changing this forces a new resource to be created. This field is only used in cross-tenant scenario.
- `principal_type` - (Optional) The type of the `principal_id`. Possible values are `User`, `Group` and `ServicePrincipal`. It is necessary to explicitly set this attribute when creating role assignments if the principal creating the assignment is constrained by ABAC rules that filters on the PrincipalType attribute.
> Note: only set `skip_service_principal_aad_check` to true if you are assigning a role to a service principal.
DESCRIPTIONvalidation {
condition = alltrue([
for_, vin var.role_assignments:v.delegated_managed_identity_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", v.delegated_managed_identity_resource_id))
])
error_message = "Each `role_assignments[*].delegated_managed_identity_resource_id` must be a valid user-assigned managed identity resource ID, or null." }
}
module"avm_interfaces" {
source = "Azure/avm-utl-interfaces/azure"version = "0.6.0" # check latest version at the time of use
role_assignments = var.role_assignmentsrole_assignment_definition_scope = azapi_resource.this.id } # Example resource declaration
resource"azapi_resource""role_assignments" {
for_each = module.avm_interfaces.role_assignments_azapitype = each.value.typename = each.value.nameparent_id = each.value.parent_idbody = each.value.bodyretry = {
error_message_regex = ["ScopeLocked"] # retry if a lock is in place on the scope and has only just been removed
interval_seconds = 15max_interval_seconds = 60 }
timeouts {
delete = "5m" }
}
Details on child, extension and cross-referenced resources:
Modules MUST support Role Assignments on child, extension and cross-referenced resources as well as the primary resource via parameters/variables
The name attribute is optional in both the top-level role_assignments interface and private_endpoints[*].role_assignments. Omitting it remains valid and backward compatible; a random UUID is generated when no name is supplied.
During migration, tooling MAY temporarily accept the older exact type declaration without the name attribute. New and updated modules SHOULD use the canonical schema, including name = optional(string, null).
Resource Locks
variable"lock" {
type = object({
kind = stringname = optional(string, null)
notes = optional(string, null)
})
default = nulldescription = <<DESCRIPTION Controls the Resource Lock configuration for this resource. The following properties can be specified:
- `kind` - (Required) The type of lock. Possible values are `\"CanNotDelete\"` and `\"ReadOnly\"`.
- `name` - (Optional) The name of the lock. If not specified, a name will be generated based on the `kind` value. Changing this forces the creation of a new resource.
- `notes` - (Optional) Notes about the lock. This value maps to `Microsoft.Authorization/locks.properties.notes`.
DESCRIPTIONvalidation {
condition = var.lock!=null? contains(["CanNotDelete", "ReadOnly"], var.lock.kind) :trueerror_message = "Lock kind must be either `\"CanNotDelete\"` or `\"ReadOnly\"`." }
}
module"avm_interfaces" {
source = "Azure/avm-utl-interfaces/azure"version = "0.6.0" # check latest version at the time of use
lock = var.locklock_scope = azapi_resource.this.id } # Example resource implementation
resource"azapi_resource""lock" {
count = var.lock!=null?1:0type = module.avm_interfaces.lock_azapi.typename = module.avm_interfaces.lock_azapi.nameparent_id = module.avm_interfaces.lock_azapi.parent_idbody = module.avm_interfaces.lock_azapi.body }
Locks SHOULD be able to be set for child resources of the primary resource in resource modules
Details on cross-referenced resources:
Locks MUST be automatically applied to cross-referenced resources if the primary resource has a lock applied.
This MUST also be able to be turned off for each of the cross-referenced resources by the module consumer via a parameter/variable if they desire
An example of this is a Key Vault module that has a Private Endpoints enabled. If a lock is applied to the Key Vault via the lock parameter/variable then the lock should also be applied to the Private Endpoint automatically, unless the privateEndpointLock/private_endpoint_lock (example name) parameter/variable is set to None
Important
In Terraform, locks become part of the resource graph and suitable depends_on values should be set. Note that, during a destroy operation, Terraform will remove the locks before removing the resource itself, reducing the usefulness of the lock somewhat. Also note, due to eventual consistency in Azure, use of locks can cause destroy operations to fail as the lock may not have been fully removed by the time the destroy operation is executed.
Tags
variable"tags" {
type = map(string)
default = nulldescription = "(Optional) Tags of the resource." }
variable"resource_tags" {
type = object({
resources = optional(object({
this = optional(map(string))
child = optional(map(string))
}))
modules = optional(object({
child = optional(object({
resources = optional(object({
this = optional(map(string))
}))
}))
}))
})
default = nulldescription = "(Optional) Per-resource tag overrides." }
The tags variable is the module-wide fallback and common interface. It MUST remain a map(string) with a default of null. A module that does not expose per-resource overrides can continue to assign tags = var.tags directly.
Modules MAY add the typed resource_tags variable when consumers need to replace tags for individual resources or resources declared by submodules. The variable MUST default to null and use this canonical shape:
resources is an optional object whose attribute names match Terraform resource block labels in the current module.
modules is an optional object whose attribute names match Terraform module block labels. Each value repeats that submodule’s typed resource_tags shape.
The resources and modules namespaces keep identical resource and module labels unambiguous. For example, resource_tags.resources.child and resource_tags.modules.child identify different blocks.
Each module MUST declare a deterministic object type containing only its supported resource and submodule labels. Open-ended maps of objects or any types MUST NOT replace the typed shape.
Every namespace, resource label, and module label MUST be optional without an inline default. The object MUST contain at least one resource label, either directly or below a module label.
For every tag-capable resource, an omitted or null resource override inherits var.tags. A supplied map replaces var.tags completely for that resource; implementations MUST NOT merge the two maps. An empty map therefore deliberately applies no tags. A resource block override applies uniformly to every instance created from that block with count or for_each. This expression implements the required precedence for a resource labeled this:
Tags MUST propagate by default to tag-capable child, extension, and cross-referenced resources. A parent module passes the fallback and the nested override independently:
The child module applies the same precedence to its own resource labels. Omitting resource_tags.modules.child, or setting it to null, leaves every child resource on the tags fallback unless a more specific non-null override is supplied.
Managed Identities
variable"managed_identities" {
type = object({
system_assigned = optional(bool, false)
user_assigned_resource_ids = optional(set(string), [])
})
default = {}
nullable = falsedescription = <<DESCRIPTION Controls the Managed Identity configuration on this resource. The following properties can be specified:
- `system_assigned` - (Optional) Specifies if the System Assigned Managed Identity should be enabled.
- `user_assigned_resource_ids` - (Optional) Specifies a list of User Assigned Managed Identity resource IDs to be assigned to this resource.
DESCRIPTIONvalidation {
condition = alltrue([
foridin var.managed_identities.user_assigned_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", id))
])
error_message = "Each entry in `managed_identities.user_assigned_resource_ids` must be a valid user-assigned managed identity resource ID." }
}
module"avm_interfaces" {
source = "Azure/avm-utl-interfaces/azure"version = "0.6.0" # check latest version at the time of use
managed_identities = var.managed_identities } # Example identity block on the parent azapi_resource. The avm_interfaces
# module returns a single object with the correct `type` and `identity_ids`
# values, including the case when no identity is configured (in which case
# the for_each is empty and no identity block is rendered).
#
# Note: AzAPI accepts a single `identity` block. The dynamic block below
# renders zero or one block depending on whether a managed identity is
# configured. The same pattern works for resources that only support
# SystemAssigned or only UserAssigned identities.
resource"azapi_resource""this" { # ...other arguments...
dynamic"identity" {
for_each = module.avm_interfaces.managed_identities_azapi!=null? [module.avm_interfaces.managed_identities_azapi] : []
content {
type = identity.value.typeidentity_ids = identity.value.identity_ids }
}
}
Reason for differences in User Assigned data type in languages:
We do not forsee the Managed Identity Resource Provider team to ever add additional properties within the empty object ({}) value required on the input of a User Assigned Managed Identity.
In Bicep we therefore have removed the need for this to be declared and just converted it to a simple array of Resource IDs
However, in Terraform we have left it as a object/map as this simplifies for_each and other loop mechanisms and provides more consistency in plan, apply, destroy operations
Especially when adding, removing or changing the order of the User Assigned Managed Identities as they are declared
Private Endpoints
# In this example we only support one service, e.g. Key Vault.
# If your service has multiple private endpoint services, then expose the service name.
variable"private_endpoints_manage_dns_zone_group" {
type = booldefault = truenullable = falsedescription = "Whether to manage private DNS zone groups with this module. If set to false, you must manage private DNS zone groups externally, e.g. using Azure Policy." }
variable"private_endpoints" {
type = map(object({
name = optional(string, null)
role_assignments = optional(map(object({
name = optional(string, null)
role_definition_id_or_name = stringprincipal_id = stringdescription = optional(string, null)
skip_service_principal_aad_check = optional(bool, false)
condition = optional(string, null)
condition_version = optional(string, null)
delegated_managed_identity_resource_id = optional(string, null)
principal_type = optional(string, null)
})), {})
lock = optional(object({
kind = stringname = optional(string, null)
notes = optional(string, null)
}), null)
tags = optional(map(string), null)
subnet_resource_id = stringsubresource_name = optional(string, null) # only required if the parent resource exposes more than one private endpoint sub-resource
private_dns_zone_group_name = optional(string, "default")
private_dns_zone_resource_ids = optional(set(string), [])
application_security_group_associations = optional(map(string), {})
private_service_connection_name = optional(string, null)
network_interface_name = optional(string, null)
location = optional(string, null)
resource_group_name = optional(string, null)
ip_configurations = optional(map(object({
name = stringprivate_ip_address = stringmember_name = optional(string)
})), {})
}))
default = {}
nullable = falsedescription = <<DESCRIPTION A map of private endpoints to create on the Key Vault. The map key is deliberately arbitrary to avoid issues where map keys maybe unknown at plan time.
- `name` - (Optional) The name of the private endpoint. One will be generated if not set.
- `role_assignments` - (Optional) A map of role assignments to create on the private endpoint. The map key is deliberately arbitrary to avoid issues where map keys maybe unknown at plan time. See `var.role_assignments` for more information.
- `name` - (Optional) The name of the role assignment. If not set, a random UUID will be generated. Changing this forces the creation of a new resource.
- `role_definition_id_or_name` - The ID or name of the role definition to assign to the principal.
- `principal_id` - The ID of the principal to assign the role to.
- `description` - (Optional) The description of the role assignment.
- `skip_service_principal_aad_check` - (Optional) If set to true, skips the Azure Active Directory check for the service principal in the tenant. Defaults to false.
- `condition` - (Optional) The condition which will be used to scope the role assignment.
- `condition_version` - (Optional) The version of the condition syntax. Leave as `null` if you are not using a condition, if you are then valid values are '2.0'.
- `delegated_managed_identity_resource_id` - (Optional) The delegated Azure Resource Id which contains a Managed Identity. Changing this forces a new resource to be created. This field is only used in cross-tenant scenario.
- `principal_type` - (Optional) The type of the `principal_id`. Possible values are `User`, `Group` and `ServicePrincipal`. It is necessary to explicitly set this attribute when creating role assignments if the principal creating the assignment is constrained by ABAC rules that filters on the PrincipalType attribute.
- `lock` - (Optional) The lock level to apply to the private endpoint. Default is `None`. Possible values are `None`, `CanNotDelete`, and `ReadOnly`.
- `kind` - (Required) The type of lock. Possible values are `\"CanNotDelete\"` and `\"ReadOnly\"`.
- `name` - (Optional) The name of the lock. If not specified, a name will be generated based on the `kind` value. Changing this forces the creation of a new resource.
- `notes` - (Optional) Notes about the lock. This value maps to `Microsoft.Authorization/locks.properties.notes`.
- `tags` - (Optional) A mapping of tags to assign to the private endpoint.
- `subnet_resource_id` - The resource ID of the subnet to deploy the private endpoint in.
- `subresource_name` (Optional) - The name of the sub resource for the private endpoint.
- `private_dns_zone_group_name` - (Optional) The name of the private DNS zone group. One will be generated if not set.
- `private_dns_zone_resource_ids` - (Optional) A set of resource IDs of private DNS zones to associate with the private endpoint. If not set, no zone groups will be created and the private endpoint will not be associated with any private DNS zones. DNS records must be managed external to this module.
- `application_security_group_associations` - (Optional) A map of resource IDs of application security groups to associate with the private endpoint. The map key is deliberately arbitrary to avoid issues where map keys maybe unknown at plan time.
- `private_service_connection_name` - (Optional) The name of the private service connection. One will be generated if not set.
- `network_interface_name` - (Optional) The name of the network interface. One will be generated if not set.
- `location` - (Optional) The Azure location where the resources will be deployed. Defaults to the location of the resource group.
- `resource_group_name` - (Optional) The resource group resource ID where the private endpoint resources will be deployed. Defaults to the resource group of the parent resource.
- `ip_configurations` - (Optional) A map of IP configurations to create on the private endpoint. If not specified the platform will create one. The map key is deliberately arbitrary to avoid issues where map keys maybe unknown at plan time.
- `name` - The name of the IP configuration.
- `private_ip_address` - The private IP address of the IP configuration.
- `member_name` - (Optional) The private IP configuration member name.
DESCRIPTIONvalidation {
condition = alltrue([
for_, vin var.private_endpoints: can(provider::azapi::parse_resource_id("Microsoft.Network/virtualNetworks/subnets", v.subnet_resource_id))
])
error_message = "Each `private_endpoints[*].subnet_resource_id` must be a valid subnet resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
foridinv.private_dns_zone_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.Network/privateDnsZones", id))
]
]))
error_message = "Each entry in `private_endpoints[*].private_dns_zone_resource_ids` must be a valid private DNS zone resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
for_, asginv.application_security_group_associations: can(provider::azapi::parse_resource_id("Microsoft.Network/applicationSecurityGroups", asg))
]
]))
error_message = "Each value in `private_endpoints[*].application_security_group_associations` must be a valid application security group resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
for_, rainv.role_assignments:ra.delegated_managed_identity_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", ra.delegated_managed_identity_resource_id))
]
]))
error_message = "Each `private_endpoints[*].role_assignments[*].delegated_managed_identity_resource_id` must be a valid user-assigned managed identity resource ID, or null." }
}
module"avm_interfaces" {
source = "Azure/avm-utl-interfaces/azure"version = "0.6.0" # check latest version at the time of use
private_endpoints = var.private_endpointsprivate_endpoints_scope = azapi_resource.this.idrole_assignment_definition_scope = azapi_resource.this.id }
resource"azapi_resource""private_endpoints" {
for_each = module.avm_interfaces.private_endpoints_azapilocation = azapi_resource.this.locationname = each.value.nameparent_id = coalesce(var.private_endpoints[each.key].resource_group_name, azapi_resource.this.parent_id)
type = each.value.typebody = each.value.bodyretry = {
error_message_regex = ["ScopeLocked"] # This will retry if a lock is in place on the resource group, and has only just been removed
}
timeouts {
delete = "5m" }
}
resource"azapi_resource""private_endpoint_locks" {
for_each = module.avm_interfaces.lock_private_endpoint_azapiname = each.value.nameparent_id = azapi_resource.private_endpoints[each.value.pe_key].idtype = each.value.typebody = each.value.bodydepends_on = [
azapi_resource.private_dns_zone_groups,
azapi_resource.private_endpoint_role_assignments ]
}
resource"azapi_resource""private_dns_zone_groups" {
for_each = module.avm_interfaces.private_dns_zone_groups_azapiname = each.value.nameparent_id = azapi_resource.private_endpoints[each.key].idtype = each.value.typebody = each.value.bodyretry = {
error_message_regex = ["ScopeLocked"] # This will retry if a lock is in place on the resource group, and has only just been removed
interval_seconds = 15max_interval_seconds = 60 }
timeouts {
delete = "5m" }
}
resource"azapi_resource""private_endpoint_role_assignments" {
for_each = module.avm_interfaces.role_assignments_private_endpoint_azapiname = each.value.nameparent_id = azapi_resource.private_endpoints[each.value.pe_key].idtype = each.value.typebody = each.value.bodyretry = {
error_message_regex = ["ScopeLocked"]
interval_seconds = 15max_interval_seconds = 60 }
timeouts {
delete = "5m" }
}
The properties defined in the schema above are the minimum amount of properties expected to be exposed for Private Endpoints in AVM Resource Modules.
A module owner MAY chose to expose additional properties of the Private Endpoint resource.
However, module owners considering this SHOULD contact the AVM core team first to consult on how the property should be exposed to avoid future breaking changes to the schema that may be enforced upon them.
Module owners MAY chose to define a list of allowed value for the ‘service’ (a.k.a. groupIds) property.
However, they should do so with caution as should a new service appear for their resource module, a new release will need to be cut to add this new service to the allowed values.
Whereas not specifying allowed values will allow flexibility from day 0 without the need for any changes and releases to be made.
Customer Managed Keys
A module MUST implement exactly one of the two variants below. Which one applies is determined by the resource provider’s API, not by module owner preference. Linting accepts either shape.
Customer Managed Keys
variable"customer_managed_key" {
type = object({
key_vault_resource_id = stringkey_name = stringkey_version = optional(string, null)
user_assigned_identity = optional(object({
resource_id = string }), null)
})
default = nullvalidation {
condition = var.customer_managed_key ==null|| can(provider::azapi::parse_resource_id("Microsoft.KeyVault/vaults", var.customer_managed_key.key_vault_resource_id))
error_message = "`customer_managed_key.key_vault_resource_id` must be a valid Azure Key Vault resource ID." }
validation {
condition = var.customer_managed_key ==null|| var.customer_managed_key.user_assigned_identity ==null|| can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", var.customer_managed_key.user_assigned_identity.resource_id))
error_message = "`customer_managed_key.user_assigned_identity.resource_id` must be a valid user-assigned managed identity resource ID." }
}
customer_managed_key = {
key_vault_resource_id = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}"key_name = "{keyName}" # Omit `key_version` to let the resource provider follow key rotations automatically.
key_version = "{keyVersion}"user_assigned_identity = {
resource_id = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{userAssignedIdentityName}" }
}
# The vault is read by resource ID, not by name. That is safe in both directions: when
# the vault already exists the read resolves during plan, and when the vault is created
# by the same apply its resource ID is unknown at plan time, so Terraform defers the
# read. Reading the *key* the same way is not safe, which is what Variant 2 exists for.
data"azapi_resource""customer_managed_key_vault" {
count = var.customer_managed_key ==null?0:1type = var.resource_types.keyvault_vaultsresource_id = var.customer_managed_key.key_vault_resource_idresponse_export_values = ["properties.vaultUri"]
}
locals {
customer_managed_key_vault_uri = try(
data.azapi_resource.customer_managed_key_vault[0].output.properties.vaultUri,
null )
customer_managed_key_identity_resource_id = try(
var.customer_managed_key.user_assigned_identity.resource_id,
null )
} # `Microsoft.Storage/storageAccounts` takes the vault URI, key name and key version as
# separate fields, and identifies the encryption identity by resource ID. A null
# `keyversion` leaves the account following key rotations automatically.
resource"azapi_resource""this" {
type = var.resource_types.storage_storage_accountsname = var.namelocation = var.locationparent_id = var.resource_group_resource_idbody = {
properties = { # ... other properties
encryption = var.customer_managed_key ==null?null: {
keySource = "Microsoft.Keyvault"identity = {
userAssignedIdentity = local.customer_managed_key_identity_resource_id }
keyvaultproperties = {
keyvaulturi = local.customer_managed_key_vault_urikeyname = var.customer_managed_key.key_namekeyversion = var.customer_managed_key.key_version }
}
}
}
lifecycle {
precondition {
condition = var.customer_managed_key ==null||local.customer_managed_key_identity_resource_id!=nullerror_message = "`customer_managed_key.user_assigned_identity.resource_id` must be supplied because the Storage API identifies the encryption identity by resource ID." }
precondition {
condition = local.customer_managed_key_identity_resource_id ==null|| contains(var.managed_identities.user_assigned_resource_ids, local.customer_managed_key_identity_resource_id)
error_message = "The user assigned managed identity used for customer managed key encryption must also be assigned to the Storage Account via `managed_identities.user_assigned_resource_ids`." }
}
}
variable"customer_managed_key" {
type = object({
key_vault_key_uri = stringuser_assigned_identity = optional(object({
client_id = string }), null)
})
default = nullvalidation {
condition = var.customer_managed_key ==null|| can(regex("^https://[^/]+/keys/[^/]+(/[^/]+)?$", var.customer_managed_key.key_vault_key_uri))
error_message = "`customer_managed_key.key_vault_key_uri` must be a Key Vault or Managed HSM key URI, in the form `https://{vaultHost}/keys/{keyName}` or `https://{vaultHost}/keys/{keyName}/{keyVersion}`." }
validation {
condition = var.customer_managed_key ==null|| var.customer_managed_key.user_assigned_identity ==null|| can(regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", var.customer_managed_key.user_assigned_identity.client_id))
error_message = "`customer_managed_key.user_assigned_identity.client_id` must be a valid GUID." }
}
customer_managed_key = { # Omit the trailing version segment to let the resource provider follow key
# rotations automatically. The host is supplied in full, so the same input shape
# works in sovereign clouds and against Managed HSM, for example
# `https://{managedHsmName}.managedhsm.azure.net/keys/{keyName}/{keyVersion}`.
key_vault_key_uri = "https://{keyVaultName}.vault.azure.net/keys/{keyName}"user_assigned_identity = {
client_id = "{userAssignedIdentityClientId}" }
}
# Variant 2 carries exactly the two values the API consumes, so the module performs no
# resolution at all: no data sources, no URI construction, and no cloud specific DNS
# suffix handling. The consumer builds the key URI from the key resource they own, and
# supplies the client ID of the identity that the registry uses to reach the vault.
#
# `Microsoft.ContainerRegistry/registries` takes a single combined key identifier and
# identifies the encryption identity by client ID. A client ID cannot be derived from an
# identity resource ID without a data source, which is why this variant exists.
resource"azapi_resource""this" {
type = var.resource_types.containerregistry_registriesname = var.namelocation = var.locationparent_id = var.resource_group_resource_idbody = {
properties = { # ... other properties
encryption = var.customer_managed_key ==null?null: {
status = "enabled"keyVaultProperties = {
keyIdentifier = var.customer_managed_key.key_vault_key_uriidentity = var.customer_managed_key.user_assigned_identity ==null?null: var.customer_managed_key.user_assigned_identity.client_id }
}
}
}
lifecycle {
precondition {
condition = var.customer_managed_key ==null|| var.customer_managed_key.user_assigned_identity!=nullerror_message = "`customer_managed_key.user_assigned_identity` must be supplied because the Container Registry API identifies the encryption identity by client ID." }
}
}
Notes:
Modules MUST NOT use a data source to resolve the key URI or the encryption identity’s client ID.
Terraform reads a data source during plan whenever its arguments are already known. A key or identity lookup whose arguments are known literals can therefore run before a resource created by the same terraform apply exists, causing the plan to fail.
A module MAY read the Key Vault itself by key_vault_resource_id, because that argument is unknown at plan time whenever the vault is created by the same apply, which defers the read to apply time.
Variant 1 MUST be used where the resource provider takes the vault URI, the key name and the key version as separate fields, and identifies the encryption identity by resource ID, such as Microsoft.Storage/storageAccounts.
Omitting key_versionMUST leave the resource provider following key rotations automatically.
Where the resource provider requires a versioned key, such as Microsoft.Compute/diskEncryptionSets, the module MUST validate that key_version has been supplied.
Variant 2 MUST be used where the resource provider requires the encryption identity’s client ID, such as Microsoft.ContainerRegistry/registries, because a client ID cannot be resolved from an identity resource ID without a data source.
key_vault_key_uri carries the entire key identifier, so the consumer owns the host. The same input shape therefore works unchanged in sovereign clouds and against Managed HSM, and the module MUST NOT construct a DNS suffix of its own.
Omitting the trailing version segment MUST leave the resource provider following key rotations automatically.
Consumers SHOULD build key_vault_key_uri from the key resource they own, rather than from a data source, so that the value stays known at plan time.
Variant 2 deliberately carries no vault resource ID and no identity resource ID. A module MUST NOT require either, and MUST NOT attempt to cross-check the identity against managed_identities.
Modules MUST validate that whichever identity value their resource provider requires has been supplied, and SHOULD do so with a precondition so that the error names the missing attribute.
Where the resource provider also requires the identity to be assigned to the primary resource, modules MUST document that the consumer supplies the same identity through managed_identities.user_assigned_resource_ids.
Azure Monitor Alerts
Note
This interface is a SHOULD instead of a MUST and therefore the AVM core team have not mandated a interface schema to use.
AzAPI resource types
Important
Each resource_types key MUST be the snake_case form of the ARM resource type with the Microsoft. prefix dropped (for example Microsoft.Example/widgets/parts \u2192 example_widgets_parts). Each module MUST declare one optional(string, "...") field per azapi_resource (or equivalent AzAPI resource) it owns, defaulting each field to the latest tested API version. See TFFR6.
# `resource_types` keys vs Terraform resource labels
# -----------------------------------------------------------------------------
# These are two unrelated concepts:
#
# - Keys in `var.resource_types` name the AzAPI resource TYPE (e.g.
# `example_widgets`). They are derived from the ARM resource type by
# the naming rule below.
# - The Terraform resource LABEL (e.g. `azapi_resource.this`) names the
# graph node. The primary resource label MUST be `this` per TFRMNFR2.
#
# A primary-resource declaration therefore reads:
#
# resource "azapi_resource" "this" { # label per TFRMNFR2
# type = var.resource_types.example_widgets # key per the naming rule
# }
#
# The two MUST NOT be conflated. `this` is never a valid `resource_types` key.
#
# Naming rule for `resource_types` keys
# -----------------------------------------------------------------------------
# Each key MUST be the snake_case form of the ARM resource type with the
# `Microsoft.` prefix dropped. The provider namespace is rendered as a single
# lowercase token (no internal split) and each path segment after the
# provider is converted from camelCase to snake_case. Segments are joined
# with `_`:
#
# Microsoft.Example/widgets -> example_widgets
# Microsoft.Example/widgets/parts -> example_widgets_parts
# Microsoft.Example/widgets/parts/components -> example_widgets_parts_components
# Microsoft.Authorization/locks -> authorization_locks
# Microsoft.Authorization/roleAssignments -> authorization_role_assignments
# Microsoft.Insights/diagnosticSettings -> insights_diagnostic_settings
# Microsoft.KeyVault/vaults/secrets -> keyvault_vaults_secrets
# Microsoft.Network/virtualNetworks/subnets -> network_virtual_networks_subnets
#
# Submodules in the variable
# -----------------------------------------------------------------------------
# Every submodule the module instantiates gets a nested `optional(object({...}), {})`
# slot in `resource_types`, keyed by the submodule's primary ARM resource type
# (same naming rule). The slot's shape MUST match the submodule's own
# `resource_types` variable exactly. The parent MUST NOT repeat the submodule's
# defaults: the inner string attributes are declared as `optional(string)`
# with no default, so the submodule remains the single source of truth for
# its own tested API versions. Passing `null` (or omitting the key) yields
# the submodule's default.
# Root module example: manages `Microsoft.Example/widgets`, owns one extension
# resource (a lock), and instantiates a `parts` submodule that itself
# instantiates a `component` sibling submodule (per TFRMNFR1).
variable"resource_types" {
type = object({
example_widgets = optional(string, "Microsoft.Example/widgets@2024-01-01")
authorization_locks = optional(string, "Microsoft.Authorization/locks@2020-05-01")
example_widgets_parts = optional(object({
example_widgets_parts = optional(string)
example_widgets_parts_components = optional(object({
example_widgets_parts_components = optional(string)
}), {})
}), {})
})
default = {}
nullable = falsedescription = <<DESCRIPTION Override the AzAPI `<provider>/<resource>@<api-version>` strings used by this module and its submodules. Each key defaults to a tested value; supply only the keys you want to override. Useful when targeting a sovereign cloud with older API versions, or when opting into a newer preview API.
- `example_widgets` - The primary widget managed by this module.
- `authorization_locks` - Management lock applied to the widget and its private endpoints.
- `example_widgets_parts` - Override slot for the `parts` submodule. Defaults live in the submodule; supply only the keys you want to override.
- `example_widgets_parts` - The part resource managed by the `parts` submodule.
- `example_widgets_parts_components` - Override slot for the grandchild `components` submodule. Defaults live in that submodule.
- `example_widgets_parts_components` - The component resource managed by the `components` submodule.
DESCRIPTION } # `type =` of every `azapi_resource` MUST come from `var.resource_types`,
# never a hard-coded string. The resource label (`this`) and the
# `resource_types` key (`example_widgets`) are independent concerns.
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ }
response_export_values = []
} # Cascade the nested slot through to the submodule unchanged. The submodule's
# `resource_types` variable has exactly the shape of the slot, so no
# repacking or renaming is required.
module"part" {
source = "./modules/part"for_each = var.partsname = each.value.nameparent_id = azapi_resource.this.idresource_types = var.resource_types.example_widgets_parts }
# Consumers override only the keys they need; defaults supply the rest.
# Passing `null` for any attribute (or omitting it) yields the default
# declared on the owning module's variable.
resource_types = { # Pin the primary widget to a newer preview API version.
example_widgets = "Microsoft.Example/widgets@2025-06-01-preview" # Override an API version inside the `parts` submodule.
example_widgets_parts = {
example_widgets_parts = "Microsoft.Example/widgets/parts@2023-01-01" # Override an API version inside the grandchild `components` submodule
# of `parts` β the nested slot mirrors the submodule tree.
example_widgets_parts_components = {
example_widgets_parts_components = "Microsoft.Example/widgets/parts/components@2023-01-01" }
}
}
Notes:
resource_types keys name the AzAPI resource type and are derived deterministically from the ARM type. They are independent of the Terraform resource label (see TFRMNFR2) \u2014 this is never a valid resource_types key.
Submodules MUST declare their own resource_types variable using the same naming rule for the resources they own. The parent MUST declare one nested optional(object({...}), {}) slot per submodule it instantiates, shaped exactly like that submodule’s variable, and MUST cascade the slot through unchanged (see TFRMNFR1). The parent MUST NOT repeat the submodule’s defaults \u2014 the submodule remains the source of truth for its own tested API versions.
Defaults MUST be a stable (non-preview) API version unless the module’s primary resource only ships a preview API.
AzAPI retry
variable"retry" {
type = object({
error_message_regex = optional(list(string))
interval_seconds = optional(number)
max_interval_seconds = optional(number)
})
default = nulldescription = <<DESCRIPTION Retry configuration applied to every `azapi` resource managed by the module (root resource and all submodules). Defaults to `null` (no custom retry).
- `error_message_regex` - (Optional) A list of regex patterns matching error messages that trigger a retry.
- `interval_seconds` - (Optional) Initial interval between retries in seconds.
- `max_interval_seconds` - (Optional) Maximum interval between retries in seconds.
See <https://registry.terraform.io/providers/Azure/azapi/latest/docs/resources/resource#retry> for full semantics.
DESCRIPTION } # Example resource implementation. `retry` is an attribute on `azapi_resource`,
# so the variable is assigned directly. The same pattern applies to every
# `azapi_resource` declared by the module, including those in submodules.
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ }
retry = var.retryresponse_export_values = []
} # Cascade `retry` to every submodule the parent module instantiates so that a
# single override at the parent level propagates everywhere.
module"child" {
source = "./modules/child"retry = var.retry # ...other arguments...
}
The retry variable MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module.
Parent modules MUST cascade retry to each submodule they instantiate (see TFFR7 and TFRMNFR1).
Module owners MAY ship module-level defaults when the resource it manages benefits from them. To do so, set the variable’s overall default to {} (not null) and provide per-field defaults inside the optional(...) wrappers. Consumers MUST still be able to override any individual field.
# Module-level defaults example: a hypothetical module retries
# on common transient replication errors and tunes the back-off interval. The
# overall variable default is `{}` (not `null`) so the per-field defaults take
# effect, and consumers can still override any individual field.
variable"retry" {
type = object({
error_message_regex = optional(list(string), ["AnotherOperationInProgress", "TooManyRequests"])
interval_seconds = optional(number, 30)
max_interval_seconds = optional(number, 300)
})
default = {}
description = <<DESCRIPTION Retry configuration applied to every `azapi` resource managed by the module. This module ships defaults tuned for Storage Account replication; consumers **MAY** override any field.
- `error_message_regex` - (Optional) A list of regex patterns matching error messages that trigger a retry.
- `interval_seconds` - (Optional) Initial interval between retries in seconds.
- `max_interval_seconds` - (Optional) Maximum interval between retries in seconds.
DESCRIPTION }
AzAPI timeouts
variable"timeouts" {
type = object({
create = optional(string)
read = optional(string)
update = optional(string)
delete = optional(string)
})
default = nulldescription = <<DESCRIPTION Default per-operation timeouts applied to every `azapi` resource managed by the module. Defaults to `null` (provider defaults). Each value is a Go duration string (e.g. `30m`, `1h`).
- `create` - (Optional) Timeout for create operations.
- `read` - (Optional) Timeout for read operations.
- `update` - (Optional) Timeout for update operations.
- `delete` - (Optional) Timeout for delete operations.
DESCRIPTION } # Example resource implementation. `timeouts` is a block on `azapi_resource`,
# so a `dynamic "timeouts"` block is required to honour the variable's `null`
# default. The same pattern applies to every `azapi_resource` declared by
# the module, including those in submodules.
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ }
dynamic"timeouts" {
for_each = var.timeouts ==null? [] : [var.timeouts]
content {
create = timeouts.value.createread = timeouts.value.readupdate = timeouts.value.updatedelete = timeouts.value.delete }
}
response_export_values = []
} # Cascade `timeouts` to every submodule the parent module instantiates so that
# a single override at the parent level propagates everywhere.
module"child" {
source = "./modules/child"timeouts = var.timeouts # ...other arguments...
}
timeouts is a block on azapi_resource (not an attribute), so a dynamic "timeouts" block is required to honor the variable’s null default.
The timeouts variable MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module.
Parent modules MUST cascade timeouts to each submodule they instantiate (see TFFR7 and TFRMNFR1). Submodules MAY additionally expose per-item overrides for cases where individual resources need different settings.
Module owners MAY ship module-level defaults when the resource it manages benefits from them (for example, longer create / delete timeouts for slow-provisioning resources). To do so, set the variable’s overall default to {} (not null) and provide per-field defaults inside the optional(...) wrappers. Consumers MUST still be able to override any individual field.
# Module-level defaults example: a hypothetical SQL Database module ships
# longer create / delete timeouts because provisioning and dropping large
# databases can exceed the provider defaults. The overall variable default
# is `{}` (not `null`) so the per-field defaults take effect, and consumers
# can still override any individual field.
variable"timeouts" {
type = object({
create = optional(string, "1h")
read = optional(string, "5m")
update = optional(string, "1h")
delete = optional(string, "45m")
})
default = {}
description = <<DESCRIPTION Default per-operation timeouts applied to every `azapi` resource managed by the module. This module ships defaults tuned for SQL Database provisioning latency; consumers **MAY** override any field.
- `create` - (Optional) Timeout for create operations.
- `read` - (Optional) Timeout for read operations.
- `update` - (Optional) Timeout for update operations.
- `delete` - (Optional) Timeout for delete operations.
DESCRIPTION }
AzAPI ignore_body_changes
Important
ignore_body_changes is a write-only argument that requires the Azure/azapi provider v2.12.0 or later, and Terraform 1.11 or later when a non-empty value is supplied. See TFFR8.
# `ignore_body_changes` keys follow exactly the same naming rule as
# `resource_types` (see TFFR6): the snake_case form of the ARM resource type
# with the `Microsoft.` prefix dropped.
#
# Microsoft.Example/widgets -> example_widgets
# Microsoft.Example/widgets/parts -> example_widgets_parts
# Microsoft.Example/widgets/parts/components -> example_widgets_parts_components
#
# Unlike `retry` and `timeouts`, the values are dot-notation paths into ONE
# specific resource's `body`, so the variable is scoped per resource and per
# submodule instead of being cascaded unchanged. Every submodule the module
# instantiates gets a nested `optional(object({...}), {})` slot whose shape
# matches that submodule's own `ignore_body_changes` variable exactly, and the
# parent cascades that slot through unchanged.
variable"ignore_body_changes" {
type = object({
example_widgets = optional(list(string), [])
example_widgets_parts = optional(object({
example_widgets_parts = optional(list(string), [])
}), {})
})
default = {}
nullable = falsedescription = <<DESCRIPTION Paths in each resource's `body` whose changes the AzAPI provider ignores. Prefer Terraform's `lifecycle.ignore_changes` when the paths are static; use this variable when the paths must be derived from variables or other non-static values.
Paths use dot notation, for example `properties.sku.name`. Individual list items cannot be targeted β ignore the whole list property instead. Configuration changes at an ignored path are **not** sent to Azure until that path is removed from the list.
Supplying a non-empty value requires Terraform 1.11 or later, because `ignore_body_changes` is a write-only argument. Changes take effect only after an apply, because the value is held in provider-private state.
- `example_widgets` - Ignored body paths for the widget managed by this module.
- `example_widgets_parts` - Override slot for the `parts` submodule. Supply only the keys you want to override.
- `example_widgets_parts` - Ignored body paths for the part resource managed by the `parts` submodule.
DESCRIPTION } # `ignore_body_changes` is a write-only attribute on `azapi_resource`, so the
# relevant field is assigned directly. Collapse an empty list to `null` so the
# argument is absent when the feature is unused, keeping the module usable on
# Terraform versions earlier than 1.11.
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ }
ignore_body_changes = length(var.ignore_body_changes.example_widgets) >0? var.ignore_body_changes.example_widgets:nullresponse_export_values = []
} # Cascade the nested slot to the submodule unchanged. The submodule's
# `ignore_body_changes` variable has exactly the shape of the slot, so no
# repacking or renaming is required.
module"part" {
source = "./modules/part"for_each = var.partsname = each.value.nameparent_id = azapi_resource.this.idresource_types = var.resource_types.example_widgets_partsignore_body_changes = var.ignore_body_changes.example_widgets_parts }
ignore_body_changes = { # Tags are applied to the widget by Azure Policy, so suppress the diff when
# the consumer opts in. `lifecycle.ignore_changes` cannot express this,
# because the value is derived from a variable.
example_widgets = var.ignore_policy_tags? ["tags"] : []
example_widgets_parts = {
example_widgets_parts = ["properties.retentionPolicy"]
}
}
Notes:
Unlike retry and timeouts, ignore_body_changes values are dot-notation paths into one specific resource’sbody, so the variable MUST NOT be cascaded to submodules unchanged. It uses the same per-resource, per-submodule shape and key-naming rule as resource_types (see TFFR6).
The ignore_body_changes variable MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module, and every submodule MUST declare its own (see TFFR8 and TFRMNFR1).
The assignment MUST collapse an empty list to null so that the write-only argument is absent when the feature is unused, keeping the module usable on Terraform versions earlier than 1.11.
A change to ignore_body_changes only takes effect after an apply, because the value is held in provider-private state.
An ignored path is not merely hidden from the plan β configuration changes at that path are not sent to Azure until the path is removed from the list.
Module owners MAY ship module-level defaults where the resource is known to be mutated outside Terraform, by supplying the default inside the optional(list(string), [...]) wrapper. Consumers MUST still be able to override any individual field.
Terraform Pattern Module Specifications
Contribution / Support
The content below is listed based on the following tags
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
Module owners MUST set a branch protection policy on their GitHub Repositories for AVM modules against their default branch, typically main, to do the following:
Requires a Pull Request before merging
Require approval of the most recent reviewable push
Dismiss stale pull request approvals when new commits are pushed
Require linear history
Prevents force pushes
Not allow deletions
Require CODEOWNERS review
Do not allow bypassing the above settings
Above settings MUST also be enforced to administrators
Tip
If you use the template repository as mentioned in the contribution guide, the above will automatically be set.
Telemetry
The content below is listed based on the following tags
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
Terraform
Currently, no further requirements apply.
Naming / Composition
The content below is listed based on the following tags
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
ID: SFR5 - Category: Composition - Availability Zones
Modules that deploy zone-redundant resources MUST enable the spanning across as many zones as possible by default, typically all 3.
Modules that deploy zonal resources MUST provide the ability to specify a zone for the resources to be deployed/pinned to. However, they MUST NOT default to a particular zone by default, e.g. 1 in an effort to make the consumer aware of the zone they are selecting to suit their architecture requirements.
For both scenarios the modules MUST expose these configuration options via configurable parameters/variables.
ID: SFR6 - Category: Composition - Data Redundancy
Modules that deploy resources or patterns that support data redundancy SHOULD enable this to the highest possible value by default, e.g. RA-GZRS. When a resource or pattern doesn’t provide the ability to specify data redundancy as a simple property, e.g. GRS etc., then the modules MUST provide the ability to enable data redundancy for the resources or pattern via parameters/variables.
For example, a Storage Account module can simply set the sku.name property to Standard_RAGZRS. Whereas a SQL DB or Cosmos DB module will need to expose more properties, via parameters/variables, to allow the specification of the regions to replicate data to as per the consumers requirements.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
Pattern Modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Example: avm/ptn/compute/app-tier-vmss or avm/ptn/avd-lza/management-plane or avm/ptn/3-tier/web-app
Segments:
ptn defines this as a pattern module
<hyphenated grouping/category name> is a hierarchical grouping of pattern modules by category, with each word separated by dashes, such as:
project name, e.g., avd-lza,
primary resource provider, e.g., compute or network, or
architecture, e.g., 3-tier
<hyphenated pattern module name> is a term describing the module’s function, with each word separated by dashes, e.g., app-tier-vmss = Application Tier VMSS; management-plane = Azure Virtual Desktop Landing Zone Accelerator Management Plane
Terraform Pattern Module Naming
Naming convention:
avm-ptn-<pattern module name> (Module name for registry)
terraform-<provider>-avm-ptn-<pattern module name> (GitHub repository name to meet registry naming requirements)
Example: avm-ptn-apptiervmss or avm-ptn-avd-lza-managementplane
Segments:
<provider> is a legacy requirement of the Terraform registry. This must be set to azure
ptn defines this as a pattern module
<pattern module name> is a term describing the module’s function, e.g., apptiervmss = Application Tier VMSS; avd-lza-managementplane = Azure Virtual Desktop Landing Zone Accelerator Management Plane
ID: PMNFR2 - Category: Composition - Use Resource Modules to Build a Pattern Module
A Pattern Module SHOULD be built from AVM Resources Modules to establish a standardized code base and improve maintainability. If a valid reason exists, a pattern module MAY contain native resources (“vanilla” code) where it’s necessary. A Pattern Module MUST NOT contain references to non-AVM modules.
Valid reasons for not using a Resource Module for a resource required by a Pattern Module include but are not limited to:
When using a Resource Module would result in hitting scaling limitations and/or would reduce the capabilities of the Pattern Module due to the limitations of Azure Resource Manager.
Developing a Pattern Module under time constraint, without having all required Resource Modules readily available.
Note
In the latter case, the Pattern Module SHOULD be updated to use the Resource Module when the required Resource Module becomes available, to avoid accumulating technical debt. Ideally, all required Resource Modules SHOULD be developed first, and then leveraged by the Pattern Module.
Module owners MAY cross-references other modules to build either Resource or Pattern modules. However, they MUST be referenced only by a HashiCorp Terraform registry reference to a pinned version e.g.,
Every new AVM Terraform module β resource, pattern, or utility β MUST use Azure/azapi for every Azure control-plane resource and every data-plane operation supported by AzAPI. The AzureRM provider is permitted only for the unsupported data-plane/non-ARM API exception defined below.
Authors MUST only use the following Azure providers, and versions, in their modules:
provider
min version
max version
permitted use
Azure/azapi
>= 2.12
< 3.0
All Azure control-plane resources and supported data-plane operations
hashicorp/azurerm
>= 4.0
< 5.0
Only a specific unsupported data-plane/non-ARM API operation under the exception below
Pattern modules MAY also use other Microsoft-maintained providers when required by the pattern. Examples include integrations/github, microsoft/azuredevops, microsoft/fabric, and microsoft/msgraph. Each provider MUST be declared with minimum and maximum major version constraints as required by TFNFR26.
Resource and utility modules MUST NOT use these additional providers. Except for the narrow AzureRM exception below, third-party providers MUST NOT be used by any AVM Terraform module, regardless of module classification.
Note
The AzAPI floor is 2.12 because TFFR8 requires every module to expose the ignore_body_changes argument, which was introduced in Azure/azapi v2.12.0. Modules pinned below that version will fail to plan because the argument is absent from the provider schema.
This prohibition applies to every Terraform configuration shipped with the module, including:
The root module and all submodules.
Every configuration under examples/, including examples executed as end-to-end tests.
Terraform tests, test fixtures, and supporting setup configurations.
Terraform snippets in _header.md, _footer.md, generated documentation, and other repository documentation.
Supporting control-plane resources needed by an example, end-to-end test, or fixture MUST use AzAPI. AzureRM MUST NOT be used for resource groups, role assignments, monitoring resources, networking, or any other ARM control-plane resource.
Exception β unsupported data-plane/non-ARM API operations
An AVM Terraform module that is otherwise built with AzAPI MAY declare the AzureRM provider only for a specific data-plane or non-ARM API operation whose functionality is genuinely unavailable through azapi_data_plane_resource, azapi_resource, azapi_resource_action, or azapi_update_resource. This exception is intended for isolated operations such as a data-plane resource whose AzureRM implementation calls a service endpoint rather than Azure Resource Manager. It is not a general fallback for a missing or inconvenient AzAPI schema. Every azurerm_* block MUST independently satisfy this exception; one permitted block does not authorize any other AzureRM use.
Where this exception applies, the module MUST:
Continue to declare and use AzAPI as its required, primary Azure provider.
Scope every azurerm_* resource or data source to the exact unsupported data-plane/non-ARM operation.
Pin the AzureRM provider to ~> 4.0 in required_providers.
Use AzAPI for every control-plane resource and every data-plane operation that AzAPI supports.
Document the exception in the module’s README.md, including each azurerm_* block, the data-plane/non-ARM API it wraps, why AzAPI cannot implement it, and the upstream AzAPI issue or pull request tracking support.
Replace the azurerm_* block with AzAPI in the next module release after the required capability ships.
Examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets MAY configure or exercise AzureRM only when required by that exact permitted data-plane operation. All supporting control-plane resources in those surfaces MUST use AzAPI.
This exception MUST NOT be used to:
Implement any ARM control-plane resource.
Avoid AzAPI because its body schema is more verbose or less convenient.
Avoid raising an AzAPI capability gap for an unsupported control-plane operation.
Side-step any AzAPI-specific specification that applies to the module’s AzAPI resources.
The azurerm remote state backend and the final segment of a published Terraform Registry module address, such as /azurerm in an existing AVM module source, are names and are not provider declarations. They MAY appear where required for state storage or to reference an existing published AVM module. A dependency’s provider implementation is governed by that dependency’s own repository; its Registry address does not by itself justify a direct hashicorp/azurerm declaration or azurerm_* block in the consuming module repository. Any such direct use MUST independently satisfy the data-plane exception above.
Authors MUST use the required_providers block in their module to enforce the provider versions.
Authors MUST specify the response_export_values argument when using the AzAPI provider:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US"response_export_values = [] # must be specified, even if empty
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
If you require read-only properties to be returned from the resource, you SHOULD include them as follows:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US" # Example as a list:
response_export_values = ["properties.readOnlyProperty"] # Example as a map:
# response_export_values = {
# read_only_property = "properties.readOnlyProperty"
# }
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
output"read_only_property" { # Example if response_export_values is a list:
value = azapi_resource.example.output.properties.readOnlyProperty # Example if response_export_values is a map:
# value = azapi_resource.example.output.read_only_property
}
Authors MUST omit replace_triggers_refs when no body properties require replacement. When one or more body properties require replacement, authors MUST set replace_triggers_refs to a non-empty static list of JMESPath expressions that identify those paths.
Each expression MUST be valid JMESPath syntax, non-blank, and unique within the list. Do not include name or location, as AzAPI already replaces the resource when either changes. When the resource body is statically evaluable, every declared expression MUST resolve against that body.
This is to ensure that changes to properties that require replacement of the resource are handled correctly by Terraform. Authors remain responsible for identifying every property that actually requires replacement. Current Bicep-generated schemas do not reliably preserve whether a property is create-only or updateable, so the rule validates declared paths but cannot prove that the list is semantically complete.
We can use count and for_each to deploy multiple resources, but using count with an ordered collection can create an index anti-pattern where removing one item unexpectedly changes other resource addresses.
You can use count to create some kind of resources under certain conditions, for example:
The module’s owners MUST use map(xxx) or set(xxx) as resource’s for_each collection, the map’s key or set’s element MUST be static literals.
Good example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_map // `map(string)`, when user call this module, it could be: `{ "subnet0": "subnet0" }`, or `{ "subnet0": azapi_resource.subnet0.name }`
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
Bad example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_name_set // `set(string)`, when user use `toset([azapi_resource.subnet0.name])`, it would cause an error.
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
There are 3 types of assignment statements in a resource or data block: argument, meta-argument and nested block. The argument assignment statement is a parameter followed by =:
location = azapi_resource.example.location
or:
tags = {
environment = "Production"}
Nested block is a assignment statement of parameter followed by {} block:
subnet {
name = "subnet1"address_prefix = "10.0.1.0/24"}
Meta-arguments are assignment statements can be declared by all resource or data blocks. They are:
count
depends_on
for_each
lifecycle
provider
The order of declarations within resource or data blocks is:
All the meta-arguments SHOULD be declared on the top of resource or data blocks in the following order:
provider
count
for_each
Then followed by:
required arguments
optional arguments
required nested blocks
optional nested blocks
All ranked in alphabetical order.
These meta-arguments SHOULD be declared at the bottom of a resource block with the following order:
depends_on
lifecycle
The parameters of lifecycle block SHOULD show up in the following order:
create_before_destroy
ignore_changes
prevent_destroy
parameters under depends_on and ignore_changes are ranked in alphabetical order.
Meta-arguments, arguments and nested blocked are separated by blank lines.
dynamic nested blocks are ranked by the name comes after dynamic, for example:
Sometimes we need to ensure that the resources created are compliant to some rules at a minimum extent, for example a subnet has to be connected to at least one network_security_group. The user SHOULD pass in a security_group_id and ask us to make a connection to an existing security_group, or want us to create a new security group.
The disadvantage of this approach is if the user create a security group directly in the root module and use the id as a variable of the module, the expression which determines the value of count will contain an attribute from another resource, the value of this very attribute is “known after apply” at plan stage. Terraform core will not be able to get an exact plan of deployment during the “plan” stage.
For this kind of parameters, wrapping with object type is RECOMMENDED:
variable"security_group" {
type:object({
id = string })
default = null}
The advantage of doing so is encapsulating the value which is “known after apply” in an object, and the object itself can be easily found out if it’s null or not. Since the id of a resource cannot be null, this approach can avoid the situation we are facing in the first example, like the following:
variable used as feature switches SHOULD apply a positive statement, use xxx_enabled instead of xxx_disabled. Avoid double negatives like !xxx_disabled.
Please use xxx_enabled instead of xxx_disabled as name of a variable.
ID: TFNFR17 - Category: Code Style - Variables with Descriptions
The target audience of description is the module users.
For a newly created variable (Eg. variable for switching dynamic block on-off), it’s descriptionSHOULD precisely describe the input parameter’s purpose and the expected data type. descriptionSHOULD NOT contain any information for module developers, this kind of information can only exist in code comments.
For object type variable, description can be composed in HEREDOC format:
variable"kubernetes_cluster_key_management_service" {
type:object({
key_vault_key_id = stringkey_vault_network_access = optional(string)
})
default = nulldescription = <<DESCRIPTION- `key_vault_key_id` - (Required) Identifier of Azure Key Vault key. See [key identifier format](https://learn.microsoft.com/en-us/azure/key-vault/general/about-keys-secrets-certificates#vault-name-and-object-name) for more details. When Azure Key Vault key management service is enabled, this field is required and must be a valid key identifier. When `enabled` is `false`, leave the field empty.
- `key_vault_network_access` - (Optional) Network access of the key vault Network access of key vault. The possible values are `Public` and `Private`. `Public` means the key vault allows public access from all networks. `Private` means the key vault disables public access and enables private link. Defaults to `Public`.
DESCRIPTION}
You MUST remove all trailing whitespace so that terraform-docs renders the readme properly.
ID: TFNFR19 - Category: Code Style - Sensitive Data Variables
If variable’s type is object and contains one or more fields that would be assigned to a sensitive argument, then this whole variableSHOULD be declared as sensitive = true, otherwise you SHOULD extract sensitive field into separated variable block with sensitive = true.
Nullable SHOULD be set to false for collection values (e.g. sets, maps, lists) when using them in loops. However for scalar values like string and number, a null value MAY have a semantic meaning and as such these values are allowed.
MAPOTF removes redundant explicit nullable = true. That formatting cleanup does not change this requirement and does not imply that a collection is semantically safe to make nullable.
nullable = trueMUST be avoided. MAPOTF removes redundant explicit nullable = true; this cleanup is distinct from, and does not satisfy, the requirement to set nullable = false where a meaningful zero value exists.
Variables MUST be declared with nullable = false whenever the variable’s type has a meaningful zero value ({} for objects/maps, [] for lists/sets, "" for strings where empty has the same meaning as absent, etc.). Consumers should signal “no value” by omitting the input, not by explicitly passing null.
Exception β behavior-toggle inputs
A small, well-defined class of inputs MAY keep the implicit nullable = true (i.e. default = null) where null carries a distinct semantic meaning of “no override β use the underlying provider/AVM defaults”, and where representing that state with the type’s zero value would be ambiguous or wrong. Examples include:
var.retry and var.timeouts (per TFFR7) β null means “do not emit a retry/timeouts block; use the AzAPI provider defaults”.
var.lock (per the AVM lock interface) β null means “do not create a management lock”.
Optional sub-objects that toggle whole feature blocks on/off, where {} would be indistinguishable from “feature enabled with all defaults”.
Where this exception applies, the variable MUST:
Use default = null (the implicit nullable = true is permitted only for this purpose).
State explicitly in its description what null means.
Be consumed with a null-aware pattern (e.g. count = var.lock != null ? 1 : 0, or dynamic "timeouts" { for_each = var.timeouts == null ? [] : [var.timeouts] }).
This exception does not extend to required inputs, to collection-shaped inputs (TFNFR20), or to nested attributes inside an object β those MUST use nullable = false and the type’s zero value.
variable"example_map" {
type =map(string)
default = {}
description ="An example map variable with an empty default value." sensitive =true}
Bad example:
variable"example_string" {
type =string default ="sensitive_value" description ="An example string variable with a sensitive default value." sensitive =true}
Sometimes we will find names for some variable are not suitable anymore, or a change SHOULD be made to the data type. We want to ensure forward compatibility within a major version, so direct changes are strictly forbidden. The right way to do this is move this variable to an independent deprecated_variables.tf file, then redefine the new parameter in variable.tf and make sure it’s compatible everywhere else.
Deprecated variableMUST be annotated as DEPRECATED at the beginning of the description, at the same time the replacement’s name SHOULD be declared. E.g.,
variable"enable_network_security_group" {
type = stringdefault = nulldescription = "DEPRECATED, use `network_security_group_enabled` instead; Whether to generate a network security group and assign it to the subnet. Changing this forces a new resource to be created."}
A cleanup of deprecated_variables.tfSHOULD be performed during a major version release.
The terraform.tf file MUST only contain one terraform block.
The first line of the terraform block MUST define a required_version property for the Terraform CLI. The standard Terraform TFLint plugin validates the requirement; MAPOTF keeps it first.
The required_version property MUST include a constraint on the minimum version of the Terraform CLI. Previous releases of the Terraform CLI can have unexpected behavior.
The required_version property MUST include a constraint on the maximum major version of the Terraform CLI. Major version releases of the Terraform CLI can introduce breaking changes and MUST be tested.
The required_version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
ID: TFNFR26 - Category: Code Style - Providers in required_providers
The terraform block in terraform.tfMUST contain the required_providers block.
Each provider used directly in the module MUST be specified with the source and version properties. The standard Terraform TFLint plugin validates the used-provider source and version requirements. MAPOTF sorts the required_providers entries alphabetically.
Do not add providers to the required_providers block that are not directly required by this module. If submodules are used then each submodule SHOULD declare its requirements in its own terraform.tf file.
The source property MUST be in the format of namespace/name. If this is not explicitly specified, it can cause failure.
The version property MUST include a constraint on the minimum version of the provider. Older provider versions may not work as expected.
The version property MUST include a constraint on the maximum major version. A provider major version release may introduce breaking change, so updates to the major version constraint for a provider MUST be tested.
The version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
By rule, every published AVM module and submodule MUST NOT declare a provider block. Provider configuration belongs exclusively to the consuming root module.
When a module requires an alternate provider instance, it MUST declare that alias through configuration_aliases in terraform.required_providers and the consumer MUST pass the configured alias through the module’s providers map. A provider block containing only alias is not permitted in an AVM module.
Sometimes we notice that the name of certain output is not appropriate anymore, however, since we have to ensure forward compatibility in the same major version, its name MUST NOT be changed directly. It MUST be moved to an independent deprecated_outputs.tf file, then redefine a new output in output.tf and make sure it’s compatible everywhere else in the module.
A cleanup SHOULD be performed to deprecated_outputs.tf and other logics related to compatibility during a major version upgrade.
ID: TFNFR31 - Category: Code Style - locals.tf for Locals Only
In locals.tf, file we could declare multiple locals blocks, but only locals blocks are allowed.
You MAY declare locals blocks next to a resource block or data block for some advanced scenarios, like making a fake module to execute some light-weight tests aimed at the expressions.
This specification applies only to existing legacy modules that still use AzureRM while they are being migrated. It does not apply to a new module that uses AzureRM solely for the narrow unsupported data-plane/non-ARM API exception in TFFR3, because that exception does not permit AzureRM resource-group management.
In a legacy AzureRM module, the prevent_deletion_if_contains_resources provider setting SHOULD be set to false until the module is migrated. Azure Policy remediation can add resources during a test run, and the provider’s default behavior can then prevent cleanup of the test resource group.
newres is a command-line tool that generates Terraform configuration files for a specified resource type. It automates the process of creating variables.tf and main.tf files, making it easier to get started with Terraform and reducing the time spent on manual configuration.
Module owners MAY use newres when they’re trying to add new resource block, attribute, or nested block. They MAY generate the whole block along with the corresponding variable blocks in an empty folder, then copy-paste the parts they need with essential refactoring.
ID: TFNFR39 - Category: Code Style - Standard File Layout
Every Terraform AVM module (root module and every submodule) MUST organize its top-level Terraform code into the following files at the module’s root directory:
File
Required
Contents
terraform.tf
MUST
The single terraform { β¦ } block β required_version, required_providers, and any backend configuration (root module only). Provider configuration blocks MUST NOT appear here.
variables.tf
MUST
All variable blocks for the module. MAY be split into additional variables.<topic>.tf files (see below).
outputs.tf
MUST
All output blocks for the module. MAY be split into additional outputs.<topic>.tf files (see below).
main.tf
MUST
The module’s primary resource, data, and module blocks. MAY be split into additional main.<topic>.tf files (see below).
locals.tf
SHOULD
All locals blocks. Required if the module declares any locals. MAY be split into additional locals.<topic>.tf files (see below). MAY be omitted only when the module has no locals at all.
Splitting and naming additional files
For larger modules the contents of main.tf, variables.tf, outputs.tf, and locals.tfMAY each be split into multiple files along logical / topic lines. When this is done:
Additional Terraform files MUST use the canonical filename (main, variables, outputs, or locals) as the prefix, followed by a ., a short descriptive topic name, and the .tf extension β for example main.diagnostic_settings.tf, variables.diagnostic_settings.tf, outputs.diagnostic_settings.tf, locals.diagnostic_settings.tf.
The same topic name SHOULD be used across the four file types when they describe the same logical concern, so that (for example) main.private_endpoints.tf, variables.private_endpoints.tf, outputs.private_endpoints.tf, and locals.private_endpoints.tf all relate to the same feature.
Each split file MUST contain only the block kind matching its prefix:
main.<topic>.tf β only resource, data, and module blocks.
variables.<topic>.tf β only variable blocks.
outputs.<topic>.tf β only output blocks.
locals.<topic>.tf β only locals blocks.
The terraform { β¦ } block MUST appear exactly once per module, in terraform.tf. It MUST NOT be split.
Files that MUST NOT appear at the module root
A providers.tf file β provider requirements belong in terraform.tf; provider configurations belong only in the consumer’s root module, never in an AVM module (per SFR2).
A single monolithic module.tf or everything.tf β the canonical filenames above MUST be used.
Rationale
Standardizing file layout means that any reviewer or consumer can find a module’s interface (variables.tf, outputs.tf), provider constraints (terraform.tf), and primary logic (main.tf / main.<topic>.tf) in the same place across every AVM Terraform module, without having to grep. It also makes the cascade rules in TFFR6, TFFR7, and TFRMNFR1 reviewable at a glance.
Submodules (per TFRMNFR1) follow the same layout in their own root directory under modules/<subresource>/. The submodule’s terraform.tfMUST declare the same set of required_providers it actually consumes.
Auto-generated documentation files (README.md, _header.md, _footer.md) and tooling configuration files (.terraform-docs.yml, .tflint.hcl, etc.) are out of scope of this rule and follow their own specs.
Structured values that are passed as JSON or YAML MUST be constructed with jsonencode or yamlencode, rather than a literal JSON or YAML heredoc. Native HCL objects, lists, conditionals, and for expressions keep the structure reviewable and let Terraform perform correct escaping.
Terraform interpolation (${...}), template directives (%{...}), unknown values, and dynamically generated lists or maps are not exceptions: construct the native HCL value and pass it to the encoder.
A heredoc MAY be used only when the value is not JSON or YAML, or when the receiving system requires opaque source text for a downstream templating engine or syntax that jsonencode or yamlencode cannot represent without changing its meaning. The heredoc must not use Terraform interpolation to assemble JSON or YAML in that case, and its reason must be clear from the surrounding configuration.
ID: TFNFR41 - Category: Code Style - Output Definition Order
output blocks in a module SHOULD be ordered alphabetically by output name. This applies to outputs.tf and every outputs.<topic>.tf file in the root module and each submodule.
output"id" {
value = azapi_resource.this.id}
output"name" {
value = azapi_resource.this.name}
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
Authors SHOULD NOT output entire resource objects as these may contain sensitive outputs and the schema can change with API or provider versions. Instead, authors SHOULD output the computed attributes of the resource as discreet outputs. This kind of pattern protects against provider schema changes and is known as an anti-corruption layer.
Remember, you SHOULD NOT output values that are already inputs (other than name).
E.g.,
# Resource output, computed attribute.
output"foo" {
description = "MyResource foo attribute"value = azapi_resource.myresource.output.properties.foo}# Resource output for resources that are deployed using `for_each`. Again only computed attributes.
output"childresource_foos" {
description = "MyResource children's foo attributes"value = {
forkey, valueinazapi_resource.mychildresource:key => value.output.properties.foo }
}# Output of a sensitive attribute
output"bar" {
description = "MyResource bar attribute"value = azapi_resource.myresource.output.properties.barsensitive = true}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, authors MUST NOT hard-code the type argument of a supported AzAPI resource inline.
Instead, every AzAPI resource type string used by the module MUST be sourced from a single object variable named resource_types.
resource_types keys vs Terraform resource labels
These are two unrelated concepts and the spec treats them independently:
Keys in var.resource_types name the AzAPI resource type and are derived from the ARM type by the naming rule below. They appear on the right of an assignment as the value of the type argument.
Terraform resource labels (e.g. azapi_resource.this) name the graph node and govern how the resource is referenced elsewhere in HCL. The primary resource label MUST be this, per TFRMNFR2.
A typical primary-resource declaration therefore reads:
resource"azapi_resource""this" { # label per TFRMNFR2
type = var.resource_types.example_widgets # key per the naming rule below
# ...
}
this and example_widgets describe different things and are derived by different rules. They MUST NOT be made to coincide β this is never a valid resource_types key.
Key naming
Each resource_types key (at every level of nesting) MUST be the snake_case form of the ARM resource type, with the Microsoft. prefix dropped:
Drop the Microsoft. prefix.
Render the provider namespace as a single lowercase token β do not split internal camelCase (KeyVault β keyvault, DocumentDB β documentdb, EventHub β eventhub).
Convert each resource path segment after the provider from camelCase to snake_case (virtualNetworks β virtual_networks, roleAssignments β role_assignments).
Join the provider token and each path segment with _.
ARM type
Key
Microsoft.Example/widgets
example_widgets
Microsoft.Example/widgets/parts
example_widgets_parts
Microsoft.Example/widgets/parts/components
example_widgets_parts_components
Microsoft.Authorization/locks
authorization_locks
Microsoft.Authorization/roleAssignments
authorization_role_assignments
Microsoft.Insights/diagnosticSettings
insights_diagnostic_settings
Microsoft.KeyVault/vaults/secrets
keyvault_vaults_secrets
Microsoft.Network/virtualNetworks/subnets
network_virtual_networks_subnets
The rule is deterministic so consumers, lint checks and tooling can derive the expected key for any ARM type without consulting the module source. Authors MUST NOT invent shorter aliases (e.g. widgets instead of example_widgets).
Variable shape
The resource_types variable MUST:
Be a single object({...}) (not a map(string)) so typos at call sites error at plan time and per-key defaults are visible in the variable declaration.
Default the variable itself to {} so consumers only need to supply the keys they wish to override.
Be nullable = false.
Declare one optional(string, "<provider>/<resource>@<api-version>") field for every AzAPI resource the module itself declares, defaulting each to the latest API version the module has been tested against. The default MUST be a stable (non-preview) API version unless the module’s primary resource only ships a preview API.
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource and therefore exposes its own resource_types variable (see TFRMNFR1). The shape of the nested object MUST match that submodule’s own resource_types variable exactly. The parent MUST NOT repeat the submodule’s defaults β the inner string attributes are declared as optional(string) (no default) so the submodule remains the single source of truth for its own tested API versions.
Document every field in the variable’s description.
Cascading to submodules
Because the nested slot in the parent mirrors the submodule’s variable, the parent cascades the slot through unchanged:
No renaming, repacking, or null filtering is required. When the consumer omits a key or sets it explicitly to null, Terraform substitutes the default declared on the owning module’s variable (per Terraform’s optional-attribute semantics).
The rationale for the variable is to let consumers:
Target sovereign clouds (e.g., Azure US Government, Azure China) where older API versions may be the latest available.
Opt into a newer preview API version without waiting for a module release.
Pin a specific API version for compliance or reproducibility reasons.
Nesting submodule slots inside the parent’s resource_types (rather than flattening every AzAPI resource into a single top-level namespace):
Keeps each module’s defaults co-located with the resource it owns.
Lets a submodule add or rename its own resources without forcing a breaking change on parent-module consumers who never touched those keys.
Makes the override surface mirror the actual module tree β a consumer looking at the parent’s variable can see, in shape, every resource managed beneath it.
Example β root, child and grandchild
A module managing Microsoft.Example/widgets, with a parts submodule for Microsoft.Example/widgets/parts, which in turn instantiates a component sibling submodule for Microsoft.Example/widgets/parts/components (per TFRMNFR1):
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the retry and timeouts blocks of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code values inline that the consumer cannot override.
To meet this requirement, the module MUST expose two variables:
retry β an object variable controlling the AzAPI retry block.
timeouts β an object variable controlling the AzAPI timeouts block.
Diff suppression via the AzAPI ignore_body_changes argument is covered separately by TFFR8, because its values are scoped to a single resource’s body and therefore MUST NOT be cascaded to submodules unchanged.
Both variables:
MAY define module-level defaults (e.g., a default error_message_regex such as "ScopeLocked" for resources that race with lock removal, or a default delete = "5m").
MUST allow the consumer to override the defaults β either by supplying a non-null value at the variable level, or by allowing per-field overrides through optional(...) attributes.
MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module.
MUST cascade to applicable submodules β the parent module’s retry and timeouts values MUST be passed through to each submodule it instantiates that directly declares a supported AzAPI resource (see TFRMNFR1). Submodules MAY additionally expose per-item overrides for cases where individual resources need different settings.
variable"retry" {
type = object({
error_message_regex = optional(list(string))
interval_seconds = optional(number)
max_interval_seconds = optional(number)
})
default = nulldescription = <<DESCRIPTIONRetry configuration applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (no custom retry).
- `error_message_regex` - (Optional) A list of regex patterns matching error messages that trigger a retry.
- `interval_seconds` - (Optional) Initial interval between retries in seconds.
- `max_interval_seconds` - (Optional) Maximum interval between retries in seconds.
See <https://registry.terraform.io/providers/Azure/azapi/latest/docs/resources/resource#retry> for full semantics.
DESCRIPTION}
variable"timeouts" {
type = object({
create = optional(string)
read = optional(string)
update = optional(string)
delete = optional(string)
})
default = nulldescription = <<DESCRIPTIONDefault per-operation timeouts applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (provider defaults). Each value is a Go duration string (e.g. `30m`, `1h`).
- `create` - (Optional) Timeout for create operations.
- `read` - (Optional) Timeout for read operations.
- `update` - (Optional) Timeout for update operations.
- `delete` - (Optional) Timeout for delete operations.
DESCRIPTION}
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ } # `retry` is an attribute on `azapi_resource`, so the variable can be
# assigned directly. `timeouts` is a block, so a `dynamic "timeouts"`
# block is required to honor the variable's `null` default.
retry = var.retrydynamic"timeouts" {
for_each = var.timeouts ==null? [] : [var.timeouts]
content {
create = timeouts.value.createread = timeouts.value.readupdate = timeouts.value.updatedelete = timeouts.value.delete }
}
response_export_values = []
}
module"child" {
source = "./modules/child" # Cascade retry and timeouts to the submodule.
retry = var.retrytimeouts = var.timeouts # ...other arguments...
}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the ignore_body_changes argument of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code an inline list that the consumer cannot override, and MUST NOT omit the argument.
To meet this requirement, every applicable module or submodule (see TFRMNFR1) MUST expose a variable named ignore_body_changes.
ignore_body_changes lets a consumer suppress plan diffs for a set of body paths that are mutated outside Terraform (for example tags applied by Azure Policy, or an autoscaler adjusting a capacity property). It is the supported fallback for lifecycle.ignore_changes when the paths must be derived from variables, locals or other non-static values, which lifecycle blocks cannot accept.
Without this variable a consumer has no way to reach the argument, because lifecycle.ignore_changes cannot be applied to a resource from outside the module that declares it. This is exactly the same problem that TFFR7 solves for retry and timeouts.
The module’s Azure/azapi constraint in required_providersMUST allow v2.12.0 or later, which is the release that introduces the argument (see TFFR3).
A consumer supplying a non-empty value MUST be running Terraform 1.11 or later. Modules MUST NOT raise their required_version floor for this reason alone (see TFNFR25); instead they MUST emit null when the list is empty so that consumers on earlier Terraform versions who do not use the feature are unaffected. See Applying the variable.
Important
Because the value is held in provider-private state, a change to ignore_body_changes only takes effect after an apply. A consumer who adds a path will still see the pending diff for that path in the same plan, and a consumer who removes a path will not see the suppressed diff reappear until the next plan. Module documentation SHOULD call this out.
Variable shape
Unlike retry and timeouts, which are resource-agnostic and therefore cascade unchanged, ignore_body_changes values are dot-notation paths into one specific resource’sbody. A path such as properties.addressSpace is meaningful only for the resource that owns it, so passing a parent’s list straight through to a submodule would apply meaningless paths to a different resource.
The variable is therefore scoped per resource and per submodule, using exactly the same shape and key-naming rule as resource_types (TFFR6).
The ignore_body_changes variable MUST:
Be a single object({...}) (not a map(list(string))) so typos at call sites error at plan time and the full override surface is visible in the variable declaration.
Default the variable itself to {} and be nullable = false, per TFNFR20 and TFNFR21.
Declare one optional(list(string), []) field for every AzAPI resource the module itself declares, keyed by the snake_case form of the ARM resource type with the Microsoft. prefix dropped β the identical key used in resource_types (for example Microsoft.Example/widgets β example_widgets).
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource, keyed by that submodule’s primary ARM resource type. The shape of the nested object MUST match that submodule’s own ignore_body_changes variable exactly, and the parent MUST cascade the slot through unchanged.
Document every field in the variable’s description, including what ignore_body_changes does, that paths use dot notation, and that changes take effect only after an apply.
Module owners MAY ship module-level defaults where the resource is known to be mutated outside Terraform. To do so, supply the default inside the optional(list(string), [...]) wrapper. Consumers MUST still be able to override any individual field, and a module-level default MUST NOT be used to work around a bug that belongs in the module body.
Modules MAY additionally expose per-item overrides on the collection variable that drives a for_each submodule, for cases where individual instances need different paths. Where they do, the per-item value MUST take precedence over the shared slot.
Path syntax
Values are dot-notation paths relative to the resource’s body, for example tags or properties.sku.name. Each element MUST be a non-empty string.
Individual list items MUST NOT be targeted (there is no index syntax) β ignore the entire list property instead.
Authors and consumers MUST understand that an ignored path is not merely hidden from the plan: configuration changes at that path are not sent to Azure until the path is removed from the list.
Applying the variable
ignore_body_changes is an attribute (not a block) on azapi_resource, so the relevant field of the variable is assigned directly. The assignment MUST collapse an empty list to null so that the write-only argument is absent when the feature is unused:
ID: TFFR9 - Category: Inputs/Outputs - AzAPI - Tag Propagation
Applicability
This requirement applies independently to every root module and submodule that directly declares a managed AzAPI resource. The avm_azapi_resource_tags_required rule uses its embedded AVM-generated capability snapshot to classify the resource type’s tags property as writable, read-only, or unsupported.
Requirement
For every resource type with a statically writable tags property, the resource MUST expose consumer-settable tags through the standard tags interface and set the tags argument. A direct assignment remains valid for modules that use only the module-wide fallback:
resource"azapi_resource""this" {
type = var.resource_types.example_widgetstags = var.tags}
When the module exposes the optional resource_tags interface, a non-null override for the Terraform resource block label MUST replace var.tags completely. An omitted or null override MUST inherit var.tags, and an empty map MUST remain an intentional empty replacement. The implementation MUST NOT merge the fallback and override maps.
Resource override keys identify Terraform resource block labels, not ARM resource types. Submodule overrides MUST use the deterministic typed resource_tags.modules.<module_label> shape defined by the standard tags interface. The separate resources and modules namespaces MUST resolve identical resource and module labels without ambiguity.
For every resource type with a statically read-only or unsupported tags property, the resource MUST NOT set a tags argument. Do not use a conditional, dynamic value, or an empty map to force tags onto these types.
The validation skips dynamic or otherwise unevaluable type expressions to avoid false positives. Authors SHOULD keep resource types statically resolvable through var.resource_types as required by TFFR6.
The embedded AVM-generated capability snapshot, rather than a hand-maintained module allowlist or an AzAPI import, is the authority for this classification.
ID: TFNFR14 - Category: Inputs - Not allowed variables
Since Terraform 0.13, count, for_each and depends_on are introduced for modules, module development is significantly simplified. Module’s owners MUST NOT add variables like enabled or module_depends_on to control the entire module’s operation. Boolean feature toggles are acceptable however.
ID: TFNFR38 - Category: Inputs/Outputs - Resource ID Variable Validation
Every input variable (or nested attribute) that holds an Azure ARM resource ID MUST be validated using the AzAPI provider-defined function provider::azapi::parse_resource_id, called with a literal string naming the expected resource type, and wrapped in can(...).
Hand-rolled regex, startswith, length, or split checks MUST NOT be used to validate resource IDs. The provider function knows the canonical ARM ID grammar for every resource type, is fixed in lockstep with the provider, and produces a single consistent error model β including for IDs whose grammar contains anomalies (such as classic resources, extension resources, or scope-based IDs).
This rule covers, but is not limited to:
Top-level scope variables such as parent_id (see TFRMFR1).
Variables that reference other Azure resources by ID (e.g. subnet_resource_id, key_vault_resource_id, workspace_resource_id, private_dns_zone_resource_ids, user_assigned_resource_ids).
Nested attributes inside object, map(object), set(object), or list(object) types that hold resource IDs.
Rules
The resource type passed to parse_resource_idMUST be a literal string (e.g. "Microsoft.Network/virtualNetworks/subnets"). It MUST NOT be a reference to another variable, local, or expression. This keeps each validation block self-contained and avoids requiring cross-variable validation.
For optional / nullable variables, the validation MUST short-circuit on null (e.g. var.x == null || can(provider::azapi::parse_resource_id("...", var.x))) so that callers omitting the value do not trip validation.
For collection-valued variables (set(string), list(string), map(string)), the validation MUST iterate the collection with alltrue([for v in ... : can(...)]).
For nested attributes within object types, the validation MUST iterate the parent collection (or reference the object directly) and validate each nested resource ID, again handling null for optional nested attributes.
Where a variable can legitimately hold IDs of more than one resource type (rare β e.g. marketplace_partner_resource_id in the diagnostic-settings interface), this rule does not apply and the variable SHOULD be left without resource-ID validation rather than validated against a single arbitrary type.
Examples
A required, single-value resource ID:
variable"key_vault_resource_id" {
type = stringnullable = falsevalidation {
condition = can(provider::azapi::parse_resource_id("Microsoft.KeyVault/vaults", var.key_vault_resource_id))
error_message = "`key_vault_resource_id` must be a valid Azure Key Vault resource ID." }
description = "The resource ID of the Key Vault that holds the customer-managed key."}
An optional, single-value resource ID:
variable"workspace_resource_id" {
type = stringdefault = nullnullable = truevalidation {
condition = var.workspace_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.OperationalInsights/workspaces", var.workspace_resource_id))
error_message = "`workspace_resource_id` must be a valid Log Analytics workspace resource ID, or `null`." }
description = "The resource ID of the Log Analytics workspace to send diagnostics to."}
A collection of resource IDs:
variable"user_assigned_resource_ids" {
type = set(string)
default = []
nullable = falsevalidation {
condition = alltrue([
foridin var.user_assigned_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", id))
])
error_message = "Each entry in `user_assigned_resource_ids` must be a valid user-assigned managed identity resource ID." }
description = "A set of user-assigned managed identity resource IDs to attach to the resource."}
A nested resource ID inside a map(object(...)):
variable"private_endpoints" {
type = map(object({
subnet_resource_id = stringprivate_dns_zone_resource_ids = optional(set(string), []) # ...other attributes...
}))
default = {}
nullable = falsevalidation {
condition = alltrue([
for_, vin var.private_endpoints: can(provider::azapi::parse_resource_id("Microsoft.Network/virtualNetworks/subnets", v.subnet_resource_id))
])
error_message = "Each `private_endpoints[*].subnet_resource_id` must be a valid subnet resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
foridinv.private_dns_zone_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.Network/privateDnsZones", id))
]
]))
error_message = "Each entry in `private_endpoints[*].private_dns_zone_resource_ids` must be a valid private DNS zone resource ID." }
}
Notes
The rule applies regardless of whether the resource ID is required or optional, single-valued or collection-valued, top-level or nested.
parse_resource_id errors when (a) the input is not a well-formed ARM ID, or (b) the input does not parse as the supplied resource type. Wrapping in can(...) converts both failure modes into a single boolean suitable for a validation block’s condition.
This rule supersedes any older guidance suggesting startswith(var.x, "/") or hand-written regex for resource ID validation.
Testing
The content below is listed based on the following tags
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
Module owners MUST test that child and extension resources and those Bicep or Terreform interface resources that are supported by their modules, are validated in E2E tests as per SNFR2 to ensure they deploy and are configured correctly.
These MAY be tested in a separate E2E test and DO NOT have to be tested in each E2E test.
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
Where descriptions for variables and outputs spans multiple lines. The description MAY provide variable input examples for each variable using the HEREDOC format and embedded markdown.
Example:
variable"my_complex_input" {
type = map(object({
param1 = stringparam2 = optional(number, null)
}))
description = <<DESCRIPTION A complex input variable that is a map of objects.
Each object has two attributes:
- `param1`: A required string parameter.
- `param2`: (Optional) An optional number parameter.
Example Input:
```terraform
my_complex_input = {
"object1" = {
param1 = "value1"
param2 = 2
}
"object2" = {
param1 = "value2"
}
}
```
DESCRIPTION }
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
Terraform Resource Module Specifications
Contribution / Support
The content below is listed based on the following tags
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
Module owners MUST set a branch protection policy on their GitHub Repositories for AVM modules against their default branch, typically main, to do the following:
Requires a Pull Request before merging
Require approval of the most recent reviewable push
Dismiss stale pull request approvals when new commits are pushed
Require linear history
Prevents force pushes
Not allow deletions
Require CODEOWNERS review
Do not allow bypassing the above settings
Above settings MUST also be enforced to administrators
Tip
If you use the template repository as mentioned in the contribution guide, the above will automatically be set.
Telemetry
The content below is listed based on the following tags
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
Terraform
Currently, no further requirements apply.
Naming / Composition
The content below is listed based on the following tags
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
ID: SFR5 - Category: Composition - Availability Zones
Modules that deploy zone-redundant resources MUST enable the spanning across as many zones as possible by default, typically all 3.
Modules that deploy zonal resources MUST provide the ability to specify a zone for the resources to be deployed/pinned to. However, they MUST NOT default to a particular zone by default, e.g. 1 in an effort to make the consumer aware of the zone they are selecting to suit their architecture requirements.
For both scenarios the modules MUST expose these configuration options via configurable parameters/variables.
ID: SFR6 - Category: Composition - Data Redundancy
Modules that deploy resources or patterns that support data redundancy SHOULD enable this to the highest possible value by default, e.g. RA-GZRS. When a resource or pattern doesn’t provide the ability to specify data redundancy as a simple property, e.g. GRS etc., then the modules MUST provide the ability to enable data redundancy for the resources or pattern via parameters/variables.
For example, a Storage Account module can simply set the sku.name property to Standard_RAGZRS. Whereas a SQL DB or Cosmos DB module will need to expose more properties, via parameters/variables, to allow the specification of the regions to replicate data to as per the consumers requirements.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
Resource modules support the following optional features/extension resources, as specified, if supported by the primary resource. The top-level variable/parameter names MUST be:
Optional Features/Extension Resources
Bicep Parameter Name
Terraform Variable Name
MUST/SHOULD
Diagnostic Settings
diagnosticSettings
diagnostic_settings
MUST
Role Assignments
roleAssignments
role_assignments
MUST
Resource Locks
lock
lock
MUST
Tags
tags
tags
MUST
Managed Identities (System / User Assigned)
managedIdentities
managed_identities
MUST
Private Endpoints
privateEndpoints
private_endpoints
MUST
Customer Managed Keys
customerManagedKey
customer_managed_key
MUST
Azure Monitor Alerts
alerts
alerts
SHOULD
Resource modules MUST NOT deploy required/dependent resources for the optional features/extension resources specified above. For example, for Diagnostic Settings the resource module MUST NOT deploy the Log Analytics Workspace, this is expected to be already in existence from the perspective of the resource module deployed via another method/module etc.
Note
Please note that the implementation of Customer Managed Keys from an ARM API perspective is different across various RPs that implement Customer Managed Keys in their service. For that reason you may see differences between modules on how Customer Managed Keys are handled and implemented, but functionality will be as expected.
Module owners MAY choose to utilize cross repo dependencies for these “add-on” resources, or MAY chose to implement the code directly in their own repo/module. So long as the implementation and outputs are as per the specifications requirements, then this is acceptable.
Tip
Make sure to checkout the language specific specifications for more info on this:
Resource modules MUST implement a common interface, e.g. the input’s data structures and properties within them (objects/arrays/dictionaries/maps), for the optional features/extension resources:
When a given version of an Azure resource used in a resource module reaches its end-of-life (EOL) and is no longer supported by Microsoft, the module owner SHOULD ensure that:
The module is aligned with these changes and only includes supported versions of the resource. This is typically achieved through the allowed values in the parameter that specifies the resource SKU or type.
The following notice is shown under the Notes section of the module’s readme.md. (If any related public announcement is available, it can also be linked to from the Notes section.):
“Certain versions of this Azure resource reached their end of life. The latest version of this module only includes supported versions of the resource. All unsupported versions have been removed from the related parameters.”
AND the related parameter’s description:
“Certain versions of this Azure resource reached their end of life. The latest version of this module only includes supported versions of the resource. All unsupported versions have been removed from this parameter.”
Resource modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Report missing or incorrect resource names to the AVM core team. Index corrections go through catalog generation and reviewed publication.
Bicep Resource Module Naming
Naming convention (module name for registry): avm/res/<hyphenated resource provider name>/<hyphenated ARM resource type>
Example: avm/res/compute/virtual-machine or avm/res/managed-identity/user-assigned-identity
Segments:
res defines this is a resource module
<hyphenated resource provider name> is the resource provider’s name after the Microsoft part, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Compute = compute, Microsoft.ManagedIdentity = managed-identity.
<hyphenated ARM resource type> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Compute/virtualMachines = virtual-machine, BUTMicrosoft.Network/trafficmanagerprofiles = trafficmanagerprofile - since trafficmanagerprofiles is all lower case as per the ARM API definition.
Bicep Child Module Naming
Naming convention (module name for registry):avm/res/<hyphenated resource provider name>/<hyphenated ARM resource type>/<hyphenated child resource type/<hyphenated grandchild resource type>/<etc.>
Example: avm/res/network/virtual-network/subnet or avm/res/storage/storage-account/blob-service/container
Segments:
res defines this is a resource module
<hyphenated resource provider name> is the resource provider’s name after the Microsoft part, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network = network.
<hyphenated ARM resource type> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network/virtualNetworks = virtual-network.
<hyphenated child resource type (to be repeated for grandchildren, etc.)> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network/virtualNetworks/subnets = subnet or Microsoft.Storage/storageAccounts/blobServices/containers = blob-service/container.
Terraform Resource Module Naming
Naming convention:
avm-res-<resource provider>-<ARM resource type> (module name for registry)
terraform-<provider>-avm-res-<resource provider>-<ARM resource type> (GitHub repository name to meet registry naming requirements)
Example: avm-res-compute-virtualmachine or avm-res-managedidentity-userassignedidentity
Segments:
<provider> is a legacy requirement of the Terraform registry. This must be set to azure
res defines this is a resource module
<resource provider> is the resource provider’s name after the Microsoft part, e.g., Microsoft.Compute = compute.
<ARM resource type> is the singular version of the word after the resource provider, e.g., Microsoft.Compute/virtualMachines = virtualmachine
ID: RMNFR3 - Category: Composition - RP Collaboration
Module owners (Microsoft FTEs) SHOULD reach out to the respective Resource Provider teams to build a partnership and collaboration on the modules creation, existence and long term maintenance.
Module owners MAY cross-references other modules to build either Resource or Pattern modules. However, they MUST be referenced only by a HashiCorp Terraform registry reference to a pinned version e.g.,
Every new AVM Terraform module β resource, pattern, or utility β MUST use Azure/azapi for every Azure control-plane resource and every data-plane operation supported by AzAPI. The AzureRM provider is permitted only for the unsupported data-plane/non-ARM API exception defined below.
Authors MUST only use the following Azure providers, and versions, in their modules:
provider
min version
max version
permitted use
Azure/azapi
>= 2.12
< 3.0
All Azure control-plane resources and supported data-plane operations
hashicorp/azurerm
>= 4.0
< 5.0
Only a specific unsupported data-plane/non-ARM API operation under the exception below
Pattern modules MAY also use other Microsoft-maintained providers when required by the pattern. Examples include integrations/github, microsoft/azuredevops, microsoft/fabric, and microsoft/msgraph. Each provider MUST be declared with minimum and maximum major version constraints as required by TFNFR26.
Resource and utility modules MUST NOT use these additional providers. Except for the narrow AzureRM exception below, third-party providers MUST NOT be used by any AVM Terraform module, regardless of module classification.
Note
The AzAPI floor is 2.12 because TFFR8 requires every module to expose the ignore_body_changes argument, which was introduced in Azure/azapi v2.12.0. Modules pinned below that version will fail to plan because the argument is absent from the provider schema.
This prohibition applies to every Terraform configuration shipped with the module, including:
The root module and all submodules.
Every configuration under examples/, including examples executed as end-to-end tests.
Terraform tests, test fixtures, and supporting setup configurations.
Terraform snippets in _header.md, _footer.md, generated documentation, and other repository documentation.
Supporting control-plane resources needed by an example, end-to-end test, or fixture MUST use AzAPI. AzureRM MUST NOT be used for resource groups, role assignments, monitoring resources, networking, or any other ARM control-plane resource.
Exception β unsupported data-plane/non-ARM API operations
An AVM Terraform module that is otherwise built with AzAPI MAY declare the AzureRM provider only for a specific data-plane or non-ARM API operation whose functionality is genuinely unavailable through azapi_data_plane_resource, azapi_resource, azapi_resource_action, or azapi_update_resource. This exception is intended for isolated operations such as a data-plane resource whose AzureRM implementation calls a service endpoint rather than Azure Resource Manager. It is not a general fallback for a missing or inconvenient AzAPI schema. Every azurerm_* block MUST independently satisfy this exception; one permitted block does not authorize any other AzureRM use.
Where this exception applies, the module MUST:
Continue to declare and use AzAPI as its required, primary Azure provider.
Scope every azurerm_* resource or data source to the exact unsupported data-plane/non-ARM operation.
Pin the AzureRM provider to ~> 4.0 in required_providers.
Use AzAPI for every control-plane resource and every data-plane operation that AzAPI supports.
Document the exception in the module’s README.md, including each azurerm_* block, the data-plane/non-ARM API it wraps, why AzAPI cannot implement it, and the upstream AzAPI issue or pull request tracking support.
Replace the azurerm_* block with AzAPI in the next module release after the required capability ships.
Examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets MAY configure or exercise AzureRM only when required by that exact permitted data-plane operation. All supporting control-plane resources in those surfaces MUST use AzAPI.
This exception MUST NOT be used to:
Implement any ARM control-plane resource.
Avoid AzAPI because its body schema is more verbose or less convenient.
Avoid raising an AzAPI capability gap for an unsupported control-plane operation.
Side-step any AzAPI-specific specification that applies to the module’s AzAPI resources.
The azurerm remote state backend and the final segment of a published Terraform Registry module address, such as /azurerm in an existing AVM module source, are names and are not provider declarations. They MAY appear where required for state storage or to reference an existing published AVM module. A dependency’s provider implementation is governed by that dependency’s own repository; its Registry address does not by itself justify a direct hashicorp/azurerm declaration or azurerm_* block in the consuming module repository. Any such direct use MUST independently satisfy the data-plane exception above.
Authors MUST use the required_providers block in their module to enforce the provider versions.
Authors MUST specify the response_export_values argument when using the AzAPI provider:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US"response_export_values = [] # must be specified, even if empty
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
If you require read-only properties to be returned from the resource, you SHOULD include them as follows:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US" # Example as a list:
response_export_values = ["properties.readOnlyProperty"] # Example as a map:
# response_export_values = {
# read_only_property = "properties.readOnlyProperty"
# }
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
output"read_only_property" { # Example if response_export_values is a list:
value = azapi_resource.example.output.properties.readOnlyProperty # Example if response_export_values is a map:
# value = azapi_resource.example.output.read_only_property
}
Authors MUST omit replace_triggers_refs when no body properties require replacement. When one or more body properties require replacement, authors MUST set replace_triggers_refs to a non-empty static list of JMESPath expressions that identify those paths.
Each expression MUST be valid JMESPath syntax, non-blank, and unique within the list. Do not include name or location, as AzAPI already replaces the resource when either changes. When the resource body is statically evaluable, every declared expression MUST resolve against that body.
This is to ensure that changes to properties that require replacement of the resource are handled correctly by Terraform. Authors remain responsible for identifying every property that actually requires replacement. Current Bicep-generated schemas do not reliably preserve whether a property is create-only or updateable, so the rule validates declared paths but cannot prove that the list is semantically complete.
ID: TFRMNFR1 - Category: Composition - Subresources as submodules
Resource modules MUST implement each ARM subresource (a child resource type as defined in the API spec, for example Microsoft.Example/widgets/parts is a subresource of Microsoft.Example/widgets) as a Terraform submodule.
Submodules MUST be located in a direct modules/<subresource-singular-name>/ child directory at the repository root, where <subresource-singular-name> is the singular form of the ARM subresource name as per PMNFR1. Nested Terraform module roots are prohibited: modules/<name>/modules/<name>/ is not an AVM module scope.
Terraform example roots follow the same one-layer convention: each example MUST be a direct examples/<name>/ child directory. Nested example roots are prohibited.
Avm.Authoring convention validation enforces the direct modules/* and examples/* scope structure. Consequently, directory-specific TFLint overrides apply only at those direct roots; see TFLint configuration overrides.
For example, a resource module for Microsoft.Example/widgets would have the following layout:
The parent module MUST reference and compose its submodules so that supported subresources can be expressed through the parent module, but each submodule MUST also be independently consumable.
“Independently consumable” means a caller can source the submodule directly and use it without relying on hidden behavior in the parent module. Therefore, a submodule MUST follow the same interface and specification rules as a root AVM Terraform module (as listed below), even when the parent module also instantiates it.
Submodule cardinality
Submodules MUST deploy exactly one instance of the resource they manage. The submodule’s primary azapi_resource (or equivalent) MUST NOT declare count or for_each, and the submodule MUST NOT otherwise create multiple instances of its primary resource.
Cardinality is the parent module’s responsibility: the parent module MUST use count or for_each on its submodule call to control how many instances of the subresource are deployed. This keeps each submodule’s variables, outputs and tests focused on a single resource and pushes cardinality concerns up to the consumer.
This rule applies equally when a submodule is consumed through its parent module and when the same submodule is consumed directly by another caller.
For example, a parent module deploying multiple parts calls its part submodule using for_each, cascades the matching nested slot from its own resource_types (see TFFR6 for the naming rule and nested-slot pattern), passes retry and timeouts through unchanged (see TFFR7), and cascades the matching nested slot from its own ignore_body_changes (see TFFR8):
When the ARM subresource type is more than one level deep (for example Microsoft.Example/widgets/parts/components), its Terraform module root still MUST be a direct child of modules/. Use a descriptive direct name such as modules/part-component/; do not create modules/part/modules/component/. The parent module composes all direct submodules and exposes the required nested interface values without creating nested Terraform roots.
The following pattern is NOT allowed inside a submodule, because it pushes cardinality into the submodule itself:
Submodules MAY reference a direct sibling submodule using a relative path:
# Inside modules/part/main.tf, calling the direct sibling modules/sub-part/
module"sub_part" {
source = "../sub-part" # ...other arguments...
}
This pattern is useful when an ARM resource provider exposes child resources nested more than one level deep, while preserving the required one-layer module-root layout.
Submodules MUST NOT reference a sibling submodule via the Terraform Registry (for example Azure/avm-res-example-widget/azure//modules/part) or via a Git URL when the sibling lives in the same repository. Using a relative path keeps the entire module tree as a single unit that can be developed, tested and released atomically.
Submodule documentation files
Each submodule directory MUST contain its own _header.md and _footer.md files at the root of the submodule (alongside main.tf). These files are consumed by the AVM terraform-docs documentation generation pipeline (see TFNFR2) to produce the submodule’s README.md. Without them, the generated submodule documentation will be missing its introduction and footer sections and the documentation pipeline will not produce a complete README.md.
The submodule _header.md and _footer.mdMUST:
Describe the subresource the submodule manages, not the parent resource.
Be checked in to source control (they are inputs to documentation generation, not generated artifacts).
Be present in every submodule under modules/, even if the submodule is not intended to be consumed independently.
Submodules are full AVM modules
Submodules MUST meet every requirement that applies to a top-level AVM Terraform resource module, including (but not limited to):
All shared specifications (SFR and SNFR prefixed specs).
All resource module specifications (RMFR and RMNFR prefixed specs).
All Terraform specifications (TFFR and TFNFR prefixed specs), including:
TFFR3 β AzAPI is mandatory for every control-plane resource and supported data-plane operation in every module and submodule; AzureRM is permitted only for the documented unsupported data-plane/non-ARM API exception.
TFFR6 β resource_types variable. Each submodule declares its own resource_types for the resources it owns; the parent declares a nested optional(object({...}), {}) slot per submodule that mirrors the submodule’s variable exactly, and cascades it through unchanged.
TFFR7 β retry and timeouts variables, which the parent module MUST cascade to each submodule unchanged.
TFFR8 β ignore_body_changes variable. Each submodule declares its own for the resources it owns; the parent declares a nested optional(object({...}), {}) slot per submodule that mirrors the submodule’s variable exactly, and cascades it through unchanged. The parent’s own paths MUST NOT be cascaded, because they are scoped to the parent’s body.
All applicable interface specifications (managed identities, role assignments, locks, diagnostic settings, private endpoints, customer-managed keys, tags) β for any interface that is supported by the underlying ARM subresource.
To avoid duplication, this specification deliberately states the requirement once: every requirement that applies to a top-level resource module applies equally to every one of its submodules. Where a requirement contradicts the submodule’s nature (for example, a submodule that is never published independently still MUST include all required documentation files but is not itself listed in the registry), the requirement is interpreted in the context of the submodule.
Rationale
Implementing subresources as submodules:
Provides a clean, narrowly-scoped Terraform interface per ARM resource type, mirroring the ARM/AzAPI model where each resource type has its own type identifier and API version.
Allows consumers to use only the subresources they need, without paying the cost of unused resources.
Keeps each submodule’s variables, outputs and tests focused, which improves readability, testability and review velocity.
Aligns with the equivalent Bicep guidance in BCPRMNFR3 so that AVM resource modules in both languages share a consistent structure.
The primary azapi_resource (or equivalent AzAPI resource) declared in a Terraform resource module MUST be named this. The same rule applies to the primary resource declared in any submodule (per TFRMNFR1).
The “primary resource” is the single Azure resource that the module exists to manage β the one whose ARM resource type appears in the module’s name (per RMNFR1). Every other resource declared by the module (locks, role assignments, diagnostic settings, private endpoints, private DNS zone groups, child / extension resources required by the primary resource, etc.) is a satellite resource and MUST NOT be named this; instead, satellites MUST be named after what they represent (for example azapi_resource.lock, azapi_resource.role_assignments, azapi_resource.diagnostic_settings, azapi_resource.private_endpoints).
Standardizing on this for the primary resource lets consumers, CI checks, and the AVM interface utility module reference it predictably β most notably as azapi_resource.this.id for downstream parent_id wiring, and azapi_resource.this.output for exported values.
Example
The resource label (this) and the var.resource_types.<key> argument supplied to type = are independent concerns: the label is governed by this spec, the key by the naming rule in TFFR6. this is therefore never a valid resource_types key β the key names the AzAPI resource type, not the Terraform graph node.
The this rule MAY be relaxed only when all of the following are true:
The module is a utility module (per Module Classifications) OR the module’s primary functionality is implemented by two or more azapi_resource declarations that are peers (no resource is the ARM parent of any other, and no resource depends on another resource’s ID for its own creation).
No single azapi_resource would, on its own, be a meaningful handle for downstream consumers (i.e. there is no resource whose id would be the obvious value of a single canonical resource_id output).
A module where one azapi_resource is the ARM parent of, or a hard dependency for, another azapi_resource is NOT exempted β the parent resource is the primary and MUST be named this.
Where this exception applies, each resource MUST be named after what it represents, and the module’s README.mdMUST document why the this convention does not apply.
Notes
This rule applies regardless of whether the primary resource uses azapi_resource, azapi_resource_action, azapi_update_resource, or any other AzAPI resource type.
The rule applies independently to every submodule: each submodule has its own this (the primary resource it manages) β that is the contract enabling the parent module to write module.<submodule>.resource_id.
The rule does not apply to data sources or to azapi_resource_list lookups; those SHOULD still be named after what they represent.
Code Style
The content below is listed based on the following tags
We can use count and for_each to deploy multiple resources, but using count with an ordered collection can create an index anti-pattern where removing one item unexpectedly changes other resource addresses.
You can use count to create some kind of resources under certain conditions, for example:
The module’s owners MUST use map(xxx) or set(xxx) as resource’s for_each collection, the map’s key or set’s element MUST be static literals.
Good example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_map // `map(string)`, when user call this module, it could be: `{ "subnet0": "subnet0" }`, or `{ "subnet0": azapi_resource.subnet0.name }`
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
Bad example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_name_set // `set(string)`, when user use `toset([azapi_resource.subnet0.name])`, it would cause an error.
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
There are 3 types of assignment statements in a resource or data block: argument, meta-argument and nested block. The argument assignment statement is a parameter followed by =:
location = azapi_resource.example.location
or:
tags = {
environment = "Production"}
Nested block is a assignment statement of parameter followed by {} block:
subnet {
name = "subnet1"address_prefix = "10.0.1.0/24"}
Meta-arguments are assignment statements can be declared by all resource or data blocks. They are:
count
depends_on
for_each
lifecycle
provider
The order of declarations within resource or data blocks is:
All the meta-arguments SHOULD be declared on the top of resource or data blocks in the following order:
provider
count
for_each
Then followed by:
required arguments
optional arguments
required nested blocks
optional nested blocks
All ranked in alphabetical order.
These meta-arguments SHOULD be declared at the bottom of a resource block with the following order:
depends_on
lifecycle
The parameters of lifecycle block SHOULD show up in the following order:
create_before_destroy
ignore_changes
prevent_destroy
parameters under depends_on and ignore_changes are ranked in alphabetical order.
Meta-arguments, arguments and nested blocked are separated by blank lines.
dynamic nested blocks are ranked by the name comes after dynamic, for example:
Sometimes we need to ensure that the resources created are compliant to some rules at a minimum extent, for example a subnet has to be connected to at least one network_security_group. The user SHOULD pass in a security_group_id and ask us to make a connection to an existing security_group, or want us to create a new security group.
The disadvantage of this approach is if the user create a security group directly in the root module and use the id as a variable of the module, the expression which determines the value of count will contain an attribute from another resource, the value of this very attribute is “known after apply” at plan stage. Terraform core will not be able to get an exact plan of deployment during the “plan” stage.
For this kind of parameters, wrapping with object type is RECOMMENDED:
variable"security_group" {
type:object({
id = string })
default = null}
The advantage of doing so is encapsulating the value which is “known after apply” in an object, and the object itself can be easily found out if it’s null or not. Since the id of a resource cannot be null, this approach can avoid the situation we are facing in the first example, like the following:
variable used as feature switches SHOULD apply a positive statement, use xxx_enabled instead of xxx_disabled. Avoid double negatives like !xxx_disabled.
Please use xxx_enabled instead of xxx_disabled as name of a variable.
ID: TFNFR17 - Category: Code Style - Variables with Descriptions
The target audience of description is the module users.
For a newly created variable (Eg. variable for switching dynamic block on-off), it’s descriptionSHOULD precisely describe the input parameter’s purpose and the expected data type. descriptionSHOULD NOT contain any information for module developers, this kind of information can only exist in code comments.
For object type variable, description can be composed in HEREDOC format:
variable"kubernetes_cluster_key_management_service" {
type:object({
key_vault_key_id = stringkey_vault_network_access = optional(string)
})
default = nulldescription = <<DESCRIPTION- `key_vault_key_id` - (Required) Identifier of Azure Key Vault key. See [key identifier format](https://learn.microsoft.com/en-us/azure/key-vault/general/about-keys-secrets-certificates#vault-name-and-object-name) for more details. When Azure Key Vault key management service is enabled, this field is required and must be a valid key identifier. When `enabled` is `false`, leave the field empty.
- `key_vault_network_access` - (Optional) Network access of the key vault Network access of key vault. The possible values are `Public` and `Private`. `Public` means the key vault allows public access from all networks. `Private` means the key vault disables public access and enables private link. Defaults to `Public`.
DESCRIPTION}
You MUST remove all trailing whitespace so that terraform-docs renders the readme properly.
ID: TFNFR19 - Category: Code Style - Sensitive Data Variables
If variable’s type is object and contains one or more fields that would be assigned to a sensitive argument, then this whole variableSHOULD be declared as sensitive = true, otherwise you SHOULD extract sensitive field into separated variable block with sensitive = true.
Nullable SHOULD be set to false for collection values (e.g. sets, maps, lists) when using them in loops. However for scalar values like string and number, a null value MAY have a semantic meaning and as such these values are allowed.
MAPOTF removes redundant explicit nullable = true. That formatting cleanup does not change this requirement and does not imply that a collection is semantically safe to make nullable.
nullable = trueMUST be avoided. MAPOTF removes redundant explicit nullable = true; this cleanup is distinct from, and does not satisfy, the requirement to set nullable = false where a meaningful zero value exists.
Variables MUST be declared with nullable = false whenever the variable’s type has a meaningful zero value ({} for objects/maps, [] for lists/sets, "" for strings where empty has the same meaning as absent, etc.). Consumers should signal “no value” by omitting the input, not by explicitly passing null.
Exception β behavior-toggle inputs
A small, well-defined class of inputs MAY keep the implicit nullable = true (i.e. default = null) where null carries a distinct semantic meaning of “no override β use the underlying provider/AVM defaults”, and where representing that state with the type’s zero value would be ambiguous or wrong. Examples include:
var.retry and var.timeouts (per TFFR7) β null means “do not emit a retry/timeouts block; use the AzAPI provider defaults”.
var.lock (per the AVM lock interface) β null means “do not create a management lock”.
Optional sub-objects that toggle whole feature blocks on/off, where {} would be indistinguishable from “feature enabled with all defaults”.
Where this exception applies, the variable MUST:
Use default = null (the implicit nullable = true is permitted only for this purpose).
State explicitly in its description what null means.
Be consumed with a null-aware pattern (e.g. count = var.lock != null ? 1 : 0, or dynamic "timeouts" { for_each = var.timeouts == null ? [] : [var.timeouts] }).
This exception does not extend to required inputs, to collection-shaped inputs (TFNFR20), or to nested attributes inside an object β those MUST use nullable = false and the type’s zero value.
variable"example_map" {
type =map(string)
default = {}
description ="An example map variable with an empty default value." sensitive =true}
Bad example:
variable"example_string" {
type =string default ="sensitive_value" description ="An example string variable with a sensitive default value." sensitive =true}
Sometimes we will find names for some variable are not suitable anymore, or a change SHOULD be made to the data type. We want to ensure forward compatibility within a major version, so direct changes are strictly forbidden. The right way to do this is move this variable to an independent deprecated_variables.tf file, then redefine the new parameter in variable.tf and make sure it’s compatible everywhere else.
Deprecated variableMUST be annotated as DEPRECATED at the beginning of the description, at the same time the replacement’s name SHOULD be declared. E.g.,
variable"enable_network_security_group" {
type = stringdefault = nulldescription = "DEPRECATED, use `network_security_group_enabled` instead; Whether to generate a network security group and assign it to the subnet. Changing this forces a new resource to be created."}
A cleanup of deprecated_variables.tfSHOULD be performed during a major version release.
The terraform.tf file MUST only contain one terraform block.
The first line of the terraform block MUST define a required_version property for the Terraform CLI. The standard Terraform TFLint plugin validates the requirement; MAPOTF keeps it first.
The required_version property MUST include a constraint on the minimum version of the Terraform CLI. Previous releases of the Terraform CLI can have unexpected behavior.
The required_version property MUST include a constraint on the maximum major version of the Terraform CLI. Major version releases of the Terraform CLI can introduce breaking changes and MUST be tested.
The required_version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
ID: TFNFR26 - Category: Code Style - Providers in required_providers
The terraform block in terraform.tfMUST contain the required_providers block.
Each provider used directly in the module MUST be specified with the source and version properties. The standard Terraform TFLint plugin validates the used-provider source and version requirements. MAPOTF sorts the required_providers entries alphabetically.
Do not add providers to the required_providers block that are not directly required by this module. If submodules are used then each submodule SHOULD declare its requirements in its own terraform.tf file.
The source property MUST be in the format of namespace/name. If this is not explicitly specified, it can cause failure.
The version property MUST include a constraint on the minimum version of the provider. Older provider versions may not work as expected.
The version property MUST include a constraint on the maximum major version. A provider major version release may introduce breaking change, so updates to the major version constraint for a provider MUST be tested.
The version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
By rule, every published AVM module and submodule MUST NOT declare a provider block. Provider configuration belongs exclusively to the consuming root module.
When a module requires an alternate provider instance, it MUST declare that alias through configuration_aliases in terraform.required_providers and the consumer MUST pass the configured alias through the module’s providers map. A provider block containing only alias is not permitted in an AVM module.
Sometimes we notice that the name of certain output is not appropriate anymore, however, since we have to ensure forward compatibility in the same major version, its name MUST NOT be changed directly. It MUST be moved to an independent deprecated_outputs.tf file, then redefine a new output in output.tf and make sure it’s compatible everywhere else in the module.
A cleanup SHOULD be performed to deprecated_outputs.tf and other logics related to compatibility during a major version upgrade.
ID: TFNFR31 - Category: Code Style - locals.tf for Locals Only
In locals.tf, file we could declare multiple locals blocks, but only locals blocks are allowed.
You MAY declare locals blocks next to a resource block or data block for some advanced scenarios, like making a fake module to execute some light-weight tests aimed at the expressions.
This specification applies only to existing legacy modules that still use AzureRM while they are being migrated. It does not apply to a new module that uses AzureRM solely for the narrow unsupported data-plane/non-ARM API exception in TFFR3, because that exception does not permit AzureRM resource-group management.
In a legacy AzureRM module, the prevent_deletion_if_contains_resources provider setting SHOULD be set to false until the module is migrated. Azure Policy remediation can add resources during a test run, and the provider’s default behavior can then prevent cleanup of the test resource group.
newres is a command-line tool that generates Terraform configuration files for a specified resource type. It automates the process of creating variables.tf and main.tf files, making it easier to get started with Terraform and reducing the time spent on manual configuration.
Module owners MAY use newres when they’re trying to add new resource block, attribute, or nested block. They MAY generate the whole block along with the corresponding variable blocks in an empty folder, then copy-paste the parts they need with essential refactoring.
ID: TFNFR39 - Category: Code Style - Standard File Layout
Every Terraform AVM module (root module and every submodule) MUST organize its top-level Terraform code into the following files at the module’s root directory:
File
Required
Contents
terraform.tf
MUST
The single terraform { β¦ } block β required_version, required_providers, and any backend configuration (root module only). Provider configuration blocks MUST NOT appear here.
variables.tf
MUST
All variable blocks for the module. MAY be split into additional variables.<topic>.tf files (see below).
outputs.tf
MUST
All output blocks for the module. MAY be split into additional outputs.<topic>.tf files (see below).
main.tf
MUST
The module’s primary resource, data, and module blocks. MAY be split into additional main.<topic>.tf files (see below).
locals.tf
SHOULD
All locals blocks. Required if the module declares any locals. MAY be split into additional locals.<topic>.tf files (see below). MAY be omitted only when the module has no locals at all.
Splitting and naming additional files
For larger modules the contents of main.tf, variables.tf, outputs.tf, and locals.tfMAY each be split into multiple files along logical / topic lines. When this is done:
Additional Terraform files MUST use the canonical filename (main, variables, outputs, or locals) as the prefix, followed by a ., a short descriptive topic name, and the .tf extension β for example main.diagnostic_settings.tf, variables.diagnostic_settings.tf, outputs.diagnostic_settings.tf, locals.diagnostic_settings.tf.
The same topic name SHOULD be used across the four file types when they describe the same logical concern, so that (for example) main.private_endpoints.tf, variables.private_endpoints.tf, outputs.private_endpoints.tf, and locals.private_endpoints.tf all relate to the same feature.
Each split file MUST contain only the block kind matching its prefix:
main.<topic>.tf β only resource, data, and module blocks.
variables.<topic>.tf β only variable blocks.
outputs.<topic>.tf β only output blocks.
locals.<topic>.tf β only locals blocks.
The terraform { β¦ } block MUST appear exactly once per module, in terraform.tf. It MUST NOT be split.
Files that MUST NOT appear at the module root
A providers.tf file β provider requirements belong in terraform.tf; provider configurations belong only in the consumer’s root module, never in an AVM module (per SFR2).
A single monolithic module.tf or everything.tf β the canonical filenames above MUST be used.
Rationale
Standardizing file layout means that any reviewer or consumer can find a module’s interface (variables.tf, outputs.tf), provider constraints (terraform.tf), and primary logic (main.tf / main.<topic>.tf) in the same place across every AVM Terraform module, without having to grep. It also makes the cascade rules in TFFR6, TFFR7, and TFRMNFR1 reviewable at a glance.
Submodules (per TFRMNFR1) follow the same layout in their own root directory under modules/<subresource>/. The submodule’s terraform.tfMUST declare the same set of required_providers it actually consumes.
Auto-generated documentation files (README.md, _header.md, _footer.md) and tooling configuration files (.terraform-docs.yml, .tflint.hcl, etc.) are out of scope of this rule and follow their own specs.
Structured values that are passed as JSON or YAML MUST be constructed with jsonencode or yamlencode, rather than a literal JSON or YAML heredoc. Native HCL objects, lists, conditionals, and for expressions keep the structure reviewable and let Terraform perform correct escaping.
Terraform interpolation (${...}), template directives (%{...}), unknown values, and dynamically generated lists or maps are not exceptions: construct the native HCL value and pass it to the encoder.
A heredoc MAY be used only when the value is not JSON or YAML, or when the receiving system requires opaque source text for a downstream templating engine or syntax that jsonencode or yamlencode cannot represent without changing its meaning. The heredoc must not use Terraform interpolation to assemble JSON or YAML in that case, and its reason must be clear from the surrounding configuration.
ID: TFNFR41 - Category: Code Style - Output Definition Order
output blocks in a module SHOULD be ordered alphabetically by output name. This applies to outputs.tf and every outputs.<topic>.tf file in the root module and each submodule.
output"id" {
value = azapi_resource.this.id}
output"name" {
value = azapi_resource.this.name}
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
Parameters/variables that pertain to the primary resource MUST NOT use the resource type in the name.
e.g., use sku, vs. virtualMachineSku/virtualmachine_sku
Another example for where RPs contain some of their name within a property, leave the property unchanged. E.g. Key Vault has a property called keySize, it is fine to leave as this and not remove the key part from the property/parameter name.
A resource module MUST use the following standard inputs:
name (no default)
location (if supported by the resource and not a global resource, then use Resource Group location, if resource supports Resource Groups, otherwise no default)
Authors SHOULD NOT output entire resource objects as these may contain sensitive outputs and the schema can change with API or provider versions. Instead, authors SHOULD output the computed attributes of the resource as discreet outputs. This kind of pattern protects against provider schema changes and is known as an anti-corruption layer.
Remember, you SHOULD NOT output values that are already inputs (other than name).
E.g.,
# Resource output, computed attribute.
output"foo" {
description = "MyResource foo attribute"value = azapi_resource.myresource.output.properties.foo}# Resource output for resources that are deployed using `for_each`. Again only computed attributes.
output"childresource_foos" {
description = "MyResource children's foo attributes"value = {
forkey, valueinazapi_resource.mychildresource:key => value.output.properties.foo }
}# Output of a sensitive attribute
output"bar" {
description = "MyResource bar attribute"value = azapi_resource.myresource.output.properties.barsensitive = true}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, authors MUST NOT hard-code the type argument of a supported AzAPI resource inline.
Instead, every AzAPI resource type string used by the module MUST be sourced from a single object variable named resource_types.
resource_types keys vs Terraform resource labels
These are two unrelated concepts and the spec treats them independently:
Keys in var.resource_types name the AzAPI resource type and are derived from the ARM type by the naming rule below. They appear on the right of an assignment as the value of the type argument.
Terraform resource labels (e.g. azapi_resource.this) name the graph node and govern how the resource is referenced elsewhere in HCL. The primary resource label MUST be this, per TFRMNFR2.
A typical primary-resource declaration therefore reads:
resource"azapi_resource""this" { # label per TFRMNFR2
type = var.resource_types.example_widgets # key per the naming rule below
# ...
}
this and example_widgets describe different things and are derived by different rules. They MUST NOT be made to coincide β this is never a valid resource_types key.
Key naming
Each resource_types key (at every level of nesting) MUST be the snake_case form of the ARM resource type, with the Microsoft. prefix dropped:
Drop the Microsoft. prefix.
Render the provider namespace as a single lowercase token β do not split internal camelCase (KeyVault β keyvault, DocumentDB β documentdb, EventHub β eventhub).
Convert each resource path segment after the provider from camelCase to snake_case (virtualNetworks β virtual_networks, roleAssignments β role_assignments).
Join the provider token and each path segment with _.
ARM type
Key
Microsoft.Example/widgets
example_widgets
Microsoft.Example/widgets/parts
example_widgets_parts
Microsoft.Example/widgets/parts/components
example_widgets_parts_components
Microsoft.Authorization/locks
authorization_locks
Microsoft.Authorization/roleAssignments
authorization_role_assignments
Microsoft.Insights/diagnosticSettings
insights_diagnostic_settings
Microsoft.KeyVault/vaults/secrets
keyvault_vaults_secrets
Microsoft.Network/virtualNetworks/subnets
network_virtual_networks_subnets
The rule is deterministic so consumers, lint checks and tooling can derive the expected key for any ARM type without consulting the module source. Authors MUST NOT invent shorter aliases (e.g. widgets instead of example_widgets).
Variable shape
The resource_types variable MUST:
Be a single object({...}) (not a map(string)) so typos at call sites error at plan time and per-key defaults are visible in the variable declaration.
Default the variable itself to {} so consumers only need to supply the keys they wish to override.
Be nullable = false.
Declare one optional(string, "<provider>/<resource>@<api-version>") field for every AzAPI resource the module itself declares, defaulting each to the latest API version the module has been tested against. The default MUST be a stable (non-preview) API version unless the module’s primary resource only ships a preview API.
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource and therefore exposes its own resource_types variable (see TFRMNFR1). The shape of the nested object MUST match that submodule’s own resource_types variable exactly. The parent MUST NOT repeat the submodule’s defaults β the inner string attributes are declared as optional(string) (no default) so the submodule remains the single source of truth for its own tested API versions.
Document every field in the variable’s description.
Cascading to submodules
Because the nested slot in the parent mirrors the submodule’s variable, the parent cascades the slot through unchanged:
No renaming, repacking, or null filtering is required. When the consumer omits a key or sets it explicitly to null, Terraform substitutes the default declared on the owning module’s variable (per Terraform’s optional-attribute semantics).
The rationale for the variable is to let consumers:
Target sovereign clouds (e.g., Azure US Government, Azure China) where older API versions may be the latest available.
Opt into a newer preview API version without waiting for a module release.
Pin a specific API version for compliance or reproducibility reasons.
Nesting submodule slots inside the parent’s resource_types (rather than flattening every AzAPI resource into a single top-level namespace):
Keeps each module’s defaults co-located with the resource it owns.
Lets a submodule add or rename its own resources without forcing a breaking change on parent-module consumers who never touched those keys.
Makes the override surface mirror the actual module tree β a consumer looking at the parent’s variable can see, in shape, every resource managed beneath it.
Example β root, child and grandchild
A module managing Microsoft.Example/widgets, with a parts submodule for Microsoft.Example/widgets/parts, which in turn instantiates a component sibling submodule for Microsoft.Example/widgets/parts/components (per TFRMNFR1):
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the retry and timeouts blocks of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code values inline that the consumer cannot override.
To meet this requirement, the module MUST expose two variables:
retry β an object variable controlling the AzAPI retry block.
timeouts β an object variable controlling the AzAPI timeouts block.
Diff suppression via the AzAPI ignore_body_changes argument is covered separately by TFFR8, because its values are scoped to a single resource’s body and therefore MUST NOT be cascaded to submodules unchanged.
Both variables:
MAY define module-level defaults (e.g., a default error_message_regex such as "ScopeLocked" for resources that race with lock removal, or a default delete = "5m").
MUST allow the consumer to override the defaults β either by supplying a non-null value at the variable level, or by allowing per-field overrides through optional(...) attributes.
MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module.
MUST cascade to applicable submodules β the parent module’s retry and timeouts values MUST be passed through to each submodule it instantiates that directly declares a supported AzAPI resource (see TFRMNFR1). Submodules MAY additionally expose per-item overrides for cases where individual resources need different settings.
variable"retry" {
type = object({
error_message_regex = optional(list(string))
interval_seconds = optional(number)
max_interval_seconds = optional(number)
})
default = nulldescription = <<DESCRIPTIONRetry configuration applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (no custom retry).
- `error_message_regex` - (Optional) A list of regex patterns matching error messages that trigger a retry.
- `interval_seconds` - (Optional) Initial interval between retries in seconds.
- `max_interval_seconds` - (Optional) Maximum interval between retries in seconds.
See <https://registry.terraform.io/providers/Azure/azapi/latest/docs/resources/resource#retry> for full semantics.
DESCRIPTION}
variable"timeouts" {
type = object({
create = optional(string)
read = optional(string)
update = optional(string)
delete = optional(string)
})
default = nulldescription = <<DESCRIPTIONDefault per-operation timeouts applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (provider defaults). Each value is a Go duration string (e.g. `30m`, `1h`).
- `create` - (Optional) Timeout for create operations.
- `read` - (Optional) Timeout for read operations.
- `update` - (Optional) Timeout for update operations.
- `delete` - (Optional) Timeout for delete operations.
DESCRIPTION}
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ } # `retry` is an attribute on `azapi_resource`, so the variable can be
# assigned directly. `timeouts` is a block, so a `dynamic "timeouts"`
# block is required to honor the variable's `null` default.
retry = var.retrydynamic"timeouts" {
for_each = var.timeouts ==null? [] : [var.timeouts]
content {
create = timeouts.value.createread = timeouts.value.readupdate = timeouts.value.updatedelete = timeouts.value.delete }
}
response_export_values = []
}
module"child" {
source = "./modules/child" # Cascade retry and timeouts to the submodule.
retry = var.retrytimeouts = var.timeouts # ...other arguments...
}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the ignore_body_changes argument of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code an inline list that the consumer cannot override, and MUST NOT omit the argument.
To meet this requirement, every applicable module or submodule (see TFRMNFR1) MUST expose a variable named ignore_body_changes.
ignore_body_changes lets a consumer suppress plan diffs for a set of body paths that are mutated outside Terraform (for example tags applied by Azure Policy, or an autoscaler adjusting a capacity property). It is the supported fallback for lifecycle.ignore_changes when the paths must be derived from variables, locals or other non-static values, which lifecycle blocks cannot accept.
Without this variable a consumer has no way to reach the argument, because lifecycle.ignore_changes cannot be applied to a resource from outside the module that declares it. This is exactly the same problem that TFFR7 solves for retry and timeouts.
The module’s Azure/azapi constraint in required_providersMUST allow v2.12.0 or later, which is the release that introduces the argument (see TFFR3).
A consumer supplying a non-empty value MUST be running Terraform 1.11 or later. Modules MUST NOT raise their required_version floor for this reason alone (see TFNFR25); instead they MUST emit null when the list is empty so that consumers on earlier Terraform versions who do not use the feature are unaffected. See Applying the variable.
Important
Because the value is held in provider-private state, a change to ignore_body_changes only takes effect after an apply. A consumer who adds a path will still see the pending diff for that path in the same plan, and a consumer who removes a path will not see the suppressed diff reappear until the next plan. Module documentation SHOULD call this out.
Variable shape
Unlike retry and timeouts, which are resource-agnostic and therefore cascade unchanged, ignore_body_changes values are dot-notation paths into one specific resource’sbody. A path such as properties.addressSpace is meaningful only for the resource that owns it, so passing a parent’s list straight through to a submodule would apply meaningless paths to a different resource.
The variable is therefore scoped per resource and per submodule, using exactly the same shape and key-naming rule as resource_types (TFFR6).
The ignore_body_changes variable MUST:
Be a single object({...}) (not a map(list(string))) so typos at call sites error at plan time and the full override surface is visible in the variable declaration.
Default the variable itself to {} and be nullable = false, per TFNFR20 and TFNFR21.
Declare one optional(list(string), []) field for every AzAPI resource the module itself declares, keyed by the snake_case form of the ARM resource type with the Microsoft. prefix dropped β the identical key used in resource_types (for example Microsoft.Example/widgets β example_widgets).
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource, keyed by that submodule’s primary ARM resource type. The shape of the nested object MUST match that submodule’s own ignore_body_changes variable exactly, and the parent MUST cascade the slot through unchanged.
Document every field in the variable’s description, including what ignore_body_changes does, that paths use dot notation, and that changes take effect only after an apply.
Module owners MAY ship module-level defaults where the resource is known to be mutated outside Terraform. To do so, supply the default inside the optional(list(string), [...]) wrapper. Consumers MUST still be able to override any individual field, and a module-level default MUST NOT be used to work around a bug that belongs in the module body.
Modules MAY additionally expose per-item overrides on the collection variable that drives a for_each submodule, for cases where individual instances need different paths. Where they do, the per-item value MUST take precedence over the shared slot.
Path syntax
Values are dot-notation paths relative to the resource’s body, for example tags or properties.sku.name. Each element MUST be a non-empty string.
Individual list items MUST NOT be targeted (there is no index syntax) β ignore the entire list property instead.
Authors and consumers MUST understand that an ignored path is not merely hidden from the plan: configuration changes at that path are not sent to Azure until the path is removed from the list.
Applying the variable
ignore_body_changes is an attribute (not a block) on azapi_resource, so the relevant field of the variable is assigned directly. The assignment MUST collapse an empty list to null so that the write-only argument is absent when the feature is unused:
ID: TFFR9 - Category: Inputs/Outputs - AzAPI - Tag Propagation
Applicability
This requirement applies independently to every root module and submodule that directly declares a managed AzAPI resource. The avm_azapi_resource_tags_required rule uses its embedded AVM-generated capability snapshot to classify the resource type’s tags property as writable, read-only, or unsupported.
Requirement
For every resource type with a statically writable tags property, the resource MUST expose consumer-settable tags through the standard tags interface and set the tags argument. A direct assignment remains valid for modules that use only the module-wide fallback:
resource"azapi_resource""this" {
type = var.resource_types.example_widgetstags = var.tags}
When the module exposes the optional resource_tags interface, a non-null override for the Terraform resource block label MUST replace var.tags completely. An omitted or null override MUST inherit var.tags, and an empty map MUST remain an intentional empty replacement. The implementation MUST NOT merge the fallback and override maps.
Resource override keys identify Terraform resource block labels, not ARM resource types. Submodule overrides MUST use the deterministic typed resource_tags.modules.<module_label> shape defined by the standard tags interface. The separate resources and modules namespaces MUST resolve identical resource and module labels without ambiguity.
For every resource type with a statically read-only or unsupported tags property, the resource MUST NOT set a tags argument. Do not use a conditional, dynamic value, or an empty map to force tags onto these types.
The validation skips dynamic or otherwise unevaluable type expressions to avoid false positives. Authors SHOULD keep resource types statically resolvable through var.resource_types as required by TFFR6.
The embedded AVM-generated capability snapshot, rather than a hand-maintained module allowlist or an AzAPI import, is the authority for this classification.
ID: TFNFR14 - Category: Inputs - Not allowed variables
Since Terraform 0.13, count, for_each and depends_on are introduced for modules, module development is significantly simplified. Module’s owners MUST NOT add variables like enabled or module_depends_on to control the entire module’s operation. Boolean feature toggles are acceptable however.
ID: TFNFR38 - Category: Inputs/Outputs - Resource ID Variable Validation
Every input variable (or nested attribute) that holds an Azure ARM resource ID MUST be validated using the AzAPI provider-defined function provider::azapi::parse_resource_id, called with a literal string naming the expected resource type, and wrapped in can(...).
Hand-rolled regex, startswith, length, or split checks MUST NOT be used to validate resource IDs. The provider function knows the canonical ARM ID grammar for every resource type, is fixed in lockstep with the provider, and produces a single consistent error model β including for IDs whose grammar contains anomalies (such as classic resources, extension resources, or scope-based IDs).
This rule covers, but is not limited to:
Top-level scope variables such as parent_id (see TFRMFR1).
Variables that reference other Azure resources by ID (e.g. subnet_resource_id, key_vault_resource_id, workspace_resource_id, private_dns_zone_resource_ids, user_assigned_resource_ids).
Nested attributes inside object, map(object), set(object), or list(object) types that hold resource IDs.
Rules
The resource type passed to parse_resource_idMUST be a literal string (e.g. "Microsoft.Network/virtualNetworks/subnets"). It MUST NOT be a reference to another variable, local, or expression. This keeps each validation block self-contained and avoids requiring cross-variable validation.
For optional / nullable variables, the validation MUST short-circuit on null (e.g. var.x == null || can(provider::azapi::parse_resource_id("...", var.x))) so that callers omitting the value do not trip validation.
For collection-valued variables (set(string), list(string), map(string)), the validation MUST iterate the collection with alltrue([for v in ... : can(...)]).
For nested attributes within object types, the validation MUST iterate the parent collection (or reference the object directly) and validate each nested resource ID, again handling null for optional nested attributes.
Where a variable can legitimately hold IDs of more than one resource type (rare β e.g. marketplace_partner_resource_id in the diagnostic-settings interface), this rule does not apply and the variable SHOULD be left without resource-ID validation rather than validated against a single arbitrary type.
Examples
A required, single-value resource ID:
variable"key_vault_resource_id" {
type = stringnullable = falsevalidation {
condition = can(provider::azapi::parse_resource_id("Microsoft.KeyVault/vaults", var.key_vault_resource_id))
error_message = "`key_vault_resource_id` must be a valid Azure Key Vault resource ID." }
description = "The resource ID of the Key Vault that holds the customer-managed key."}
An optional, single-value resource ID:
variable"workspace_resource_id" {
type = stringdefault = nullnullable = truevalidation {
condition = var.workspace_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.OperationalInsights/workspaces", var.workspace_resource_id))
error_message = "`workspace_resource_id` must be a valid Log Analytics workspace resource ID, or `null`." }
description = "The resource ID of the Log Analytics workspace to send diagnostics to."}
A collection of resource IDs:
variable"user_assigned_resource_ids" {
type = set(string)
default = []
nullable = falsevalidation {
condition = alltrue([
foridin var.user_assigned_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", id))
])
error_message = "Each entry in `user_assigned_resource_ids` must be a valid user-assigned managed identity resource ID." }
description = "A set of user-assigned managed identity resource IDs to attach to the resource."}
A nested resource ID inside a map(object(...)):
variable"private_endpoints" {
type = map(object({
subnet_resource_id = stringprivate_dns_zone_resource_ids = optional(set(string), []) # ...other attributes...
}))
default = {}
nullable = falsevalidation {
condition = alltrue([
for_, vin var.private_endpoints: can(provider::azapi::parse_resource_id("Microsoft.Network/virtualNetworks/subnets", v.subnet_resource_id))
])
error_message = "Each `private_endpoints[*].subnet_resource_id` must be a valid subnet resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
foridinv.private_dns_zone_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.Network/privateDnsZones", id))
]
]))
error_message = "Each entry in `private_endpoints[*].private_dns_zone_resource_ids` must be a valid private DNS zone resource ID." }
}
Notes
The rule applies regardless of whether the resource ID is required or optional, single-valued or collection-valued, top-level or nested.
parse_resource_id errors when (a) the input is not a well-formed ARM ID, or (b) the input does not parse as the supplied resource type. Wrapping in can(...) converts both failure modes into a single boolean suitable for a validation block’s condition.
This rule supersedes any older guidance suggesting startswith(var.x, "/") or hand-written regex for resource ID validation.
ID: TFRMFR1 - Category: Inputs/Outputs - Resource Module Parent ID
A Terraform resource module MUST expose its parent scope to consumers as a single string variable named parent_id, and MUST assign that variable to the parent_id argument of every primary azapi_resource (or equivalent AzAPI resource) it manages.
parent_id is the AzAPI provider’s universal way of expressing where a resource lives in the Azure Resource Manager hierarchy. Depending on the resource type, it can be:
A subscription ID (e.g. /subscriptions/{subscriptionId}) β for tenant- or subscription-scoped resources.
A management group ID (e.g. /providers/Microsoft.Management/managementGroups/{name}) β for management-group-scoped resources.
A resource group ID (e.g. /subscriptions/{subscriptionId}/resourceGroups/{rgName}) β for the most common case of resources that live inside a resource group.
The resource ID of a parent ARM resource (e.g. the ID of a virtual network for subnets, the ID of a storage account for blob containers) β for child / nested resources.
Because the same variable describes every possible parent scope, modules MUST NOT expose resource_group_name, resource_group_resource_id, or any other parent-scope-specific variable. The fully-qualified ARM ID supplied via parent_id is sufficient and works uniformly for every kind of Azure resource.
parent_idMUST be validated using the AzAPI provider’s provider-defined functions, per TFNFR38. The required function is provider::azapi::parse_resource_id, called with the expected parent resource type for the module’s primary resource (for example Microsoft.Resources/resourceGroups for resources that live inside a resource group, or Microsoft.Network/virtualNetworks for a subnet module). Hand-rolled regex, startswith, or length checks MUST NOT be used.
This rule supersedes the Terraform clause of RMFR3 (which historically required a resource_group_name variable in Terraform). RMFR3 still applies to Bicep modules; for AVM Terraform modules the rules in this spec take precedence.
Variable declaration
variable"parent_id" {
type = stringnullable = falsevalidation { # Validate via the AzAPI provider's `parse_resource_id` function. The function
# errors if `parent_id` is malformed OR if it does not parse as the expected
# parent resource type (e.g. passing a subscription ID where a resource group
# is required). Replace `Microsoft.Resources/resourceGroups` with the parent
# resource type expected by this module's primary resource (for example
# `Microsoft.Network/virtualNetworks` for a subnet module).
condition = can(provider::azapi::parse_resource_id("Microsoft.Resources/resourceGroups", var.parent_id))
error_message = "`parent_id` must be a valid Azure resource group resource ID." }
description = <<DESCRIPTIONThe fully-qualified ARM resource ID of the scope into which the resource managed by this module will be deployed. Examples:
- Subscription scope: `/subscriptions/00000000-0000-0000-0000-000000000000`
- Management group scope: `/providers/Microsoft.Management/managementGroups/example-mg`
- Resource group scope: `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg`
- Parent resource scope: `/subscriptions/.../resourceGroups/example-rg/providers/Microsoft.Network/virtualNetworks/example-vnet`
This module **does not** create the parent scope. The consumer (or composing pattern module) is responsible for providing a `parent_id` for an existing scope.
DESCRIPTION}
The resource type passed to parse_resource_idMUST be a literal string naming the expected parent resource type for the module’s primary resource (e.g. "Microsoft.Resources/resourceGroups" for a resource that lives inside a resource group, or "Microsoft.Network/virtualNetworks" for a subnet module). It MUST NOT be a reference to another variable. This keeps the validation block self-contained.
Modules MUST NOT accept resource_group_name, resource_group_resource_id, or any other parent-scope-specific variable. If a module needs to be told which resource group (or subscription, or management group) to deploy into, it does so exclusively via parent_id.
Modules MUST NOT create the parent scope themselves (see RMFR3 for the resource-group case). The consumer or composing pattern module supplies an existing scope’s ARM ID.
Submodules (per TFRMNFR1) MUST also expose parent_id and follow the same rules. The parent module typically passes its own primary resource’s ID to each child, e.g. parent_id = azapi_resource.this.id.
Modules MAY expose additional, narrower scope variables only when a single resource genuinely needs two different parent scopes (rare). In that case the additional variable MUST still be a parent_id-shaped string (fully-qualified ARM ID), validated with the same provider-defined function pattern, and MUST NOT be named after a specific scope kind such as resource_group_name.
Exception β extension-resource modules
A small class of resource modules manages an Azure extension resource (a resource type that attaches to any parent ARM resource, regardless of its provider). Examples include modules whose primary resource is Microsoft.Authorization/locks, Microsoft.Authorization/roleAssignments, Microsoft.Insights/diagnosticSettings, Microsoft.Resources/tags, or similar. For these modules, the parent resource type is intentionally polymorphic and a literal parse_resource_id("Microsoft.X/y", var.parent_id) validation MUST NOT be used.
Where this exception applies, the module MUST still:
Expose the parent scope as the variable named parent_id (no other name), of type string, required, and nullable = false.
Validate that parent_id is a non-empty fully-qualified ARM ID using a generic check, e.g.:
validation {
condition = length(var.parent_id) >0&& (startswith(var.parent_id, "/subscriptions/") ||startswith(var.parent_id, "/providers/"))
error_message = "`parent_id` must be a fully-qualified ARM resource ID starting with `/subscriptions/` or `/providers/`."}
Document in the variable’s description that any ARM resource ID is accepted because the module manages an extension resource.
Document the exception in the module’s README.md so reviewers immediately understand why the standard parse_resource_id validation is absent.
Testing
The content below is listed based on the following tags
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
Module owners MUST test that child and extension resources and those Bicep or Terreform interface resources that are supported by their modules, are validated in E2E tests as per SNFR2 to ensure they deploy and are configured correctly.
These MAY be tested in a separate E2E test and DO NOT have to be tested in each E2E test.
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
Where descriptions for variables and outputs spans multiple lines. The description MAY provide variable input examples for each variable using the HEREDOC format and embedded markdown.
Example:
variable"my_complex_input" {
type = map(object({
param1 = stringparam2 = optional(number, null)
}))
description = <<DESCRIPTION A complex input variable that is a map of objects.
Each object has two attributes:
- `param1`: A required string parameter.
- `param2`: (Optional) An optional number parameter.
Example Input:
```terraform
my_complex_input = {
"object1" = {
param1 = "value1"
param2 = 2
}
"object2" = {
param1 = "value2"
}
}
```
DESCRIPTION }
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
Terraform Utility Module Specifications
Contribution / Support
The content below is listed based on the following tags
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
Module owners MUST set a branch protection policy on their GitHub Repositories for AVM modules against their default branch, typically main, to do the following:
Requires a Pull Request before merging
Require approval of the most recent reviewable push
Dismiss stale pull request approvals when new commits are pushed
Require linear history
Prevents force pushes
Not allow deletions
Require CODEOWNERS review
Do not allow bypassing the above settings
Above settings MUST also be enforced to administrators
Tip
If you use the template repository as mentioned in the contribution guide, the above will automatically be set.
Telemetry
The content below is listed based on the following tags
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
Terraform
Currently, no further requirements apply.
Naming / Composition
The content below is listed based on the following tags
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
Utility Modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Example: avm/utl/general/get-environment or avm/utl/types/avm-common-types
Segments:
utl defines this as a utility module
<hyphenated grouping/category name> is a hierarchical grouping of utility modules by category, with each word separated by dashes, such as: general or types
<hyphenated utility module name> is a term describing the module’s function, with each word separated by dashes, e.g., get-environment = to get environmental details; avm-common-types = to use common types.
Terraform Utility Module Naming
Naming convention:
avm-utl-<utility module name> (Module name for registry)
terraform-<provider>-avm-utl-<utility module name> (GitHub repository name to meet registry naming requirements)
Example: avm-utl-sku-finder or avm-utl-naming
Segments:
<provider> is a legacy requirement of the Terraform registry. For AVM Terraform utility modules this MUST be set to azure (for example Azure/avm-utl-naming/azure). Older utility modules may still use the azurerm or azuread segments. These segments are names only and do not permit use of the AzureRM provider; TFFR3 still requires every module to be built with AzAPI.
utl defines this as a utility module
<utility module name> is a term describing the module’s function, e.g., sku-finder = to find available SKUs; naming = to handle naming conventions.
Module owners MAY cross-references other modules to build either Resource or Pattern modules. However, they MUST be referenced only by a HashiCorp Terraform registry reference to a pinned version e.g.,
Every new AVM Terraform module β resource, pattern, or utility β MUST use Azure/azapi for every Azure control-plane resource and every data-plane operation supported by AzAPI. The AzureRM provider is permitted only for the unsupported data-plane/non-ARM API exception defined below.
Authors MUST only use the following Azure providers, and versions, in their modules:
provider
min version
max version
permitted use
Azure/azapi
>= 2.12
< 3.0
All Azure control-plane resources and supported data-plane operations
hashicorp/azurerm
>= 4.0
< 5.0
Only a specific unsupported data-plane/non-ARM API operation under the exception below
Pattern modules MAY also use other Microsoft-maintained providers when required by the pattern. Examples include integrations/github, microsoft/azuredevops, microsoft/fabric, and microsoft/msgraph. Each provider MUST be declared with minimum and maximum major version constraints as required by TFNFR26.
Resource and utility modules MUST NOT use these additional providers. Except for the narrow AzureRM exception below, third-party providers MUST NOT be used by any AVM Terraform module, regardless of module classification.
Note
The AzAPI floor is 2.12 because TFFR8 requires every module to expose the ignore_body_changes argument, which was introduced in Azure/azapi v2.12.0. Modules pinned below that version will fail to plan because the argument is absent from the provider schema.
This prohibition applies to every Terraform configuration shipped with the module, including:
The root module and all submodules.
Every configuration under examples/, including examples executed as end-to-end tests.
Terraform tests, test fixtures, and supporting setup configurations.
Terraform snippets in _header.md, _footer.md, generated documentation, and other repository documentation.
Supporting control-plane resources needed by an example, end-to-end test, or fixture MUST use AzAPI. AzureRM MUST NOT be used for resource groups, role assignments, monitoring resources, networking, or any other ARM control-plane resource.
Exception β unsupported data-plane/non-ARM API operations
An AVM Terraform module that is otherwise built with AzAPI MAY declare the AzureRM provider only for a specific data-plane or non-ARM API operation whose functionality is genuinely unavailable through azapi_data_plane_resource, azapi_resource, azapi_resource_action, or azapi_update_resource. This exception is intended for isolated operations such as a data-plane resource whose AzureRM implementation calls a service endpoint rather than Azure Resource Manager. It is not a general fallback for a missing or inconvenient AzAPI schema. Every azurerm_* block MUST independently satisfy this exception; one permitted block does not authorize any other AzureRM use.
Where this exception applies, the module MUST:
Continue to declare and use AzAPI as its required, primary Azure provider.
Scope every azurerm_* resource or data source to the exact unsupported data-plane/non-ARM operation.
Pin the AzureRM provider to ~> 4.0 in required_providers.
Use AzAPI for every control-plane resource and every data-plane operation that AzAPI supports.
Document the exception in the module’s README.md, including each azurerm_* block, the data-plane/non-ARM API it wraps, why AzAPI cannot implement it, and the upstream AzAPI issue or pull request tracking support.
Replace the azurerm_* block with AzAPI in the next module release after the required capability ships.
Examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets MAY configure or exercise AzureRM only when required by that exact permitted data-plane operation. All supporting control-plane resources in those surfaces MUST use AzAPI.
This exception MUST NOT be used to:
Implement any ARM control-plane resource.
Avoid AzAPI because its body schema is more verbose or less convenient.
Avoid raising an AzAPI capability gap for an unsupported control-plane operation.
Side-step any AzAPI-specific specification that applies to the module’s AzAPI resources.
The azurerm remote state backend and the final segment of a published Terraform Registry module address, such as /azurerm in an existing AVM module source, are names and are not provider declarations. They MAY appear where required for state storage or to reference an existing published AVM module. A dependency’s provider implementation is governed by that dependency’s own repository; its Registry address does not by itself justify a direct hashicorp/azurerm declaration or azurerm_* block in the consuming module repository. Any such direct use MUST independently satisfy the data-plane exception above.
Authors MUST use the required_providers block in their module to enforce the provider versions.
Authors MUST specify the response_export_values argument when using the AzAPI provider:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US"response_export_values = [] # must be specified, even if empty
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
If you require read-only properties to be returned from the resource, you SHOULD include them as follows:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US" # Example as a list:
response_export_values = ["properties.readOnlyProperty"] # Example as a map:
# response_export_values = {
# read_only_property = "properties.readOnlyProperty"
# }
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
output"read_only_property" { # Example if response_export_values is a list:
value = azapi_resource.example.output.properties.readOnlyProperty # Example if response_export_values is a map:
# value = azapi_resource.example.output.read_only_property
}
Authors MUST omit replace_triggers_refs when no body properties require replacement. When one or more body properties require replacement, authors MUST set replace_triggers_refs to a non-empty static list of JMESPath expressions that identify those paths.
Each expression MUST be valid JMESPath syntax, non-blank, and unique within the list. Do not include name or location, as AzAPI already replaces the resource when either changes. When the resource body is statically evaluable, every declared expression MUST resolve against that body.
This is to ensure that changes to properties that require replacement of the resource are handled correctly by Terraform. Authors remain responsible for identifying every property that actually requires replacement. Current Bicep-generated schemas do not reliably preserve whether a property is create-only or updateable, so the rule validates declared paths but cannot prove that the list is semantically complete.
We can use count and for_each to deploy multiple resources, but using count with an ordered collection can create an index anti-pattern where removing one item unexpectedly changes other resource addresses.
You can use count to create some kind of resources under certain conditions, for example:
The module’s owners MUST use map(xxx) or set(xxx) as resource’s for_each collection, the map’s key or set’s element MUST be static literals.
Good example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_map // `map(string)`, when user call this module, it could be: `{ "subnet0": "subnet0" }`, or `{ "subnet0": azapi_resource.subnet0.name }`
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
Bad example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_name_set // `set(string)`, when user use `toset([azapi_resource.subnet0.name])`, it would cause an error.
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
There are 3 types of assignment statements in a resource or data block: argument, meta-argument and nested block. The argument assignment statement is a parameter followed by =:
location = azapi_resource.example.location
or:
tags = {
environment = "Production"}
Nested block is a assignment statement of parameter followed by {} block:
subnet {
name = "subnet1"address_prefix = "10.0.1.0/24"}
Meta-arguments are assignment statements can be declared by all resource or data blocks. They are:
count
depends_on
for_each
lifecycle
provider
The order of declarations within resource or data blocks is:
All the meta-arguments SHOULD be declared on the top of resource or data blocks in the following order:
provider
count
for_each
Then followed by:
required arguments
optional arguments
required nested blocks
optional nested blocks
All ranked in alphabetical order.
These meta-arguments SHOULD be declared at the bottom of a resource block with the following order:
depends_on
lifecycle
The parameters of lifecycle block SHOULD show up in the following order:
create_before_destroy
ignore_changes
prevent_destroy
parameters under depends_on and ignore_changes are ranked in alphabetical order.
Meta-arguments, arguments and nested blocked are separated by blank lines.
dynamic nested blocks are ranked by the name comes after dynamic, for example:
Sometimes we need to ensure that the resources created are compliant to some rules at a minimum extent, for example a subnet has to be connected to at least one network_security_group. The user SHOULD pass in a security_group_id and ask us to make a connection to an existing security_group, or want us to create a new security group.
The disadvantage of this approach is if the user create a security group directly in the root module and use the id as a variable of the module, the expression which determines the value of count will contain an attribute from another resource, the value of this very attribute is “known after apply” at plan stage. Terraform core will not be able to get an exact plan of deployment during the “plan” stage.
For this kind of parameters, wrapping with object type is RECOMMENDED:
variable"security_group" {
type:object({
id = string })
default = null}
The advantage of doing so is encapsulating the value which is “known after apply” in an object, and the object itself can be easily found out if it’s null or not. Since the id of a resource cannot be null, this approach can avoid the situation we are facing in the first example, like the following:
variable used as feature switches SHOULD apply a positive statement, use xxx_enabled instead of xxx_disabled. Avoid double negatives like !xxx_disabled.
Please use xxx_enabled instead of xxx_disabled as name of a variable.
ID: TFNFR17 - Category: Code Style - Variables with Descriptions
The target audience of description is the module users.
For a newly created variable (Eg. variable for switching dynamic block on-off), it’s descriptionSHOULD precisely describe the input parameter’s purpose and the expected data type. descriptionSHOULD NOT contain any information for module developers, this kind of information can only exist in code comments.
For object type variable, description can be composed in HEREDOC format:
variable"kubernetes_cluster_key_management_service" {
type:object({
key_vault_key_id = stringkey_vault_network_access = optional(string)
})
default = nulldescription = <<DESCRIPTION- `key_vault_key_id` - (Required) Identifier of Azure Key Vault key. See [key identifier format](https://learn.microsoft.com/en-us/azure/key-vault/general/about-keys-secrets-certificates#vault-name-and-object-name) for more details. When Azure Key Vault key management service is enabled, this field is required and must be a valid key identifier. When `enabled` is `false`, leave the field empty.
- `key_vault_network_access` - (Optional) Network access of the key vault Network access of key vault. The possible values are `Public` and `Private`. `Public` means the key vault allows public access from all networks. `Private` means the key vault disables public access and enables private link. Defaults to `Public`.
DESCRIPTION}
You MUST remove all trailing whitespace so that terraform-docs renders the readme properly.
ID: TFNFR19 - Category: Code Style - Sensitive Data Variables
If variable’s type is object and contains one or more fields that would be assigned to a sensitive argument, then this whole variableSHOULD be declared as sensitive = true, otherwise you SHOULD extract sensitive field into separated variable block with sensitive = true.
Nullable SHOULD be set to false for collection values (e.g. sets, maps, lists) when using them in loops. However for scalar values like string and number, a null value MAY have a semantic meaning and as such these values are allowed.
MAPOTF removes redundant explicit nullable = true. That formatting cleanup does not change this requirement and does not imply that a collection is semantically safe to make nullable.
nullable = trueMUST be avoided. MAPOTF removes redundant explicit nullable = true; this cleanup is distinct from, and does not satisfy, the requirement to set nullable = false where a meaningful zero value exists.
Variables MUST be declared with nullable = false whenever the variable’s type has a meaningful zero value ({} for objects/maps, [] for lists/sets, "" for strings where empty has the same meaning as absent, etc.). Consumers should signal “no value” by omitting the input, not by explicitly passing null.
Exception β behavior-toggle inputs
A small, well-defined class of inputs MAY keep the implicit nullable = true (i.e. default = null) where null carries a distinct semantic meaning of “no override β use the underlying provider/AVM defaults”, and where representing that state with the type’s zero value would be ambiguous or wrong. Examples include:
var.retry and var.timeouts (per TFFR7) β null means “do not emit a retry/timeouts block; use the AzAPI provider defaults”.
var.lock (per the AVM lock interface) β null means “do not create a management lock”.
Optional sub-objects that toggle whole feature blocks on/off, where {} would be indistinguishable from “feature enabled with all defaults”.
Where this exception applies, the variable MUST:
Use default = null (the implicit nullable = true is permitted only for this purpose).
State explicitly in its description what null means.
Be consumed with a null-aware pattern (e.g. count = var.lock != null ? 1 : 0, or dynamic "timeouts" { for_each = var.timeouts == null ? [] : [var.timeouts] }).
This exception does not extend to required inputs, to collection-shaped inputs (TFNFR20), or to nested attributes inside an object β those MUST use nullable = false and the type’s zero value.
variable"example_map" {
type =map(string)
default = {}
description ="An example map variable with an empty default value." sensitive =true}
Bad example:
variable"example_string" {
type =string default ="sensitive_value" description ="An example string variable with a sensitive default value." sensitive =true}
Sometimes we will find names for some variable are not suitable anymore, or a change SHOULD be made to the data type. We want to ensure forward compatibility within a major version, so direct changes are strictly forbidden. The right way to do this is move this variable to an independent deprecated_variables.tf file, then redefine the new parameter in variable.tf and make sure it’s compatible everywhere else.
Deprecated variableMUST be annotated as DEPRECATED at the beginning of the description, at the same time the replacement’s name SHOULD be declared. E.g.,
variable"enable_network_security_group" {
type = stringdefault = nulldescription = "DEPRECATED, use `network_security_group_enabled` instead; Whether to generate a network security group and assign it to the subnet. Changing this forces a new resource to be created."}
A cleanup of deprecated_variables.tfSHOULD be performed during a major version release.
The terraform.tf file MUST only contain one terraform block.
The first line of the terraform block MUST define a required_version property for the Terraform CLI. The standard Terraform TFLint plugin validates the requirement; MAPOTF keeps it first.
The required_version property MUST include a constraint on the minimum version of the Terraform CLI. Previous releases of the Terraform CLI can have unexpected behavior.
The required_version property MUST include a constraint on the maximum major version of the Terraform CLI. Major version releases of the Terraform CLI can introduce breaking changes and MUST be tested.
The required_version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
ID: TFNFR26 - Category: Code Style - Providers in required_providers
The terraform block in terraform.tfMUST contain the required_providers block.
Each provider used directly in the module MUST be specified with the source and version properties. The standard Terraform TFLint plugin validates the used-provider source and version requirements. MAPOTF sorts the required_providers entries alphabetically.
Do not add providers to the required_providers block that are not directly required by this module. If submodules are used then each submodule SHOULD declare its requirements in its own terraform.tf file.
The source property MUST be in the format of namespace/name. If this is not explicitly specified, it can cause failure.
The version property MUST include a constraint on the minimum version of the provider. Older provider versions may not work as expected.
The version property MUST include a constraint on the maximum major version. A provider major version release may introduce breaking change, so updates to the major version constraint for a provider MUST be tested.
The version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
By rule, every published AVM module and submodule MUST NOT declare a provider block. Provider configuration belongs exclusively to the consuming root module.
When a module requires an alternate provider instance, it MUST declare that alias through configuration_aliases in terraform.required_providers and the consumer MUST pass the configured alias through the module’s providers map. A provider block containing only alias is not permitted in an AVM module.
Sometimes we notice that the name of certain output is not appropriate anymore, however, since we have to ensure forward compatibility in the same major version, its name MUST NOT be changed directly. It MUST be moved to an independent deprecated_outputs.tf file, then redefine a new output in output.tf and make sure it’s compatible everywhere else in the module.
A cleanup SHOULD be performed to deprecated_outputs.tf and other logics related to compatibility during a major version upgrade.
ID: TFNFR31 - Category: Code Style - locals.tf for Locals Only
In locals.tf, file we could declare multiple locals blocks, but only locals blocks are allowed.
You MAY declare locals blocks next to a resource block or data block for some advanced scenarios, like making a fake module to execute some light-weight tests aimed at the expressions.
This specification applies only to existing legacy modules that still use AzureRM while they are being migrated. It does not apply to a new module that uses AzureRM solely for the narrow unsupported data-plane/non-ARM API exception in TFFR3, because that exception does not permit AzureRM resource-group management.
In a legacy AzureRM module, the prevent_deletion_if_contains_resources provider setting SHOULD be set to false until the module is migrated. Azure Policy remediation can add resources during a test run, and the provider’s default behavior can then prevent cleanup of the test resource group.
newres is a command-line tool that generates Terraform configuration files for a specified resource type. It automates the process of creating variables.tf and main.tf files, making it easier to get started with Terraform and reducing the time spent on manual configuration.
Module owners MAY use newres when they’re trying to add new resource block, attribute, or nested block. They MAY generate the whole block along with the corresponding variable blocks in an empty folder, then copy-paste the parts they need with essential refactoring.
ID: TFNFR39 - Category: Code Style - Standard File Layout
Every Terraform AVM module (root module and every submodule) MUST organize its top-level Terraform code into the following files at the module’s root directory:
File
Required
Contents
terraform.tf
MUST
The single terraform { β¦ } block β required_version, required_providers, and any backend configuration (root module only). Provider configuration blocks MUST NOT appear here.
variables.tf
MUST
All variable blocks for the module. MAY be split into additional variables.<topic>.tf files (see below).
outputs.tf
MUST
All output blocks for the module. MAY be split into additional outputs.<topic>.tf files (see below).
main.tf
MUST
The module’s primary resource, data, and module blocks. MAY be split into additional main.<topic>.tf files (see below).
locals.tf
SHOULD
All locals blocks. Required if the module declares any locals. MAY be split into additional locals.<topic>.tf files (see below). MAY be omitted only when the module has no locals at all.
Splitting and naming additional files
For larger modules the contents of main.tf, variables.tf, outputs.tf, and locals.tfMAY each be split into multiple files along logical / topic lines. When this is done:
Additional Terraform files MUST use the canonical filename (main, variables, outputs, or locals) as the prefix, followed by a ., a short descriptive topic name, and the .tf extension β for example main.diagnostic_settings.tf, variables.diagnostic_settings.tf, outputs.diagnostic_settings.tf, locals.diagnostic_settings.tf.
The same topic name SHOULD be used across the four file types when they describe the same logical concern, so that (for example) main.private_endpoints.tf, variables.private_endpoints.tf, outputs.private_endpoints.tf, and locals.private_endpoints.tf all relate to the same feature.
Each split file MUST contain only the block kind matching its prefix:
main.<topic>.tf β only resource, data, and module blocks.
variables.<topic>.tf β only variable blocks.
outputs.<topic>.tf β only output blocks.
locals.<topic>.tf β only locals blocks.
The terraform { β¦ } block MUST appear exactly once per module, in terraform.tf. It MUST NOT be split.
Files that MUST NOT appear at the module root
A providers.tf file β provider requirements belong in terraform.tf; provider configurations belong only in the consumer’s root module, never in an AVM module (per SFR2).
A single monolithic module.tf or everything.tf β the canonical filenames above MUST be used.
Rationale
Standardizing file layout means that any reviewer or consumer can find a module’s interface (variables.tf, outputs.tf), provider constraints (terraform.tf), and primary logic (main.tf / main.<topic>.tf) in the same place across every AVM Terraform module, without having to grep. It also makes the cascade rules in TFFR6, TFFR7, and TFRMNFR1 reviewable at a glance.
Submodules (per TFRMNFR1) follow the same layout in their own root directory under modules/<subresource>/. The submodule’s terraform.tfMUST declare the same set of required_providers it actually consumes.
Auto-generated documentation files (README.md, _header.md, _footer.md) and tooling configuration files (.terraform-docs.yml, .tflint.hcl, etc.) are out of scope of this rule and follow their own specs.
Structured values that are passed as JSON or YAML MUST be constructed with jsonencode or yamlencode, rather than a literal JSON or YAML heredoc. Native HCL objects, lists, conditionals, and for expressions keep the structure reviewable and let Terraform perform correct escaping.
Terraform interpolation (${...}), template directives (%{...}), unknown values, and dynamically generated lists or maps are not exceptions: construct the native HCL value and pass it to the encoder.
A heredoc MAY be used only when the value is not JSON or YAML, or when the receiving system requires opaque source text for a downstream templating engine or syntax that jsonencode or yamlencode cannot represent without changing its meaning. The heredoc must not use Terraform interpolation to assemble JSON or YAML in that case, and its reason must be clear from the surrounding configuration.
ID: TFNFR41 - Category: Code Style - Output Definition Order
output blocks in a module SHOULD be ordered alphabetically by output name. This applies to outputs.tf and every outputs.<topic>.tf file in the root module and each submodule.
output"id" {
value = azapi_resource.this.id}
output"name" {
value = azapi_resource.this.name}
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
Authors SHOULD NOT output entire resource objects as these may contain sensitive outputs and the schema can change with API or provider versions. Instead, authors SHOULD output the computed attributes of the resource as discreet outputs. This kind of pattern protects against provider schema changes and is known as an anti-corruption layer.
Remember, you SHOULD NOT output values that are already inputs (other than name).
E.g.,
# Resource output, computed attribute.
output"foo" {
description = "MyResource foo attribute"value = azapi_resource.myresource.output.properties.foo}# Resource output for resources that are deployed using `for_each`. Again only computed attributes.
output"childresource_foos" {
description = "MyResource children's foo attributes"value = {
forkey, valueinazapi_resource.mychildresource:key => value.output.properties.foo }
}# Output of a sensitive attribute
output"bar" {
description = "MyResource bar attribute"value = azapi_resource.myresource.output.properties.barsensitive = true}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, authors MUST NOT hard-code the type argument of a supported AzAPI resource inline.
Instead, every AzAPI resource type string used by the module MUST be sourced from a single object variable named resource_types.
resource_types keys vs Terraform resource labels
These are two unrelated concepts and the spec treats them independently:
Keys in var.resource_types name the AzAPI resource type and are derived from the ARM type by the naming rule below. They appear on the right of an assignment as the value of the type argument.
Terraform resource labels (e.g. azapi_resource.this) name the graph node and govern how the resource is referenced elsewhere in HCL. The primary resource label MUST be this, per TFRMNFR2.
A typical primary-resource declaration therefore reads:
resource"azapi_resource""this" { # label per TFRMNFR2
type = var.resource_types.example_widgets # key per the naming rule below
# ...
}
this and example_widgets describe different things and are derived by different rules. They MUST NOT be made to coincide β this is never a valid resource_types key.
Key naming
Each resource_types key (at every level of nesting) MUST be the snake_case form of the ARM resource type, with the Microsoft. prefix dropped:
Drop the Microsoft. prefix.
Render the provider namespace as a single lowercase token β do not split internal camelCase (KeyVault β keyvault, DocumentDB β documentdb, EventHub β eventhub).
Convert each resource path segment after the provider from camelCase to snake_case (virtualNetworks β virtual_networks, roleAssignments β role_assignments).
Join the provider token and each path segment with _.
ARM type
Key
Microsoft.Example/widgets
example_widgets
Microsoft.Example/widgets/parts
example_widgets_parts
Microsoft.Example/widgets/parts/components
example_widgets_parts_components
Microsoft.Authorization/locks
authorization_locks
Microsoft.Authorization/roleAssignments
authorization_role_assignments
Microsoft.Insights/diagnosticSettings
insights_diagnostic_settings
Microsoft.KeyVault/vaults/secrets
keyvault_vaults_secrets
Microsoft.Network/virtualNetworks/subnets
network_virtual_networks_subnets
The rule is deterministic so consumers, lint checks and tooling can derive the expected key for any ARM type without consulting the module source. Authors MUST NOT invent shorter aliases (e.g. widgets instead of example_widgets).
Variable shape
The resource_types variable MUST:
Be a single object({...}) (not a map(string)) so typos at call sites error at plan time and per-key defaults are visible in the variable declaration.
Default the variable itself to {} so consumers only need to supply the keys they wish to override.
Be nullable = false.
Declare one optional(string, "<provider>/<resource>@<api-version>") field for every AzAPI resource the module itself declares, defaulting each to the latest API version the module has been tested against. The default MUST be a stable (non-preview) API version unless the module’s primary resource only ships a preview API.
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource and therefore exposes its own resource_types variable (see TFRMNFR1). The shape of the nested object MUST match that submodule’s own resource_types variable exactly. The parent MUST NOT repeat the submodule’s defaults β the inner string attributes are declared as optional(string) (no default) so the submodule remains the single source of truth for its own tested API versions.
Document every field in the variable’s description.
Cascading to submodules
Because the nested slot in the parent mirrors the submodule’s variable, the parent cascades the slot through unchanged:
No renaming, repacking, or null filtering is required. When the consumer omits a key or sets it explicitly to null, Terraform substitutes the default declared on the owning module’s variable (per Terraform’s optional-attribute semantics).
The rationale for the variable is to let consumers:
Target sovereign clouds (e.g., Azure US Government, Azure China) where older API versions may be the latest available.
Opt into a newer preview API version without waiting for a module release.
Pin a specific API version for compliance or reproducibility reasons.
Nesting submodule slots inside the parent’s resource_types (rather than flattening every AzAPI resource into a single top-level namespace):
Keeps each module’s defaults co-located with the resource it owns.
Lets a submodule add or rename its own resources without forcing a breaking change on parent-module consumers who never touched those keys.
Makes the override surface mirror the actual module tree β a consumer looking at the parent’s variable can see, in shape, every resource managed beneath it.
Example β root, child and grandchild
A module managing Microsoft.Example/widgets, with a parts submodule for Microsoft.Example/widgets/parts, which in turn instantiates a component sibling submodule for Microsoft.Example/widgets/parts/components (per TFRMNFR1):
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the retry and timeouts blocks of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code values inline that the consumer cannot override.
To meet this requirement, the module MUST expose two variables:
retry β an object variable controlling the AzAPI retry block.
timeouts β an object variable controlling the AzAPI timeouts block.
Diff suppression via the AzAPI ignore_body_changes argument is covered separately by TFFR8, because its values are scoped to a single resource’s body and therefore MUST NOT be cascaded to submodules unchanged.
Both variables:
MAY define module-level defaults (e.g., a default error_message_regex such as "ScopeLocked" for resources that race with lock removal, or a default delete = "5m").
MUST allow the consumer to override the defaults β either by supplying a non-null value at the variable level, or by allowing per-field overrides through optional(...) attributes.
MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module.
MUST cascade to applicable submodules β the parent module’s retry and timeouts values MUST be passed through to each submodule it instantiates that directly declares a supported AzAPI resource (see TFRMNFR1). Submodules MAY additionally expose per-item overrides for cases where individual resources need different settings.
variable"retry" {
type = object({
error_message_regex = optional(list(string))
interval_seconds = optional(number)
max_interval_seconds = optional(number)
})
default = nulldescription = <<DESCRIPTIONRetry configuration applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (no custom retry).
- `error_message_regex` - (Optional) A list of regex patterns matching error messages that trigger a retry.
- `interval_seconds` - (Optional) Initial interval between retries in seconds.
- `max_interval_seconds` - (Optional) Maximum interval between retries in seconds.
See <https://registry.terraform.io/providers/Azure/azapi/latest/docs/resources/resource#retry> for full semantics.
DESCRIPTION}
variable"timeouts" {
type = object({
create = optional(string)
read = optional(string)
update = optional(string)
delete = optional(string)
})
default = nulldescription = <<DESCRIPTIONDefault per-operation timeouts applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (provider defaults). Each value is a Go duration string (e.g. `30m`, `1h`).
- `create` - (Optional) Timeout for create operations.
- `read` - (Optional) Timeout for read operations.
- `update` - (Optional) Timeout for update operations.
- `delete` - (Optional) Timeout for delete operations.
DESCRIPTION}
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ } # `retry` is an attribute on `azapi_resource`, so the variable can be
# assigned directly. `timeouts` is a block, so a `dynamic "timeouts"`
# block is required to honor the variable's `null` default.
retry = var.retrydynamic"timeouts" {
for_each = var.timeouts ==null? [] : [var.timeouts]
content {
create = timeouts.value.createread = timeouts.value.readupdate = timeouts.value.updatedelete = timeouts.value.delete }
}
response_export_values = []
}
module"child" {
source = "./modules/child" # Cascade retry and timeouts to the submodule.
retry = var.retrytimeouts = var.timeouts # ...other arguments...
}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the ignore_body_changes argument of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code an inline list that the consumer cannot override, and MUST NOT omit the argument.
To meet this requirement, every applicable module or submodule (see TFRMNFR1) MUST expose a variable named ignore_body_changes.
ignore_body_changes lets a consumer suppress plan diffs for a set of body paths that are mutated outside Terraform (for example tags applied by Azure Policy, or an autoscaler adjusting a capacity property). It is the supported fallback for lifecycle.ignore_changes when the paths must be derived from variables, locals or other non-static values, which lifecycle blocks cannot accept.
Without this variable a consumer has no way to reach the argument, because lifecycle.ignore_changes cannot be applied to a resource from outside the module that declares it. This is exactly the same problem that TFFR7 solves for retry and timeouts.
The module’s Azure/azapi constraint in required_providersMUST allow v2.12.0 or later, which is the release that introduces the argument (see TFFR3).
A consumer supplying a non-empty value MUST be running Terraform 1.11 or later. Modules MUST NOT raise their required_version floor for this reason alone (see TFNFR25); instead they MUST emit null when the list is empty so that consumers on earlier Terraform versions who do not use the feature are unaffected. See Applying the variable.
Important
Because the value is held in provider-private state, a change to ignore_body_changes only takes effect after an apply. A consumer who adds a path will still see the pending diff for that path in the same plan, and a consumer who removes a path will not see the suppressed diff reappear until the next plan. Module documentation SHOULD call this out.
Variable shape
Unlike retry and timeouts, which are resource-agnostic and therefore cascade unchanged, ignore_body_changes values are dot-notation paths into one specific resource’sbody. A path such as properties.addressSpace is meaningful only for the resource that owns it, so passing a parent’s list straight through to a submodule would apply meaningless paths to a different resource.
The variable is therefore scoped per resource and per submodule, using exactly the same shape and key-naming rule as resource_types (TFFR6).
The ignore_body_changes variable MUST:
Be a single object({...}) (not a map(list(string))) so typos at call sites error at plan time and the full override surface is visible in the variable declaration.
Default the variable itself to {} and be nullable = false, per TFNFR20 and TFNFR21.
Declare one optional(list(string), []) field for every AzAPI resource the module itself declares, keyed by the snake_case form of the ARM resource type with the Microsoft. prefix dropped β the identical key used in resource_types (for example Microsoft.Example/widgets β example_widgets).
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource, keyed by that submodule’s primary ARM resource type. The shape of the nested object MUST match that submodule’s own ignore_body_changes variable exactly, and the parent MUST cascade the slot through unchanged.
Document every field in the variable’s description, including what ignore_body_changes does, that paths use dot notation, and that changes take effect only after an apply.
Module owners MAY ship module-level defaults where the resource is known to be mutated outside Terraform. To do so, supply the default inside the optional(list(string), [...]) wrapper. Consumers MUST still be able to override any individual field, and a module-level default MUST NOT be used to work around a bug that belongs in the module body.
Modules MAY additionally expose per-item overrides on the collection variable that drives a for_each submodule, for cases where individual instances need different paths. Where they do, the per-item value MUST take precedence over the shared slot.
Path syntax
Values are dot-notation paths relative to the resource’s body, for example tags or properties.sku.name. Each element MUST be a non-empty string.
Individual list items MUST NOT be targeted (there is no index syntax) β ignore the entire list property instead.
Authors and consumers MUST understand that an ignored path is not merely hidden from the plan: configuration changes at that path are not sent to Azure until the path is removed from the list.
Applying the variable
ignore_body_changes is an attribute (not a block) on azapi_resource, so the relevant field of the variable is assigned directly. The assignment MUST collapse an empty list to null so that the write-only argument is absent when the feature is unused:
ID: TFFR9 - Category: Inputs/Outputs - AzAPI - Tag Propagation
Applicability
This requirement applies independently to every root module and submodule that directly declares a managed AzAPI resource. The avm_azapi_resource_tags_required rule uses its embedded AVM-generated capability snapshot to classify the resource type’s tags property as writable, read-only, or unsupported.
Requirement
For every resource type with a statically writable tags property, the resource MUST expose consumer-settable tags through the standard tags interface and set the tags argument. A direct assignment remains valid for modules that use only the module-wide fallback:
resource"azapi_resource""this" {
type = var.resource_types.example_widgetstags = var.tags}
When the module exposes the optional resource_tags interface, a non-null override for the Terraform resource block label MUST replace var.tags completely. An omitted or null override MUST inherit var.tags, and an empty map MUST remain an intentional empty replacement. The implementation MUST NOT merge the fallback and override maps.
Resource override keys identify Terraform resource block labels, not ARM resource types. Submodule overrides MUST use the deterministic typed resource_tags.modules.<module_label> shape defined by the standard tags interface. The separate resources and modules namespaces MUST resolve identical resource and module labels without ambiguity.
For every resource type with a statically read-only or unsupported tags property, the resource MUST NOT set a tags argument. Do not use a conditional, dynamic value, or an empty map to force tags onto these types.
The validation skips dynamic or otherwise unevaluable type expressions to avoid false positives. Authors SHOULD keep resource types statically resolvable through var.resource_types as required by TFFR6.
The embedded AVM-generated capability snapshot, rather than a hand-maintained module allowlist or an AzAPI import, is the authority for this classification.
ID: TFNFR14 - Category: Inputs - Not allowed variables
Since Terraform 0.13, count, for_each and depends_on are introduced for modules, module development is significantly simplified. Module’s owners MUST NOT add variables like enabled or module_depends_on to control the entire module’s operation. Boolean feature toggles are acceptable however.
ID: TFNFR38 - Category: Inputs/Outputs - Resource ID Variable Validation
Every input variable (or nested attribute) that holds an Azure ARM resource ID MUST be validated using the AzAPI provider-defined function provider::azapi::parse_resource_id, called with a literal string naming the expected resource type, and wrapped in can(...).
Hand-rolled regex, startswith, length, or split checks MUST NOT be used to validate resource IDs. The provider function knows the canonical ARM ID grammar for every resource type, is fixed in lockstep with the provider, and produces a single consistent error model β including for IDs whose grammar contains anomalies (such as classic resources, extension resources, or scope-based IDs).
This rule covers, but is not limited to:
Top-level scope variables such as parent_id (see TFRMFR1).
Variables that reference other Azure resources by ID (e.g. subnet_resource_id, key_vault_resource_id, workspace_resource_id, private_dns_zone_resource_ids, user_assigned_resource_ids).
Nested attributes inside object, map(object), set(object), or list(object) types that hold resource IDs.
Rules
The resource type passed to parse_resource_idMUST be a literal string (e.g. "Microsoft.Network/virtualNetworks/subnets"). It MUST NOT be a reference to another variable, local, or expression. This keeps each validation block self-contained and avoids requiring cross-variable validation.
For optional / nullable variables, the validation MUST short-circuit on null (e.g. var.x == null || can(provider::azapi::parse_resource_id("...", var.x))) so that callers omitting the value do not trip validation.
For collection-valued variables (set(string), list(string), map(string)), the validation MUST iterate the collection with alltrue([for v in ... : can(...)]).
For nested attributes within object types, the validation MUST iterate the parent collection (or reference the object directly) and validate each nested resource ID, again handling null for optional nested attributes.
Where a variable can legitimately hold IDs of more than one resource type (rare β e.g. marketplace_partner_resource_id in the diagnostic-settings interface), this rule does not apply and the variable SHOULD be left without resource-ID validation rather than validated against a single arbitrary type.
Examples
A required, single-value resource ID:
variable"key_vault_resource_id" {
type = stringnullable = falsevalidation {
condition = can(provider::azapi::parse_resource_id("Microsoft.KeyVault/vaults", var.key_vault_resource_id))
error_message = "`key_vault_resource_id` must be a valid Azure Key Vault resource ID." }
description = "The resource ID of the Key Vault that holds the customer-managed key."}
An optional, single-value resource ID:
variable"workspace_resource_id" {
type = stringdefault = nullnullable = truevalidation {
condition = var.workspace_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.OperationalInsights/workspaces", var.workspace_resource_id))
error_message = "`workspace_resource_id` must be a valid Log Analytics workspace resource ID, or `null`." }
description = "The resource ID of the Log Analytics workspace to send diagnostics to."}
A collection of resource IDs:
variable"user_assigned_resource_ids" {
type = set(string)
default = []
nullable = falsevalidation {
condition = alltrue([
foridin var.user_assigned_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", id))
])
error_message = "Each entry in `user_assigned_resource_ids` must be a valid user-assigned managed identity resource ID." }
description = "A set of user-assigned managed identity resource IDs to attach to the resource."}
A nested resource ID inside a map(object(...)):
variable"private_endpoints" {
type = map(object({
subnet_resource_id = stringprivate_dns_zone_resource_ids = optional(set(string), []) # ...other attributes...
}))
default = {}
nullable = falsevalidation {
condition = alltrue([
for_, vin var.private_endpoints: can(provider::azapi::parse_resource_id("Microsoft.Network/virtualNetworks/subnets", v.subnet_resource_id))
])
error_message = "Each `private_endpoints[*].subnet_resource_id` must be a valid subnet resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
foridinv.private_dns_zone_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.Network/privateDnsZones", id))
]
]))
error_message = "Each entry in `private_endpoints[*].private_dns_zone_resource_ids` must be a valid private DNS zone resource ID." }
}
Notes
The rule applies regardless of whether the resource ID is required or optional, single-valued or collection-valued, top-level or nested.
parse_resource_id errors when (a) the input is not a well-formed ARM ID, or (b) the input does not parse as the supplied resource type. Wrapping in can(...) converts both failure modes into a single boolean suitable for a validation block’s condition.
This rule supersedes any older guidance suggesting startswith(var.x, "/") or hand-written regex for resource ID validation.
Testing
The content below is listed based on the following tags
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
Where descriptions for variables and outputs spans multiple lines. The description MAY provide variable input examples for each variable using the HEREDOC format and embedded markdown.
Example:
variable"my_complex_input" {
type = map(object({
param1 = stringparam2 = optional(number, null)
}))
description = <<DESCRIPTION A complex input variable that is a map of objects.
Each object has two attributes:
- `param1`: A required string parameter.
- `param2`: (Optional) An optional number parameter.
Example Input:
```terraform
my_complex_input = {
"object1" = {
param1 = "value1"
param2 = 2
}
"object2" = {
param1 = "value2"
}
}
```
DESCRIPTION }
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
Module owners MAY cross-reference other modules to build either Resource or Pattern modules.
However, they MUST be referenced only by a public registry reference to a pinned version e.g. br/public:avm/[res|ptn|utl]/<publishedModuleName>:>version<. They MUST NOT use local parent path references to a module e.g. ../../xxx/yyy.bicep.
The only exception to this rule are child modules as documented in BCPFR6.
Modules MUST NOT contain references to non-AVM modules.
ID: BCPFR2 - Category: Composition - Role Assignments Role Definition Mapping
Module owners MAY define common RBAC Role Definition names and IDs within a variable to allow consumers to define a RBAC Role Definition by their name rather than their ID, this should be self contained within the module themselves.
However, they MUST use only the official RBAC Role Definition name within the variable and nothing else.
To meet the requirements of BCPFR2, BCPNFR5 and BCPNFR6 you MUST use the below code sample in your AVM Modules to achieve this.
@description('''Required. You can provide either the display name (note not all roles are supported, check module documentation) of the role definition, or its fully qualified ID in the following format: `/providers/Microsoft.Authorization/roleDefinitions/c2f4ef07-c644-48eb-af81-4b1b4947fb11`.''')
param roleDefinitionIdOrName string
var builtInRbacRoleNames = {
Owner: '/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635' Contributor: '/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c' Reader: '/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7''Role Based Access Control Administrator (Preview)': '/providers/Microsoft.Authorization/roleDefinitions/f58310d9-a9f6-439a-9e8d-f62e7b41a168''User Access Administrator': '/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9'//Other RBAC Role Definitions Names & IDs can be added here as needed for your module }
var roleDefinitionIdMappedResult = (contains(builtInRbacRoleNames, roleDefinitionIdOrName) ? builtInRbacRoleNames[roleDefinitionIdOrName] : roleDefinitionIdOrName)
resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
//Other properties removed for ease of reading properties: {
roleDefinitionId: roleDefinitionIdMappedResult
//Other properties removed for ease of reading }
}
To comply with specifications outlined in SFR3 & SFR4 you MUST incorporate the following code snippet into your modules. Place this code sample in the “top level” main.bicep file; it is not necessary to include it in any nested Bicep files (child modules), unless they are marked for direct publishing (Ref Child module publishing).
Parent templates MUST reference all their direct child-templates to allow for an end-to-end deployment experience. For example, the SQL server template must reference its child database module and encapsulate it in a loop to allow for the deployment of multiple databases.
@description('Optional. The databases to create in the server')
param databases databaseType[]?
resource server 'Microsoft.Sql/servers@(...)' = { (...) }
module server_databases 'database/main.bicep' = [for (database, index) in (databases ?? []): {
name: '${uniqueString(server.id, location)}-Sql-DB-${index}' params: {
serverName: server.name
(...)
}
}]
A variable named enableReferencedModulesTelemetry is created in the main.bicep file of the module, that cross-references other published modules, and set to false. This variable is used to set the enableTelemetry parameter of cross-referenced modules.
var enableReferencedModulesTelemetry = false// local referencingmodule virtualNetwork_subnets 'subnet/main.bicep' = [
for (subnet, index) in (subnets ?? []): {
name: '${uniqueString(virtualNetwork.id, location)}-subnet-${index}' params: {
(...)
enableTelemetry: enableReferencedModulesTelemetry
}
}
]
// published module referencemodule virtualNetwork_subnet 'br/public:avm/res/network/virtual-network/subnet:0.1.0' = {
name: '${uniqueString(virtualNetwork.id, location)}-subnet-${index}' params: {
(...)
enableTelemetry: enableReferencedModulesTelemetry
}
}
ID: BCPNFR1 - Category: Inputs - Complex data types - General
To simplify the consumption experience for module consumers when interacting with complex data types input parameters, mainly objects and arrays, the Bicep features of Resource-Derived Types or User-Defined TypesMUST be used and declared.
Tip
User-Defined Types are GA in Bicep as of version v0.21.1, Resource-Derived Types are GA as of version v0.34.1, please ensure you have this version(s) installed as a minimum.
Resource-Derived Types and User-Defined Types allow intellisense support in supported IDEs (e.g. Visual Studio Code) for complex input parameters using objects and array of objects.
v0.x Exemption
While we allow the release of major versions, starting with v1.0.0, retrofitting Resource-Derived Types and User-Defined Types for all modules will take a considerable amount of time.
Therefore, the addition of these features is currently NOT mandated/enforced. However, all modules MUST implement Resource-Derived Types and User-Defined Types prior to the release of their v1.0.0 version.
ID: BCPNFR10 - Category: Testing - Test Bicep File Naming
Module owners MUST name their test .bicep files in the /tests/e2e/<defaults/waf-aligned/max/etc.> directories: main.test.bicep as the test framework (CI) relies upon this name.
ID: BCPNFR13 - Category: Testing - Test file metadata
By default, the ReadMe-generating utility will create usage examples headers based on each e2e folder’s name. Module owners MAY provide a custom name & description by specifying the metadata blocks name & description in their main.test.bicep test files.
For example:
metadata name = 'Using Customer-Managed-Keys with System-Assigned identity'metadata description = 'This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.'
would lead to a header in the module’s readme.md file along the lines of
### Example 1: _Using Customer-Managed-Keys with System-Assigned identity_
This instance deploys the module using Customer-Managed-Keys using a System-Assigned Identity. This required the service to be deployed twice, once as a pre-requisite to create the System-Assigned Identity, and once to use it for accessing the Customer-Managed-Key secret.
The version value is in the form of MAJOR.MINOR. The PATCH version will be incremented by the CI automatically when publishing the module to the Public Bicep Registry once the corresponding pull request is merged. Therefore, contributions that would only require an update of the patch version, can keep the version.json file intact.
For example, the version value should be:
0.1 for new modules, so that they can be released as v0.1.0.
1.0 once the module owner signs off the module is stable enough for it’s first Major release of v1.0.0.
0.x for all feature updates between the first release v0.1.0 and the first Major release of v1.0.0.
The module-name-dropdown in the BRM AVM Module Issue templateMUST list top-level Bicep modules with Available or Orphaned status, sorted by module class and name. Proposed, deprecated, and child modules are excluded.
The module list sync workflow compares the dropdown with the published module catalog and updates it through a verified, auto-merged bot pull request. Module owners maintain root metadata and the required publication or deprecation evidence instead of editing the dropdown directly.
For each test case in the e2e folder, you can optionally add post-deployment Pester tests that are executed once the corresponding deployment completed and before the removal logic kicks in.
To leverage the feature you MUST:
Use Pester as a test framework in each test file
Name the file with the suffix "*.tests.ps1"
Place each test file the e2e test’s folder or any subfolder (e.g., e2e/max/myTest.tests.ps1 or e2e/max/tests/myTest.tests.ps1)
Implement an input parameter TestInputData in the following way:
Through this parameter you can make use of every output the main.test.bicep file returns, as well as the path to the test template file in case you want to extract data from it directly.
For example, with an output such as output resourceId string = testDeployment[1].outputs.resourceId defined in the main.test.bicep file, the $TestInputData would look like:
$TestInputData = @{
DeploymentOutputs = @{
resourceId = @{
Type = "String" Value = "/subscriptions/***/resourceGroups/dep-***-keyvault.vaults-kvvpe-rg/providers/Microsoft.KeyVault/vaults/***kvvpe001" }
}
ModuleTestFolderPath = "/home/runner/work/bicep-registry-modules/bicep-registry-modules/avm/res/key-vault/vault/tests/e2e/private-endpoint"}
To improve the usability of primitive module properties declared as strings, you SHOULD declare them using a type which better represents them, and apply any required casting in the module on behalf of the user.
For reference, please refer to the following examples:
User-defined types (UDTs) MUST always be singular and non-nullable. The configuration of either should instead be done directly at the parameter or output that uses the type.
For example, instead of
param subnets subnetsType
type subnetsType = { ... }[]?
the type should be defined like
param subnets subnetType[]?
type subnetType = { ... }
The primary reason for this requirement is clarity. If not defined directly at the parameter or output, a user would always be required to check the type to understand how e.g., a parameter is expected.
User-defined types (UDTs) MUST always end with the suffix (...)Type to make them obvious to users. In addition it is recommended to extend the suffix to (...)OutputType if a UDT is exclusively used for outputs.
type subnet = { ... } // Wrongtype subnetType = { ... } // Correcttype subnetOutputType = { ... } // Correct, if used only for outputs
Since User-defined types (UDTs) MUST always be singular as per BCPNFR18, their naming should reflect this and also be singular.
User-defined types (UDTs) SHOULD always be exported via the @export() annotation in every template they’re implemented in.
@export()
type subnetType = { ... }
Doing so has the benefit that other (e.g., parent) modules can import them and as such reduce code duplication. Also, if the module itself is published, users of the Public Bicep Registry can import the types independently of the module itself. One example where this can be useful is a pattern module that may re-use the same interface when referencing a module from the registry.
Similar to BCPNFR9, User-defined types (UDTs) MUST implement decorators such as description & secure (if sensitive). This is true for every property of the UDT, as well as the UDT itself.
Further, User-defined types SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('My type''s description.')
type myType = {
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
threshold: int?
@description('Required. The SKU of your resource.')
sku: ('Basic' | 'Premium' | 'Standard')
}
When a module to be published (i.e., that has a version.json file) is changed, an entry MUST be created in the CHANGELOG.md file in the module folder. A link to the latest version of the changelog file has to be included at the top of the file, just below the # Changelog line. It is surrounded by empty lines.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/<ptn|res|utl>/<namespace/modulename[/submodulePath]>/CHANGELOG.md).
For each new version, an entry MUST be created above all existing versions in the CHANGELOG.md file of the module.
## <version>
### Changes
- This changed
- And this also
### Breaking Changes
- None
Each version’s entry:
MUST contain two sections: Changes and Breaking Changes. At least one of them must have a meaningful entry and sections must not be left empty. A - None may be added as content for a section.
MUST exist only once.
All versions appear in descending order, which puts the most recent changes at the top.
What SHOULD be listed in the (Breaking) Changes section:
A CHANGELOG.md file in the module’s root folder MUST start with the # Changelog header, followed by an empty line and a link to the latest published version of the changelog file, followed by another empty line. A section for each published version follows. Newer versions are placed above older versions.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/avm/res/aad/domain-service/CHANGELOG.md).
## 0.2.1
### Changes
- Updated the referenced AVM common types
### Breaking Changes
- None
## 0.2.0
### Changes
- Implemented the minCPU parameter
- Updated the referenced VirtualNetwork module
- Updated the referenced AVM common types
### Breaking Changes
- The minCPU parameter is mandatory
## 0.1.0
### Changes
- Initial Release
### Breaking Changes
- None
Each bullet point should start with a capital letter.
Manual Editing
It is possible to modify the changelog content any time, e.g., to add missing versions, which will not create a new release of the module itself. Please note the following requirements in all cases:
All versions in the file, need to be valid and available as published version
Every version needs the two sections ## Changes and ## Breaking Changes with content
Note
Azure Verified Modules are artifacts in the Microsoft Container Registry (MCR). Every version of a module exists as a tag in the Container Registry and can be listed at https://mcr.microsoft.com/v2/bicep/avm/(res|ptn|utl)/<namespace/modulename>/tags/list. For example, see the FinOps hub module tags.
Each Bicep AVM module that lives within the Azure/bicep-registry-modules (BRM) repository in the avm directory MUST have the following directories and files:
/tests - (for unit tests and additional E2E/integration if required - e.g. Pester etc.)
/e2e - (all examples must deploy successfully - these will be used to automatically generate the examples in the README.md for the module)
/src - (for scripts and other files - e.g., scripts used by the template)
exampleFile.ps1
/modules - (for sub-modules only if used and NOT children of the primary resource - e.g. RBAC role assignments)
exampleTemplate.bicep
/main.bicep (AVM Module main .bicep file and entry point/orchestration module)
/main.json (auto generated and what is published to the MCR via BRM)
When a module references child, utility, or other modules, the deployment name MUST be deterministic. This means the deployment name must produce the same value for the same set of inputs across repeated deployments.
Why deterministic?
Azure Resource Manager has an 800-deployment limit per scope (resource group, subscription, management group, tenant). Non-deterministic names (e.g., those incorporating timestamps or utcNow()) create a new deployment object on every run, which can lead to this limit being reached over time.
While an automatic cleanup process exists for resource group and subscription scopes, it can take some time to take effect. Due to eventual consistency in the backend, the deployment count may not reflect the cleanup immediately, which can lead to failed deployments even when the actual number of deployments is below the 800 limit. Additionally, automatic cleanup does not apply to management group or tenant scopes.
We are actively working with the product team to enhance the cleanup process. In the meantime, deterministic deployment names provide a reliable way to keep deployment counts stable by overwriting previous deployment objects rather than creating new ones.
Deterministic deployment names cause Azure to overwrite the previous deployment object, keeping the deployment count stable regardless of how many times the module is deployed.
Requirement
Module owners MUST construct deployment names for referenced modules using uniqueString() seeded with the parent resource’s ID (<parentResource>.id) and location, rather than deployment().name, subscription().id, resourceGroup().id, utcNow(), or other non-deterministic or scope-level values.
A deterministic hash derived from the parent resource’s resource ID and deployment location. This is both unique per resource instance and stable across deployments.
<ChildModuleDescriptor>
A short, human-readable label identifying the child module being deployed (e.g., DB, Subnet, FederatedIdentityCred).
${index}
The loop index variable, included when deploying in a loop. Omit for single (non-looped) deployments.
location parameter
If location is not available, for example when deploying a global resource that does not have a location property, it is acceptable to omit it. However, the <parentResource>.idMUST always be included as the primary seed for uniqueString.
Why parent resource ID?
Using the parent resource’s ID as the uniqueString seed provides two critical properties:
Deterministic β the same parent resource always produces the same hash, so repeated deployments overwrite rather than accumulate.
Collision-free β different parent resource instances produce different hashes, so deploying multiple instances of the same module type within the same scope does not cause naming collisions.
Why not subscription().id and resourceGroup().id separately?
The parent resource’s ID (e.g., /subscriptions/.../resourceGroups/.../providers/.../resourceName) already contains the subscription ID and resource group ID as segments. Using <parentResource>.id as a single input to uniqueString captures all of this context in one value, keeping the code concise and readable rather than passing multiple scope-level values separately.
Supporting multiple deployments of the same module at the same scope
A common scenario is deploying the same module type more than once within the same scope β for example, two different SQL servers each with their own set of databases, or two user-assigned identities each with their own federated credentials. Because the parent resource ID is unique per resource instance, the resulting deployment names will differ even when the child module type and index are identical. This ensures that parallel deployments of the same module at the same scope do not collide.
Other approaches fail on one or both of these properties:
Approach
Deterministic?
Collision-free?
Issue
deployment().name
β
β
Changes every deployment; hits 800-limit
utcNow() / timestamps
β
β
Changes every deployment; hits 800-limit
subscription().id + resourceGroup().id
β
β
Same hash for all resources in the same RG; collisions when deploying multiple instances
The above formats are currently automatically taken & generated from the tests/e2e tests. It is enough to run the Set-ModuleReadMe or Set-AVMModule functions (from the utilities folder) to update the usage examples in the readme(s).
Note
Bicep Parameter Files (.bicepparam) are being reviewed and considered by the AVM team for the usability and features at this time and will likely be added in the future.
It is planned that these examples are automatically added to the module readme’s parameter descriptions when running either the Set-ModuleReadMe or Set-AVMModule scripts (available in the utilities folder).
BCPNFR5 - Role Assignments Role Definition Mapping Limits
ID: BCPNFR5 - Category: Composition - Role Assignments Role Definition Mapping Limits
As per BCPFR2, module owners MAY define common RBAC Role Definition names and IDs within a variable to allow consumers to define a RBAC Role Definition by their name rather than their ID.
Module owners SHOULD NOT map every RBAC Role Definition within this variable as it can cause the module to bloat in size and cause consumption issues later when stitched together with other modules due to the 4MB ARM Template size limit.
Therefore module owners SHOULD only map the most applicable and common RBAC Role Definition names for their module and SHOULD NOT exceed 15 RBAC Role Definitions in the variable.
Important
Remember if the RBAC Role Definition name is not included in the variable this does not mean it cannot be declared, used and assigned to an identity via an RBAC Role Assignment as part of a module, as any RBAC Role Definition can be specified via its ID without being in the variable.
Modules will have lots of parameters that will differ in their requirement type (required, optional, etc.). To help consumers understand what each parameter’s requirement type is, module owners MUST add the requirement type to the beginning of each parameter’s description. Below are the requirement types with a definition and example for the description decorator:
Parameter Requirement Type
Definition
Example Description Decorator
Required
The parameter value must be provided. The parameter does not have a default value and hence the module expects and requires an input.
The parameter value can be optional or required based on a condition, mostly based on the value provided to other parameters. Should contain a sentence starting with ‘Required if (…).’ to explain the condition.
The parameter value is generated within the module and should not be specified as input in most cases. A common example of this is the utcNow() function that is only supported as the input for a parameter value, and not inside a variable.
Similar to BCPNFR21, input parameters MUST implement decorators such as description & secure (if sensitive).
Further, input parameters SHOULD implement decorators like allowed, minValue, maxValue, minLength & maxLength (and others if available) as they have a big positive impact on the module’s usability.
@description('Optional. The threshold of your resource.')
@minValue(1)
@maxValue(10)
param threshold: int?
@description('Required. The SKU of your resource.')
@allowed([
'Basic''Premium''Standard'])
param sku string
ID: BCPRMNFR1 - Category: Testing - Expected Test Directories
Module owners MUST create the defaults, waf-aligned folders within their /tests/e2e/ directory in their resource module source code and SHOULD create a max folder also. Module owners CAN create additional folders as required. Each folder will be used as described for various test cases.
Note
If a module can deploy varying styles of the same resource, e.g., VMs can be Linux or Windows, each style should be tested as both defaults and waf-aligned. Each must then be used as suffixes in the directory name to denote the style, e.g., for a VM we would expect to see:
/tests/e2e/linux.defaults/main.test.bicep
/tests/e2e/linux.waf-aligned/main.test.bicep
/tests/e2e/windows.defaults/main.test.bicep
/tests/e2e/windows.waf-aligned/main.test.bicep
Defaults tests (MUST)
The defaults folder contains a test instance that deploys the module with the minimum set of required parameters.
This includes input parameters of type Required plus input parameters of type Conditional marked as required for WAF compliance.
This instance has heavy reliance on the default values for other input parameters. Parameters of type OptionalSHOULD NOT be used.
WAF aligned tests (MUST)
The waf-aligned folder contains a test instance that deploys the module in alignment with the best-practices of the Azure Well-Architected Framework.
This includes input parameters of type Required, parameters of type Conditional marked as required for WAF compliance, and parameters of type Optional useful for WAF compliance.
Parameters and dependencies which are not needed for WAF compliance, SHOULD NOT be included.
Max tests (SHOULD)
The max folder contains a test instance that deploys the module using a large parameter set, enabling most of the modules’ features.
The purpose of this instance is primarily parameter validation and not necessarily to serve as a real example scenario. Ideally, all features, extension resources and child resources should be enabled in this test, unless not possible due to conflicts, e.g., in case parameters are mutually exclusive.
Note
Please note that this test is not mandatory to have, but recommended for bulk parameter validation. It can be skipped in case the module parameter validation is covered already by additional, more scenario-specific tests.
Additional tests (CAN)
Additional folders CAN be created by module owners as required.
For example, to validate parameters not covered by the max test due to conflicts, or to provide a real example scenario for a specific use case.
When implementing any of the Bicep interface variants you MUST import their User-defined type (UDT) via the published AVM-Common-Types module.
When doing so, each type MUST be imported separately, right above the parameter or output that uses it.
import { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:*.*.*'@description('Optional. Array of role assignments to create.')
param roleAssignments roleAssignmentType[]?
import { diagnosticSettingFullType } from 'br/public:avm/utl/types/avm-common-types:*.*.*'@description('Optional. The diagnostic settings of the service.')
param diagnosticSettings diagnosticSettingFullType[]?
Importing them individually as opposed to one common block has several benefits such as
Individual versioning of types
If you must update the version for one type, you’re not exposed to unexpected changes to other types
Important
The import (...) block MUST not be added in between a parameter’s definition and its metadata. Doing so breaks the metadata’s binding to the parameter in question.
Finally, you should check for version updates regularly to ensure the resource module stays consistent with the specs. If the used AVM-Common-Types runs stale, the CI may eventually fail the module’s static tests.
Child resource modules MUST be stored in a subfolder of their parent resource module and named after the child resource’s singular name (ref), so that the path to the child resource folder is consistent with the hierarchy of its resource type. For example, Microsoft.Sql/servers may have dedicated child resources of type Microsoft.Sql/servers/databases. Hence, the SQL server database child module is stored in a database subfolder of the server parent folder.
sql
ββ server [module]
ββ database [child-module/resource]
In this folder, we recommend to place the child resource-template alongside a ReadMe & compiled JSON (to be generated via the default Set-AVMModule utility) and optionally further nest additional folders for its child resources.
There are several reasons to structure a module in this way. For example:
It allows a separation of concerns where each module can focus on its own properties and logic, while delegating most of a child-resource’s logic to its separate child module
It’s consistent with the provider namespace structure and makes modules easier to understand not only because they’re more aligned with set structure, but also are aligned with one another
As each module is its own ‘deployment’, it reduces limitations around nested loops
It enables module owners to publish child-modules as separate modules to the public registry, allowing consumers to make use of them directly [Ref child module publishing guidelines for details].
Note
In full transparency: The drawbacks of these additional deployments is an extended deployment period & a contribution to the 800 deployments limit. However, for AVM resource modules it was agreed that the advantages listed above outweigh these limitations.
Several resource types in Azure (e.g., role-assignments, budgets, etc.) may be deployed to more than one scope (e.g., subscription, management-group, etc.). In AVM, such modules can be implemented in one of two ways:
As pattern modules with one ‘orchestrating’ parent module using scoped sub-modules based on the input parameters provided
Note: Only the parent module is published. I.e., it is not possible to target e.g., the resource-group scoped sub-module directly.
As resource modules where each scope is implemented as a child-module of a non-published parent.
Note: Each child module is published, but not the parent. I.e., it is possible to target e.g., the resource-group scoped sub-module directly.
Tip
It is highly recommended to publish multi-scoped modules as resource modules as the solution provides the best user experience.
The following instructions consider all deployment scopes. Your module may only deploy to a subset of the same and you should map the conventions to your case.
To successfully implement a multi-scoped module as a pattern modules you have to adhere to the following convention:
The parent module MUST be implemented in the highest scope the resource provider supports (e.g., management-group)
The parent module MUST have one sub-module for each scope that the resource provider supports (e.g., management-group, subscription & resource-group)
Each sub-module MUST be implemented for the scope it is intended
The parent module MUST invoke each sub-module in the scope it is written for, using input parameters needed to target set scope (e.g., a subscription-id to invoke a module for set scope)
The parent module MUST have test cases to validate each sub-module
The parent module is the one that is versioned, published and maintains a changelog
The full folder structure may look like
πmain.bicep [Orchestrating module]
πmain.json [ARM JSON file of the module]
πversion.json [Version file of the module]
πREADME.md [Readme of the module]
πCHANGELOG.md [The changelog of the module]
β£ πmodules
β β£ πmanagement-group.bicep [Sub-module deploying to the mgmt-group scope (if applicable)]
β β£ πsubscription.bicep [Sub-module deploying to the subscription scope (if applicable)]
β β πresource-group.bicep [Sub-module deploying to the resource-group scope (if applicable)]
β πtests/e2e
β£ π mg.defaults
β β πmain.test.bicep [deploys parent template]
β£ π mg.waf-aligned
β β πmain.test.bicep [deploys parent template]
β£ π sub.defaults
β β πmain.test.bicep [deploys parent template with `subscriptionId` param]
β£ π sub.waf-aligned
β β πmain.test.bicep [deploys parent template with `subscriptionId` param]
β£ π rg.defaults
β β πmain.test.bicep [deploys parent template with `subscriptionId` & `resourceGroupName` params]
β π rg.waf-aligned
β πmain.test.bicep [deploys parent template with `subscriptionId` & `resourceGroupName` params]
Warning
Even if a consumer wants to deploy to one of the sub-scopes (e.g., subscription), the module must be deployed via its parent (e.g., management-group). This can be confusing for consumers at first and should be considered when implementing the solution.
Example: To use a role-assignment pattern module (which would be written for all scopes, with the parent targeting the management-group scope) to deploy role assignments to a resource group, a user would need to invoke New-AzManagementGroupDeployment and provide the parameters for both the subscription & resource-group to target. I.e., the user must have permissions to deploy to each scope.
Considerations when published as a resource module
The following instructions consider all deployment scopes. Your module may only deploy to a subset of the same and you should map the conventions to your case.
To successfully implement a multi-scoped module as a resource modules you have to adhere to the following convention:
The parent folder MUST contain a
main.bicep file
main.json file
README.md file
tests/e2e folder
One folder per each scope the resource provider can deploy to (either mg-scope, sub-scope or rg-scope).
Each child-module folder MUST be implemented as a proper child module, with a
main.bicep
main.json
version.json
README.md
CHANGELOG.md
file. Each child-module is maintained and versioned independently of the others.
The parent main.bicep MUST contain the following information
metadata name = '<Module Name> (Multi-Scope)'metadata description = '''
This module's child-modules deploy a <Placeholder> at a Management Group (mg-scope), Subscription (sub-scope) or Resource Group (rg-scope) scope.
> While this template is **not** published, you can find the actual published modules in the subfolders
>-`mg-scope`>-`sub-scope`>-`rg-scope`'''
targetScope = 'managementGroup'
updated with your module’s specifics
The tests/e2e folder MUST contain one instance of the require test cases per each scope, and MAY contain any additional test you see fit. In each case, the scope MUST be a prefix for the folder name. Each test case MUST reference the corresponding child module directly.
The full folder structure may look like
πmain.bicep [Skeleton module with disclaimer referring to the child-modules]
πmain.json [ARM JSON file of the module]
πREADME.md [The baseline readme, surfacing the metadata of the main.bicep file]
β£ πmg-scope
β β£πmain.bicep [Module deploying to mg-scope]
β β£πmain.json [ARM JSON file of the module]
β β£πREADME.md [Readme of the module]
β β£πversion.json [Version file of the module]
β βπCHANGELOG.md [The changelog of the module]
β£ πsub-scope
β β£πmain.bicep [Module deploying to sub-scope]
β β£πmain.json [ARM JSON file of the module]
β β£πREADME.md [Readme of the module]
β β£πversion.json [Version file of the module]
β βπCHANGELOG.md [The changelog of the module]
β£ πrg-scope
β β£πmain.bicep [Module deploying to rg-scope]
β β£πmain.json [ARM JSON file of the module]
β β£πREADME.md [Readme of the module]
β β£πversion.json [Version file of the module]
β βπCHANGELOG.md [The changelog of the module]
β πtests/e2e
β£ πmg-scope.defaults
β βπmain.test.bicep [references the 'mg-scope' child module template: '../../../mg-scope/main.bicep']
β£ πmg-scope.waf-aligned
β βπmain.test.bicep [references the 'mg-scope' child module template: '../../../mg-scope/main.bicep']
β£ πmg-scope.max
β βπmain.test.bicep [references the 'mg-scope' child module template: '../../../mg-scope/main.bicep']
β£ πsub-scope.defaults
β βπmain.test.bicep [references the 'sub-scope' child module template: '../../../sub-scope/main.bicep']
β£ πsub-scope.waf-aligned
β βπmain.test.bicep [references the 'sub-scope' child module template: '../../../sub-scope/main.bicep']
β£ πrg-scope.defaults
β βπmain.test.bicep [references the 'rg-scope' child module template: '../../../rg-scope/main.bicep']
β πrg-scope.waf-aligned
βπmain.test.bicep [references the 'rg-scope' child module template: '../../../rg-scope/main.bicep']
Important
Because each child-module is published on its own, you must ensure that each is registered in the MAR file before the modules can be published. The MAR file can only be accessed by Microsoft FTEs.
Please highlight the nature of your module in the issue when proposing it to AVM.
Module Classifications
Module Classification Definitions
AVM defines two module classifications, Resource Modules and Pattern Modules, that can be created, published, and consumed, these are defined further in the table below:
Module Class
Definition
Who is it for?
Resource Module
Deploys a primary resource with WAF high priority/impact best practice configurations set by default, e.g., availability zones, firewall, enforced Entra ID authentication and other shared interfaces, e.g., RBAC, Locks, Private Endpoints etc. (if supported). See What does AVM mean by “WAF Aligned”?
They MAY include related resources, e.g. VM contains disk & NIC. Focus should be on customer experience. A customer would expect that a VM module would include all required resources to provision a VM.
Furthermore, Resource Modules MUST NOT deploy external dependencies for the primary resource. E.g. a VM needs a vNet and Subnet to be deployed into, but the vNet will not be created by the VM Resource Module.
Finally, a resource can be anything such as Microsoft Defender for Cloud Pricing Plans, these are still resources in ARM and can therefore be created as a Resource Module.
People who want to craft bespoke architectures that default to WAF best practices, where appropriate, for each resource.
People who want to create pattern modules.
Pattern Module
Deploys multiple resources, usually using Resource Modules. They can be any size but should help accelerate a common task/deployment/architecture.
Good candidates for pattern modules are those architectures that exist in Azure Architecture Center, or other official documentation.
Note: Pattern modules can contain other pattern modules, however, pattern modules MUST NOT contain references to non-AVM modules.
People who want to easily deploy patterns (architectures) using WAF best practices.
Utility Module (draft, see below)
Implements a function or routine that can be flexibly reused in resource or pattern modules - e.g., a function that retrieves the endpoint of an API or portal of a given environment.
It MUST NOT deploy any Azure resources other than deployment scripts.
People who want to leverage commonly used functions/routines/helpers in their module, instead of re-implementing them locally.
PREVIEW
The concept of Utility Modules will be introduced gradually, through some initial examples. The definition above is subject to change as additional details are worked out.
The required automated tests and other workflow elements will be derived from the Pattern Modules’ automation/CI environment as the concept matures.
Utility modules will follow the below naming convention:
Bicep: avm/utl/<hyphenated grouping/category name>/<hyphenated utility module name>. Modules will be kept under the avm/utl folder in the BRM repository.
Terraform: avm-utl-<utility-module-name>. Repositories will be named after the utility module (e.g., terraform-azure-avm-utl-<my utility module>).
All related documentation (functional and non-functional requirements, etc.) will also be published along the way.
Module Lifecycle
This section outlines the different stages of a module’s lifecycle:
flowchart LR
Proposed["1 - Proposed βͺ"] --> |Acceptance criteria met β | Available["2 - Available π’"]
click Proposed "/Azure-Verified-Modules/specs/shared/module-lifecycle/#1-proposed-modules"
click Available "/Azure-Verified-Modules/specs/shared/module-lifecycle/#2-available-modules"
Proposed --> |Acceptance criteria not met β| Rejected[Rejected]
Available --> |Module temporarily not maintained| Orphaned["3 - Orphaned π‘"]
Orphaned --> |End of life| Deprecated["4 - Deprecated π΄"]
click Orphaned "/Azure-Verified-Modules/specs/shared/module-lifecycle/#3-orphaned-modules"
Orphaned --> |New owner identified| Available
Available --> |End of life| Deprecated
click Deprecated "/Azure-Verified-Modules/specs/shared/module-lifecycle/#4-deprecated-modules"
style Proposed fill:#ADD8E6,stroke:#333,stroke-width:1px
style Orphaned fill:#F4A460,stroke:#333,stroke-width:1px
style Available fill:#8DE971,stroke:#333,stroke-width:4px
style Deprecated fill:#000000,stroke:#333,stroke-width:1px,color:#fff
style Rejected fill:#A2A2A2,stroke:#333,stroke-width:1px
Important
If a module proposal is rejected, the issue is closed and the module’s lifecycle ends.
1. Proposed Modules
A module can be proposed through the module proposal process. The module proposal process is outlined in the Process Overview section.
To propose/request a new AVM resource, pattern or utility module, submit a module proposal issue in the AVM repository.
The proposal should include the following information:
module name
language (Bicep, Terraform, etc.)
module class (resource, pattern, utility)
module description
module owner(s) - if known
The AVM core team will review the proposal, and administrate the module.
Info
To propose a new module, submit a module proposal issue in the AVM repository.
2. Available modules
Once a module has been fully developed, tested and published in the main branch of the repository and the corresponding public registry (Bicep or Terraform), it is then considered to be “available” and can be used by the community. The module is maintained by the module owner(s). Feature or bug fix requests and related pull requests can be submitted by anyone for review.
Info
To publish a new version of an existing module (i.e., anything that is not being published for the first time ever), there’s no need to submit any issues in the AVM repository; contributors can just submit a Pull Request in the module’s repository with the suggested changes.
β Who needs to approve the PR?
Approval for changes to existing modules depends on the language:
Bicep: Module owners are requested for review based on their root metadata.json, but ordinary code changes may be approved and merged by any eligible BRM repository team member under repository rules. Authors cannot approve their own changes. Changes to metadata.json require metadata code-owner review; other protected paths follow their CODEOWNERS rules.
Terraform: Module-owner approval remains required in Terraform module repositories:
Reviewer notifications and triage labels help find reviewers; they do not replace either language’s repository rules.
3. Orphaned Modules
It is critical to the consumers experience that modules continue to be maintained. In the case where a module owner cannot continue in their role or do not respond to issues as per the defined timescale in the Module Support page , the following process will apply:
The module owner is responsible for finding a replacement owner and providing a handover.
If no replacement can be found or the module owner leaves Microsoft without giving warning to the AVM core team, the AVM core team will provide essential maintenance (critical bug and security fixes), as per the Module Support page
The AVM core team will continue to try and re-assign the module ownership.
While a module is in an orphaned state, only security and bug fixes MUST be made, no new feature development will be worked on until a new owner is found that can then lead this effort for the module.
An issue will be created on the central AVM repo (Azure/Azure-Verified-Modules) to track the finding of a new owner for a module.
Set "owners": [] in the root metadata.json to remove all individual and team handles, following the metadata review process. Complete the issue and required notices; the four-hourly catalog sync then publishes the public index.
When a module becomes orphaned, the AVM core team will communicate this through an information notice to be placed as follows.
In case of a Bicep module, the information notice will be placed in an ORPHANED.md file and in the header of the module’s README.md - both residing in the module’s root.
In case of a Terraform module, the information notice will be placed in the header of the README.md file, in the module’s root.
The information notice will include the following statement:
β οΈTHIS MODULE IS CURRENTLY ORPHANED.β οΈ
- Only security and bug fixes are being handled by the AVM core team at present.
- If interested in becoming the module owner of this orphaned module (must be Microsoft FTE), please look for the related "orphaned module" GitHub issue [here](https://aka.ms/AVM/OrphanedModules)!
Also, the AVM core team will amend the issue automation to auto reply stating that the repo is orphaned and only security/bug fixes are being handled until a new module owner is found.
4. Deprecated Modules
Once a module reaches the end of its lifecycle (e.g., it’s permanently replaced by another module; permanent retirement due to obsolete technology/solution), it needs to be deprecated. A deprecated module will no longer be maintained, and no new features or bug fixes will be implemented for it. The module will indefinitely stay available in the public registry and source code repository for use, but certain measures will take place, such as:
The module will show as deprecated in the AVM module index.
The module will no longer be shown through VS Code IntelliSense.
The module’s source code will be kept in its repository but it will show a deprecated status through a DEPRECATED.md file (Bicep only) and a disclaimer in the module’s README.md file.
It will be a clearly indicated on the module’s repo that new issues can no longer be submitted for the module:
Bicep: The module will be taken off the list of available modules in related issue templates.
Terraform: The module’s repo will be archived.
It is recommended to migrate to a replacement/alternative version of the module, if available.
Important
When a module becomes deprecated, the AVM core team will communicate this through an information notice to be placed as follows.
In case of a Bicep module, the information notice will be placed in a DEPRECATED.md file and in the header of the module’s README.md - both residing in the module’s root.
In case of a Terraform module, the information notice will be placed in the header of the README.md file, in the module’s root.
The information notice MUST include the following statement:
β οΈTHIS MODULE IS DEPRECATED.β οΈ
- It will no longer receive any updates.
- If the underlying Azure service is not deprecated/retired, this module may still be used as is (references to any existing versions will keep working), but it is not recommended for new deployments.
- It is recommended to migrate to a replacement/alternative version of the module, if available.
The catalog derives Deprecated from Bicep’s DEPRECATED.md or the Terraform repository’s archived flag. Complete the notices and other retirement steps above; the four-hourly catalog sync then publishes the change.
A Bicep marker deprecates its module and all descendants. A child marker does not deprecate the parent or siblings. Archiving a Terraform repository deprecates every module entry in that repository.
A module deprecated before it was ever published to the registry is removed from the indexes rather than listed as Deprecated.
Changing owners does not deprecate or reactivate a module.
β Retrieve the available versions of a deprecated module
To find all previous versions of a Bicep module, the following steps need to be performed (assuming the avm/ptn/finops-toolkit/finops-hub module has been deprecated):
To find out the all the versions the module has ever been published under, perform one of these steps:
navigate to Bicep Public Registry’s JSON index and look for the module’s name,
OR clone the Bicep Public Registry repository and run the following command in the root of the repository: git tag -l 'avm/ptn/finops-toolkit/finops-hub/*'. This will list all the tags that match the module’s name.
Identify the available versions of the module, e.g., 0.1.0, 0.1.1, etc.
Pattern Modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Example: avm/ptn/compute/app-tier-vmss or avm/ptn/avd-lza/management-plane or avm/ptn/3-tier/web-app
Segments:
ptn defines this as a pattern module
<hyphenated grouping/category name> is a hierarchical grouping of pattern modules by category, with each word separated by dashes, such as:
project name, e.g., avd-lza,
primary resource provider, e.g., compute or network, or
architecture, e.g., 3-tier
<hyphenated pattern module name> is a term describing the module’s function, with each word separated by dashes, e.g., app-tier-vmss = Application Tier VMSS; management-plane = Azure Virtual Desktop Landing Zone Accelerator Management Plane
Terraform Pattern Module Naming
Naming convention:
avm-ptn-<pattern module name> (Module name for registry)
terraform-<provider>-avm-ptn-<pattern module name> (GitHub repository name to meet registry naming requirements)
Example: avm-ptn-apptiervmss or avm-ptn-avd-lza-managementplane
Segments:
<provider> is a legacy requirement of the Terraform registry. This must be set to azure
ptn defines this as a pattern module
<pattern module name> is a term describing the module’s function, e.g., apptiervmss = Application Tier VMSS; avd-lza-managementplane = Azure Virtual Desktop Landing Zone Accelerator Management Plane
PMNFR2 - Use Resource Modules to Build a Pattern Module
ID: PMNFR2 - Category: Composition - Use Resource Modules to Build a Pattern Module
A Pattern Module SHOULD be built from AVM Resources Modules to establish a standardized code base and improve maintainability. If a valid reason exists, a pattern module MAY contain native resources (“vanilla” code) where it’s necessary. A Pattern Module MUST NOT contain references to non-AVM modules.
Valid reasons for not using a Resource Module for a resource required by a Pattern Module include but are not limited to:
When using a Resource Module would result in hitting scaling limitations and/or would reduce the capabilities of the Pattern Module due to the limitations of Azure Resource Manager.
Developing a Pattern Module under time constraint, without having all required Resource Modules readily available.
Note
In the latter case, the Pattern Module SHOULD be updated to use the Resource Module when the required Resource Module becomes available, to avoid accumulating technical debt. Ideally, all required Resource Modules SHOULD be developed first, and then leveraged by the Pattern Module.
ID: RMFR3 - Category: Composition - Resource Groups
A resource module MUST NOT create a Resource Group for resources that require them.
In the case that a Resource Group is required, a module MUST have an input (scope or variable):
In Bicep the targetScopeMUST be set to resourceGroup or not specified (which means default to resourceGroup scope).
For Terraform, the resource group is supplied via the parent_id variable defined by TFRMFR1. Terraform resource modules MUST NOT expose a resource_group_name (or resource_group_resource_id) variable.
Scopes will be covered further in the respective language specific specifications.
Resource modules support the following optional features/extension resources, as specified, if supported by the primary resource. The top-level variable/parameter names MUST be:
Optional Features/Extension Resources
Bicep Parameter Name
Terraform Variable Name
MUST/SHOULD
Diagnostic Settings
diagnosticSettings
diagnostic_settings
MUST
Role Assignments
roleAssignments
role_assignments
MUST
Resource Locks
lock
lock
MUST
Tags
tags
tags
MUST
Managed Identities (System / User Assigned)
managedIdentities
managed_identities
MUST
Private Endpoints
privateEndpoints
private_endpoints
MUST
Customer Managed Keys
customerManagedKey
customer_managed_key
MUST
Azure Monitor Alerts
alerts
alerts
SHOULD
Resource modules MUST NOT deploy required/dependent resources for the optional features/extension resources specified above. For example, for Diagnostic Settings the resource module MUST NOT deploy the Log Analytics Workspace, this is expected to be already in existence from the perspective of the resource module deployed via another method/module etc.
Note
Please note that the implementation of Customer Managed Keys from an ARM API perspective is different across various RPs that implement Customer Managed Keys in their service. For that reason you may see differences between modules on how Customer Managed Keys are handled and implemented, but functionality will be as expected.
Module owners MAY choose to utilize cross repo dependencies for these “add-on” resources, or MAY chose to implement the code directly in their own repo/module. So long as the implementation and outputs are as per the specifications requirements, then this is acceptable.
Tip
Make sure to checkout the language specific specifications for more info on this:
Resource modules MUST implement a common interface, e.g. the input’s data structures and properties within them (objects/arrays/dictionaries/maps), for the optional features/extension resources:
Parameters/variables that pertain to the primary resource MUST NOT use the resource type in the name.
e.g., use sku, vs. virtualMachineSku/virtualmachine_sku
Another example for where RPs contain some of their name within a property, leave the property unchanged. E.g. Key Vault has a property called keySize, it is fine to leave as this and not remove the key part from the property/parameter name.
When a given version of an Azure resource used in a resource module reaches its end-of-life (EOL) and is no longer supported by Microsoft, the module owner SHOULD ensure that:
The module is aligned with these changes and only includes supported versions of the resource. This is typically achieved through the allowed values in the parameter that specifies the resource SKU or type.
The following notice is shown under the Notes section of the module’s readme.md. (If any related public announcement is available, it can also be linked to from the Notes section.):
“Certain versions of this Azure resource reached their end of life. The latest version of this module only includes supported versions of the resource. All unsupported versions have been removed from the related parameters.”
AND the related parameter’s description:
“Certain versions of this Azure resource reached their end of life. The latest version of this module only includes supported versions of the resource. All unsupported versions have been removed from this parameter.”
Resource modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Report missing or incorrect resource names to the AVM core team. Index corrections go through catalog generation and reviewed publication.
Bicep Resource Module Naming
Naming convention (module name for registry): avm/res/<hyphenated resource provider name>/<hyphenated ARM resource type>
Example: avm/res/compute/virtual-machine or avm/res/managed-identity/user-assigned-identity
Segments:
res defines this is a resource module
<hyphenated resource provider name> is the resource provider’s name after the Microsoft part, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Compute = compute, Microsoft.ManagedIdentity = managed-identity.
<hyphenated ARM resource type> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Compute/virtualMachines = virtual-machine, BUTMicrosoft.Network/trafficmanagerprofiles = trafficmanagerprofile - since trafficmanagerprofiles is all lower case as per the ARM API definition.
Bicep Child Module Naming
Naming convention (module name for registry):avm/res/<hyphenated resource provider name>/<hyphenated ARM resource type>/<hyphenated child resource type/<hyphenated grandchild resource type>/<etc.>
Example: avm/res/network/virtual-network/subnet or avm/res/storage/storage-account/blob-service/container
Segments:
res defines this is a resource module
<hyphenated resource provider name> is the resource provider’s name after the Microsoft part, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network = network.
<hyphenated ARM resource type> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network/virtualNetworks = virtual-network.
<hyphenated child resource type (to be repeated for grandchildren, etc.)> is the singular version of the word after the resource provider, with each word starting with a capital letter separated by dashes, e.g., Microsoft.Network/virtualNetworks/subnets = subnet or Microsoft.Storage/storageAccounts/blobServices/containers = blob-service/container.
Terraform Resource Module Naming
Naming convention:
avm-res-<resource provider>-<ARM resource type> (module name for registry)
terraform-<provider>-avm-res-<resource provider>-<ARM resource type> (GitHub repository name to meet registry naming requirements)
Example: avm-res-compute-virtualmachine or avm-res-managedidentity-userassignedidentity
Segments:
<provider> is a legacy requirement of the Terraform registry. This must be set to azure
res defines this is a resource module
<resource provider> is the resource provider’s name after the Microsoft part, e.g., Microsoft.Compute = compute.
<ARM resource type> is the singular version of the word after the resource provider, e.g., Microsoft.Compute/virtualMachines = virtualmachine
A resource module MUST use the following standard inputs:
name (no default)
location (if supported by the resource and not a global resource, then use Resource Group location, if resource supports Resource Groups, otherwise no default)
ID: RMNFR3 - Category: Composition - RP Collaboration
Module owners (Microsoft FTEs) SHOULD reach out to the respective Resource Provider teams to build a partnership and collaboration on the modules creation, existence and long term maintenance.
Modules MAY create/adopt public preview services and features at their discretion.
Preview API versions MAY be used when:
The resource/service/feature is GA but the only API version available for the GA resource/service/feature is a preview version
For example, Diagnostic Settings (Microsoft.Insights/diagnosticSettings) the latest version of the API available with GA features, like Category Groups etc., is 2021-05-01-preview
Otherwise the latest “non-preview” version of the API SHOULD be used
Preview services and features, SHOULD NOT be promoted and exposed, unless they are supported by the respective PG, and it’s documented publicly.
However, they MAY be exposed at the module owners discretion, but the following rules MUST be followed:
The description of each of the parameters/variables used for the preview service/feature MUST start with:
“THIS IS A <PARAMETER/VARIABLE> USED FOR A PREVIEW SERVICE/FEATURE, MICROSOFT MAY NOT PROVIDE SUPPORT FOR THIS, PLEASE CHECK THE PRODUCT DOCS FOR CLARIFICATION”
Modules SHOULD set defaults in input parameters/variables to align to high priority/impact/severity recommendations, where appropriate and applicable, in the following frameworks and resources:
They SHOULD NOT align to these recommendations when it requires an external dependency/resource to be deployed and configured and then associated to the resources in the module.
Alignment SHOULD prioritize best-practices and security over cost optimization, but MUST allow for these to be overridden by a module consumer easily, if desired.
Modules MUST provide the capability to collect deployment/usage telemetry as detailed in Telemetry further.
To highlight that AVM modules use telemetry, an information notice MUST be included in the footer of each module’s README.md file with the below content. See the telemetry guidance for more details.
Telemetry Information Notice
Note
The following information notice is automatically added at the bottom of the README.md file of the module when
Terraform: Running avm pre-commit with the note and header ## Data Collection placed in the module’s _footer.md beforehand
### Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the [repository](https://aka.ms/avm/telemetry). There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at <https://go.microsoft.com/fwlink/?LinkID=824704>. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
Module Class Applicability
This specification applies to all AVM module classes (resource, pattern, utility), however, in case of utility modules, telemetry collection MUST only be added when the utility module deploys any resources (e.g., a deployment script resource). If the utility module does not deploy any resources, telemetry collection MUST NOT be added.
Record the assigned prefix in telemetryIdPrefix in the module’s metadata.json, including a child’s own file when applicable. Keep it consistent with the module source and preserve existing identifiers. Corrections follow the metadata review process; assignment of a new identifier requires the AVM core team.
Assigned values are also published in the Resource Module, Pattern Module, and Utility Module indexes. Ask the AVM core team to resolve any discrepancy with metadata rather than inventing or replacing an identifier.
The ARM deployment name used for the telemetry MUST follow the pattern and MUST be no longer than 64 characters in length: 46d3xbcp.<res/ptn>.<(short) module name>.<version>.<uniqueness>
<res/ptn> == AVM Resource or Pattern Module
<(short) module name> == The AVM Module’s, possibly shortened, name including the resource provider and the resource type, without;
The prefixes: avm-res-
The prefixes: avm-ptn-
<version> == The AVM Module’s MAJOR.MINOR version (only) with . (periods) replaced with - (hyphens), to allow simpler splitting of the ARM deployment name
<uniqueness> == This section of the ARM deployment name is to be used to ensure uniqueness of the deployment name.
This is to cater for the following scenarios:
The module is deployed multiple times to the same:
Due to the 64-character length limit of Azure deployment names, the <(short) module name> segment has a length limit of 36 characters, so if the module name is longer than that, it MUST be truncated to 36 characters. If any of the semantic version’s segments are longer than 1 character, it further restricts the number of characters that can be used for naming the module.
An example deployment name for the AVM Virtual Machine Resource Module would be: 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3
An example deployment name for a shortened module name would be: 46d3xbcp.res.desktopvirtualization-appgroup.1-2-3.eum3
Tip
Terraform: Terraform uses a telemetry provider, the configuration of which is the same for every module and is included in the template repo.
General: See the language specific contribution guides for detailed guidance and sample code to use in AVM modules to achieve this requirement.
To enable telemetry data collection for Terraform modules, the modtm telemetry provider MUST be used. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and is enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring.
The modtm provider MUST be listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The telemetry collection MUST be on/enabled by default, however module consumers MUST be allowed to disable it by setting the below parameter/variable value to false:
Bicep: enableTelemetry
Terraform: enable_telemetry
Note
Whenever a module references AVM modules that implement the telemetry parameter (e.g., a pattern module that uses AVM resource modules), the telemetry parameter value MUST be passed through to these modules. This is necessary to ensure a consumer can reliably enable & disable the telemetry feature for all used modules.
This general specification can be modified for some use-cases, that are language specific:
Bicep
For cross-references in resource modules, the spec BCPFR7 also applies.
ID: SFR5 - Category: Composition - Availability Zones
Modules that deploy zone-redundant resources MUST enable the spanning across as many zones as possible by default, typically all 3.
Modules that deploy zonal resources MUST provide the ability to specify a zone for the resources to be deployed/pinned to. However, they MUST NOT default to a particular zone by default, e.g. 1 in an effort to make the consumer aware of the zone they are selecting to suit their architecture requirements.
For both scenarios the modules MUST expose these configuration options via configurable parameters/variables.
ID: SFR6 - Category: Composition - Data Redundancy
Modules that deploy resources or patterns that support data redundancy SHOULD enable this to the highest possible value by default, e.g. RA-GZRS. When a resource or pattern doesn’t provide the ability to specify data redundancy as a simple property, e.g. GRS etc., then the modules MUST provide the ability to enable data redundancy for the resources or pattern via parameters/variables.
For example, a Storage Account module can simply set the sku.name property to Standard_RAGZRS. Whereas a SQL DB or Cosmos DB module will need to expose more properties, via parameters/variables, to allow the specification of the regions to replicate data to as per the consumers requirements.
Only the latest released version of a module MUST be supported.
For example, if an AVM Resource Module is used in an AVM Pattern Module that was working but now is not. The first step by the AVM Pattern Module owner should be to upgrade to the latest version of the AVM Resource Module test and then if not fixed, troubleshoot and fix forward from the that latest version of the AVM Resource Module onward.
This avoids AVM Module owners from having to maintain multiple major release versions.
README documentation MUST be automatically/programmatically generated. MUST include the sections as defined in the language specific requirements BCPNFR2, TFNFR2.
You cannot specify the patch version for Bicep modules in the public Bicep Registry, as this is automatically incremented by 1 each time a module is published. You can only set the Major and Minor versions.
Modules MUST use semantic versioning (aka semver) for their versions and releases in accordance with: Semantic Versioning 2.0.0
For example all modules should be released using a semantic version that matches this pattern: X.Y.Z
X == Major Version
Y == Minor Version
Z == Patch Version
Module versioning before first Major version release 1.0.0
Initially modules MUST be released as version 0.1.0 and incremented via Minor and Patch versions only until the AVM Core Team are confident the AVM specifications are mature enough and appropriate CI test coverage is in place, plus the module owner is happy the module has been “road tested” and is now stable enough for its first Major release of version 1.0.0.
Note
Releasing as version 0.1.0 initially and only incrementing Minor and Patch versions allows the module owner to make breaking changes more easily and frequently as it’s still not an official Major/Stable release. π
Until first Major version 1.0.0 is released, given a version number X.Y.Z:
X Major version MUST NOT be bumped.
Y Minor version MUST be bumped when introducing breaking changes (which would normally bump Major after 1.0.0 release) or feature updates (same as it will be after 1.0.0 release).
Z Patch version MUST be bumped when introducing non-breaking, backward compatible bug fixes (same as it will be after 1.0.0 release).
A module SHOULD avoid breaking changes, e.g., deprecating inputs vs. removing. If you need to implement changes that cause a breaking change, the major version should be increased.
Info
Modules that have not been released as 1.0.0 may introduce breaking changes, as explained in the previous ID SNFR17. That means that you have to introduce non-breaking and breaking changes with a minor version jump, as long as the module has not reached version 1.0.0.
There are, however, scenarios where you want to include breaking changes into a commit and not create a new major version. If you want to introduce breaking changes as part of a minor update, you can do so. In this case, it is essential to keep the change backward compatible, so that the existing code will continue to work. At a later point, another update can increase the major version and remove the code introduced for the backward compatibility.
Tip
See the language specific examples to find out how you can deal with deprecations in AVM modules.
Modules MUST implement end-to-end (deployment) testing that create actual resources to validate that module deployments work. In Bicep tests are sourced from the directories in /tests/e2e. In Terraform, these are in /examples.
Each test MUST run and complete without user inputs successfully, for automation purposes.
Each test MUST also destroy/clean-up its resources and test dependencies following a run.
Tip
To see a directory and file structure for a module, see the language specific contribution guide.
It is likely that to complete E2E tests, a number of resources will be required as dependencies to enable the tests to pass successfully. Some examples:
When testing the Diagnostic Settings interface for a Resource Module, you will need an existing Log Analytics Workspace to be able to send the logs to as a destination.
When testing the Private Endpoints interface for a Resource Module, you will need an existing Virtual Network, Subnet and Private DNS Zone to be able to complete the Private Endpoint deployment and configuration.
Module owners MUST:
Create the required resources that their module depends upon in the test file/directory
They MUST either use:
Simple/native resource declarations/definitions in their respective IaC language, OR
Another already published AVM Module that MUST be pinned to a specific published version.
They MUST NOT use any local directory path references or local copies of AVM modules in their own modules test directory.
β Terraform & Bicep Log Analytics Workspace examples using simple/native declarations for use in E2E tests
Deployment tests are an important part of a module’s validation and a staple of AVM’s CI environment. However, there are situations where certain e2e-test-deployments cannot be performed against AVM’s test environment (e.g., if a special configuration/registration (such as certain AI models) is required). For these cases, the CI offers the possibility to ‘skip’ specific test cases by placing a file named .e2eignore in their test folder.
Note
A skipped test case is still added to the ‘Usage Examples’ section of the module’s readme and should be manually validated in regular intervals.
Details for use in E2E tests
You MUST add a note to the tests metadata description, which explains the excemption.
If you require that a test is skipped and add an β.e2eignoreβ file (e.g. \<module\>/tests/e2e/\<testname\>/.e2eignore) to a pull request, a member of the AVM Core Technical Bicep Team must approve set pull request. The content of the file is logged the module’s workflow runs and transparently communicates why the test case is skipped during the deployment validation stage. It iss hence important to specify the reason for skipping the deployment in this file.
Sample filecontent:
The test is skipped, as only one instance of this service can be deployed to a subscription.
Note
For resource modules, the ‘defaults’ and ‘waf-aligned’ tests can’t be skipped.
The deployment of a test can be skipped by adding a .e2eignore file into a test folder (e.g. /examples/<testname>).
ID: SNFR20 - Category: Contribution/Support - GitHub Teams Only
All GitHub repositories that AVM modules are published from and hosted within MUST only assign GitHub repository permissions to GitHub teams.
Module ownership MUST be recorded separately from access permissions. Maintain owners in the root metadata.json through the metadata review process. Owner access is managed through the access package described below.
There MUST NOT be any GitHub repository permissions assigned to individual users.
Info
Non-FTE / external contributors (subject matter experts that aren’t Microsoft employees) can’t be members of the teams described in this chapter, hence, they won’t gain any extra permissions on AVM repositories, therefore, they need to work in forks.
Bicep
Note
Access management for Bicep module owners is governed centrally through Microsoft Entra. Per-module GitHub teams and parent-team assignments are no longer required.
Bicep module owners MUST continue to work in forks of the BRM repository.
CODEOWNERS file
The BRM CODEOWNERS file retains the repository-wide @Azure/azure-verified-modules-tooling-contributors default and its *avm.core.team.tests.ps1 and *.e2eignore overrides. Its /avm/ entry intentionally has no owners, and it has no per-module entries. Change module ownership in the root metadata.json, not by adding CODEOWNERS entries.
The last rule in CODEOWNERS assigns metadata.json changes to @Azure/azure-verified-modules-engineering-owners and @Azure/azure-verified-modules-module-owners. An eligible member of either team can approve a metadata change; both teams are not required. This special rule still applies to module metadata despite the ownerless /avm/ entry.
The Bicep reviewer-routing workflow uses each root module’s owners array to request reviewers for code changes; children inherit those owners. When a module has no owners, it requests @Azure/azure-verified-modules-module-owners and applies an orphaned-module triage label. These are notifications, not code-owner approvals: ordinary Bicep module code changes may be approved and merged by any eligible repository team member under repository rules. Authors cannot approve their own changes. Being listed in metadata does not grant review permission.
For Bicep and Terraform, both metadata code-owner teams must be visible and have repository write access. Access administration and environment approvals remain separate responsibilities.
Access management for Terraform repositories is governed centrally through Microsoft Entra. Module owner access is granted via an Entra access package β it is no longer managed through a per-module GitHub team or the legacy Core Identity entitlement.
All module owners MUST request access via the Azure Verified Modules (AVM) Module Contributors Entra access package:
Once approved, you are added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories. Day-to-day repository access is then granted through this group together with just-in-time (JIT) elevation.
ID: SNFR21 - Category: Publishing - Cross Language Collaboration
When the module owners of the same Resource, Pattern or Utility module are not the same individual or team for all languages, each languages team SHOULD collaborate with their sibling language team for the same module to ensure consistency where possible.
ID: SNFR22 - Category: Inputs - Parameters/Variables for Resource IDs
A module parameter/variable that requires a full Azure Resource ID as an input value, e.g. /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyVaultName}, SHOULD contain ResourceId/resource_id in its parameter/variable name when that parameter/variable is part of a user-defined type. This assists users in knowing what value to provide at a glance of the parameter/variable name.
Example for the property workspaceId for the Diagnostic Settings resource in a user-defined type: in Bicep its parameter name should be workspaceResourceId and the variable name in Terraform should be workspace_resource_id.
In that user-defined context, workspaceId is not descriptive enough and is ambiguous as to which ID is required to be input.
Special considerations for Bicep
If the property is nested in a parameter and you opt for a resource-derived type (that is, a schema defined by the resource provider), this requirement does not apply. We do however recommend to use a user-defined type whenever these cases occur to increase the module’s usability.
Example for the property subnetArmId of the Cognitive Service’s property networkInjections:
If using a user-defined type, you may define a type for the networkInjections parameter like
```shell
# Linux / MacOs# For Windows replace $PWD with your the local path or your repository#docker run -it -v $PWD:/repo -w /repo mcr.microsoft.com/powershell pwsh -Command '
#Invoke-WebRequest -Uri "https://azure.github.io/Azure-Verified-Modules/scripts/Set-AvmGitHubLabels.ps1" -OutFile "Set-AvmGitHubLabels.ps1"
$gh_version = "2.44.1"
Invoke-WebRequest -Uri "https://github.com/cli/cli/releases/download/v2.44.1/gh_2.44.1_linux_amd64.tar.gz" -OutFile "gh_$($gh_version)_linux_amd64.tar.gz"
apt-get update && apt-get install -y git
tar -xzf "gh_$($gh_version)_linux_amd64.tar.gz"
ls -lsa
mv "gh_$($gh_version)_linux_amd64/bin/gh" /usr/local/bin/
rm "gh_$($gh_version)_linux_amd64.tar.gz" && rm -rf "gh_$($gh_version)_linux_amd64"
gh --version
ls -lsa
gh auth login
$OrgProject = "Azure/terraform-azurerm-avm-res-kusto-cluster"
gh auth status
./Set-AvmGitHubLabels.ps1 -RepositoryName $OrgProject -CreateCsvLabelExports $false -NoUserPrompts $true
'```
By default this script will only update and append labels on the repository specified. However, this can be changed by setting the parameter -UpdateAndAddLabelsOnly to $false, which will remove all the labels from the repository first and then apply the AVM labels from the CSV only.
Make sure you elevate your privilege to admin level or the labels will not be applied to your repository. Go to repos.opensource.microsoft.com/orgs/Azure/repos/ to request admin access before running the script.
Full Script:
These Set-AvmGitHubLabels.ps1 can be downloaded from here.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
<#
.SYNOPSIS This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
.DESCRIPTION This script can be used to create the Azure Verified Modules (AVM) standard GitHub labels to a GitHub repository.
By default, the script will remove all pre-existing labels and apply the AVM labels. However, this can be changed by using the -RemoveExistingLabels parameter and setting it to $false. The tool will also output the labels that exist in the repository before and after the script has run to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter.
The AVM labels to be created are documented here: TBC
.NOTES Please ensure you have specified the GitHub repositry correctly. The script will prompt you to confirm the repository name before proceeding.
.COMPONENT You must have the GitHub CLI installed and be authenticated to a GitHub account with access to the repository you are applying the labels to before running this script.
.LINK TBC
.Parameter RepositoryName
The name of the GitHub repository to apply the labels to.
.Parameter RemoveExistingLabels
If set to $true, the default value, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will not remove any pre-existing labels.
.Parameter UpdateAndAddLabelsOnly
If set to $true, the default value, the script will only update and add labels to the repository specified in -RepositoryName. If set to $false, the script will remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
.Parameter OutputDirectory
The directory to output the pre-existing and post-existing labels to in a CSV file. The default value is the current directory.
.Parameter CreateCsvLabelExports
If set to $true, the default value, the script will output the pre-existing and post-existing labels to a CSV file in the current directory, or a directory specified by the -OutputDirectory parameter. If set to $false, the script will not output the pre-existing and post-existing labels to a CSV file.
.Parameter GitHubCliLimit
The maximum number of labels to return from the GitHub CLI. The default value is 999.
.Parameter LabelsToApplyCsvUri
The URI to the CSV file containing the labels to apply to the GitHub repository. The default value is https://raw.githubusercontent.com/jtracey93/label-source/main/avm-github-labels.csv.
.Parameter NoUserPrompts
If set to $true, the default value, the script will not prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels. If set to $false, the script will prompt the user to confirm they want to remove all pre-existing labels from the repository specified in -RepositoryName before applying the AVM labels.
This is useful for running the script in automation workflows
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and remove all pre-existing labels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels"
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and output the pre-existing and post-existing labels to the directory C:\GitHubLabels and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -RemoveExistingLabels $false -CreateCsvLabelExports $false
.EXAMPLE Create the AVM labels in the repository Org/MyGitHubRepo and do not create the pre-existing and post-existing labels CSV files and do not remove any pre-existing labels, just overwrite any labels that have the same name. Finally, use a custom CSV file hosted on the internet to create the labels from.
Set-AvmGitHubLabels.ps1 -RepositoryName "Org/MyGitHubRepo" -OutputDirectory "C:\GitHubLabels" -RemoveExistingLabels $false -CreateCsvLabelExports $false -LabelsToApplyCsvUri "https://example.com/csv/avm-github-labels.csv"
#>#Requires-PSEdition Core [CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$RepositoryName,
[Parameter(Mandatory = $false)]
[bool]$RemoveExistingLabels = $true,
[Parameter(Mandatory = $false)]
[bool]$UpdateAndAddLabelsOnly = $true,
[Parameter(Mandatory = $false)]
[bool]$CreateCsvLabelExports = $true,
[Parameter(Mandatory = $false)]
[string]$OutputDirectory = (Get-Location),
[Parameter(Mandatory = $false)]
[int]$GitHubCliLimit = 999,
[Parameter(Mandatory = $false)]
[string]$LabelsToApplyCsvUri = "https://azure.github.io/Azure-Verified-Modules/governance/avm-standard-github-labels.csv",
[Parameter(Mandatory = $false)]
[bool]$NoUserPrompts = $false
)
# Check if the GitHub CLI is installed $GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw"The GitHub CLI is not installed. Please install the GitHub CLI and try again." }
Write-Host "The GitHub CLI is installed..." -ForegroundColor Green
# Check if GitHub CLI is authenticated $GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI, `gh auth login`, and try again." }
Write-Host "Authenticated to GitHub..." -ForegroundColor Green
# Check if GitHub repository name is valid $GitHubRepositoryNameValid = $RepositoryName -match"^[a-zA-Z0-9-]+/[a-zA-Z0-9-]+$"if ($false -eq $GitHubRepositoryNameValid) {
throw"The GitHub repository name $RepositoryName is not valid. Please check the repository name and try again. The format must be <OrgName>/<RepoName>" }
# List GitHub repository provided and check it exists $GitHubRepository = gh repo view $RepositoryName
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubRepository -ForegroundColor Red
throw"The GitHub repository $RepositoryName does not exist. Please check the repository name and try again." }
Write-Host "The GitHub repository $RepositoryName exists..." -ForegroundColor Green
# PRE - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($RemoveExistingLabels -or $UpdateAndAddLabelsOnly) {
Write-Host "Getting the current GitHub repository (pre) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels -and $CreateCsvLabelExports -eq $true) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Pre-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (pre) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# Remove all pre-existing labels if -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labelsif ($null -ne $GitHubRepositoryLabels) {
$GitHubRepositoryLabelsJson = $GitHubRepositoryLabels | ConvertFrom-Json
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $false -and $UpdateAndAddLabelsOnly -eq $false) {
$RemoveExistingLabelsConfirmation = Read-Host "Are you sure you want to remove all $($GitHubRepositoryLabelsJson.Count) pre-existing labels from $($RepositoryName)? (Y/N)"if ($RemoveExistingLabelsConfirmation -eq"Y") {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($RemoveExistingLabels -eq $true -and $NoUserPrompts -eq $true -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Removing all pre-existing labels from $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
Write-Host "Removing label $($_.name) from $RepositoryName..." -ForegroundColor DarkRed
gh label delete -R $RepositoryName $_.name --yes
}
}
}
if ($null -eq $GitHubRepositoryLabels) {
Write-Host "No pre-existing labels to remove or not selected to be removed from $RepositoryName..." -ForegroundColor Magenta
}
# Check LabelsToApplyCsvUri is valid and contains a CSV content Write-Host "Checking $LabelsToApplyCsvUri is valid..." -ForegroundColor Yellow
$LabelsToApplyCsvUriValid = $LabelsToApplyCsvUri -match"^https?://"if ($false -eq $LabelsToApplyCsvUriValid) {
throw"The LabelsToApplyCsvUri $LabelsToApplyCsvUri is not valid. Please check the URI and try again. The format must be a valid URI." }
Write-Host "The LabelsToApplyCsvUri $LabelsToApplyCsvUri is valid..." -ForegroundColor Green
# Create AVM lables from the AVM labels CSV file stored on the web using the convertfrom-csv cmdlet $avmLabelsCsv = Invoke-WebRequest -Uri $LabelsToApplyCsvUri | ConvertFrom-Csv
# Check if the AVM labels CSV file contains the following columns: Name, Description, HEX $avmLabelsCsvColumns = $avmLabelsCsv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
$avmLabelsCsvColumnsValid = $avmLabelsCsvColumns -contains"Name"-and $avmLabelsCsvColumns -contains"Description"-and $avmLabelsCsvColumns -contains"HEX"if ($false -eq $avmLabelsCsvColumnsValid) {
throw"The labels CSV file does not contain the required columns: Name, Description, HEX. Please check the CSV file and try again. It contains the following columns: $avmLabelsCsvColumns" }
Write-Host "The labels CSV file contains the required columns: Name, Description, HEX" -ForegroundColor Green
# Create the AVM labels in the GitHub repository Write-Host "Creating/Updating the $($avmLabelsCsv.Count) AVM labels in $RepositoryName..." -ForegroundColor Yellow
$avmLabelsCsv | ForEach-Object {
if ($GitHubRepositoryLabelsJson.name -contains $_.name) {
Write-Host "The label $($_.name) already exists in $RepositoryName. Updating the label to ensure description and color are consitent..." -ForegroundColor Magenta
gh label create -R $RepositoryName "$($_.name)" -c $_.HEX -d $($_.Description) --force
}
else {
Write-Host "The label $($_.name) does not exist in $RepositoryName. Creating label $($_.name) in $RepositoryName..." -ForegroundColor Cyan
gh label create -R $RepositoryName "$($_.Name)" -c $_.HEX -d $($_.Description) --force
}
}
# POST - Get the current GitHub repository labels and export to a CSV file in the current directory or where -OutputDirectory specifies if set to a valid directory path and the directory exists or can be created if it does not exist alreadyif ($CreateCsvLabelExports -eq $true) {
Write-Host "Getting the current GitHub repository (post) labels for $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
if ($null -ne $GitHubRepositoryLabels) {
$csvFileNamePathPre = "$OutputDirectory\$($RepositoryName.Replace('/', '_'))-Labels-Post-$(Get-Date -Format FileDateTime).csv" Write-Host "Exporting the current GitHub repository (post) labels for $RepositoryName to $csvFileNamePathPre" -ForegroundColor Yellow
$GitHubRepositoryLabels | ConvertFrom-Json | Export-Csv -Path $csvFileNamePathPre -NoTypeInformation
}
}
# If -RemoveExistingLabels is set to $true and user confirms they want to remove all pre-existing labels check that only the avm labels exist in the repositoryif ($RemoveExistingLabels -eq $true -and ($RemoveExistingLabelsConfirmation -eq"Y"-or $NoUserPrompts -eq $true) -and $UpdateAndAddLabelsOnly -eq $false) {
Write-Host "Checking that only the AVM labels exist in $RepositoryName..." -ForegroundColor Yellow
$GitHubRepositoryLabels = gh label list -R $RepositoryName -L $GitHubCliLimit --json name,description,color
$GitHubRepositoryLabels | ConvertFrom-Json | ForEach-Object {
if ($avmLabelsCsv.Name -notcontains $_.name) {
throw"The label $($_.name) exists in $RepositoryName but is not in the CSV file." }
}
Write-Host "Only the CSV labels exist in $RepositoryName..." -ForegroundColor Green
}
Write-Host "The CSV labels have been created/updated in $RepositoryName..." -ForegroundColor Green
Module owners MUST test that child and extension resources and those Bicep or Terreform interface resources that are supported by their modules, are validated in E2E tests as per SNFR2 to ensure they deploy and are configured correctly.
These MAY be tested in a separate E2E test and DO NOT have to be tested in each E2E test.
Module owners MUST set the default resource name prefix for child, extension, and interface resources to the associated abbreviation for the specific resource as documented in the following CAF article Abbreviation examples for Azure resources, if specified and documented. This reduces the amount of input values a module consumer MUST provide by default when using the module.
For example, a Private Endpoint that is being deployed as part of a resource module, via the mandatory interfaces, MUST set the Private Endpoint’s default name to begin with the prefix of pep-.
Module owners MUST also provide the ability for these default names, including the prefixes, to be overridden via a parameter/variable if the consumer wishes to.
Furthermore, as per RMNFR2, Resource Modules MUST not have a default value specified for the name of the primary resource and therefore the name MUST be provided and specified by the module consumer.
The name provided MAY be used by the module owner to generate the rest of the default name for child, extension, and interface resources if they wish to. For example, for the Private Endpoint mentioned above, the full default name that can be overridden by the consumer, MAY be pep-<primary-resource-name>.
Tip
If the resource does not have a documented abbreviation in Abbreviation examples for Azure resources, then the module owner is free to use a sensible prefix instead.
Modules SHOULD implement unit testing to ensure logic and conditions within parameters/variables/locals are performing correctly. These tests MUST pass before a module version can be published.
Unit Tests test specific module functionality, without deploying resources. Used on more complex modules. In Bicep and Terraform these live in tests/unit.
Modules MUST use static analysis, e.g., linting, security scanning (PSRule, tflint, etc.). These tests MUST pass before a module version can be published.
There may be differences between languages in linting rules standards, but the AVM core team will try to close these and bring them into alignment over time.
Modules MUST implement idempotency end-to-end (deployment) testing. E.g. deploying the module twice over the top of itself.
Modules SHOULD pass the idempotency test, as we are aware that there are some exceptions where they may fail as a false-positive or legitimate cases where a resource cannot be idempotent.
For example, Virtual Machine Image names must be unique on each resource creation/update.
A module MUST have at least one owner recorded in the root metadata.json file’s owners array. Record every approved owner using bare individual handles or qualified handles for approved existing teams; children inherit that ownership. Changes require approval from either metadata code-owner team through the metadata review process.
Today this is only Microsoft FTEs, but everyone is welcome to contribute. The module just MUST be owned by a Microsoft FTE (today) so we can enforce and provide the long-term support required by this initiative.
Note
Module owners MUST obtain access through the Entra access package described in SNFR20.
In AVM there will be multiple different teams involved throughout the initiatives lifecycle and ongoing long-term support. These teams will be listed below alongside their definitions.
Important
Individuals can be members of multiple teams, at once, that are defined below.
Managing the AVM Solution: Leading and managing AVM from a technical standpoint, ensuring the maintenance and growth of the Public Bicep Registry’s repository and the Terraform Registry. Governing the lifecycle and support SLAs for all AVM modules, as well as providing overall governance and overseeing/facilitating the contribution process.
Testing and quality enforcement: Developing, operating and enforcing the test framework and related tooling with all its quality gates. Providing initial reviews for all modules, making sure all standardsΒ are met.
Documentation: Defining and refining principles, contribution and consumption guidelines, specifications and procedures related to AVM modules, maintaining and publishing all related documentation on the program’s public website.
Community Engagement: Organizing internal and external events, such as hackathons, office hours, community calls and training events for current and future module owners and contributors. Presenting in live events both publicly and internally; publishing blog posts and videos on YouTube, etc.
Security Enhancements: Facilitating the implementation and/or implementing security enhancements across all AVM repositories - through the WAF (Well-Architected Framework) framework.
Supporting Module Owners: Providing day-to-day support for module owners, helping troubleshoot and manage security fixes for orphaned modules.
Improving Processes and Gathering Insights: Improving automation for issue triage and management processes and lead the development of internal dashboards to gain insights into contribution and consumption metrics.
Undefined tasks: Anything else not defined below for another team or in the RACI π
The team includes both technical and non-technical team members who are all Microsoft FTEs.
Module Owners
Important
Today, module owners MUST be Microsoft FTEs. This is to ensure that within AVM the long-term support for each module can be upheld and honored.
Module owners are responsible for:
Initial module development
Module Maintenance (proactive & reactive)
Regular updates to ensure compatibility with the latest Azure services (including supporting new API versions and referencing the newest AVM modules when applicable).
WAF Reliability & Security alignment
Bug fixes, security patches and feature improvements.
Ensuring long term compliance with AVM specifications
Implementing and improving automated testing and validation tools for new modules.
Improving documentation through rich examples.
Ongoing module support
Module Issue/Pull Request Triage & Resolution
Module Feature Request Triage & Additions
Managing additional module contributors
Ideally there SHOULD be at least 2 module owners per module. Every approved owner MUST be recorded in the root metadata.json file’s owners array through the metadata review process.
Module Contributors can be anyone in any organization. However, they must be an active contributor and supporting the Module Owners.
Module Contributors are responsible for:
Assisting the Module Owners with their responsibilities
Contributing to a module does not require a per-module GitHub team or module owner access. Contributors work in forks and submit changes for review; module owners obtain access as described in SNFR20.
The Azure Bicep & Terraform Product Groups are responsible for:
Backup/Additional support for orphaned modules to the AVM Core Team
Providing inputs and feedback on AVM
Taking on feedback and feature requests on their products, Bicep & Terraform, from AVM usage
Note
We are investigating working with all Azure Product Groups as a future investment area that they take on ownership, or contribute to, the AVM modules for their service/product.
RACI
RACI Definition
R = Responsible β Those who do the work to complete the task/responsibility.
A = Accountable β The one answerable for the correct and thorough completion of the task. There must be only one accountable person per task/responsibility. Typically has ‘sign-off’.
C = Consulted β Those whose opinions are sought.
I = Informed β Those who are kept up to date on progress.
The below table defines a RACI to be adopted by all parties referenced in the table to ensure customers can trust these modules and can consume and contribute to the initiative at scale.
Action/Task/Responsibility
Module Owners
Module Contributors
AVM Core Team
Product Groups
Notes
Build/Construct an AVM Module
R, A
R, C
C, I
I
Publish a Bicep AVM Module to the Bicep Public Registry
R, A
C, I
C, I
I
Publish a Terraform AVM Module to the Terraform Registry
A
C, I
R
I
Publishing is managed by the AVM core team via HCP Terraform
Manage and maintain tooling/testing frameworks pertaining to module quality
C, I
C, I
R, A
C, I
Manage/run the AVM central backlog (module proposals, orphaned modules, test enhancements, etc.)
Module owners MAY cross-references other modules to build either Resource or Pattern modules. However, they MUST be referenced only by a HashiCorp Terraform registry reference to a pinned version e.g.,
Authors SHOULD NOT output entire resource objects as these may contain sensitive outputs and the schema can change with API or provider versions. Instead, authors SHOULD output the computed attributes of the resource as discreet outputs. This kind of pattern protects against provider schema changes and is known as an anti-corruption layer.
Remember, you SHOULD NOT output values that are already inputs (other than name).
E.g.,
# Resource output, computed attribute.
output"foo" {
description = "MyResource foo attribute"value = azapi_resource.myresource.output.properties.foo}# Resource output for resources that are deployed using `for_each`. Again only computed attributes.
output"childresource_foos" {
description = "MyResource children's foo attributes"value = {
forkey, valueinazapi_resource.mychildresource:key => value.output.properties.foo }
}# Output of a sensitive attribute
output"bar" {
description = "MyResource bar attribute"value = azapi_resource.myresource.output.properties.barsensitive = true}
Every new AVM Terraform module β resource, pattern, or utility β MUST use Azure/azapi for every Azure control-plane resource and every data-plane operation supported by AzAPI. The AzureRM provider is permitted only for the unsupported data-plane/non-ARM API exception defined below.
Authors MUST only use the following Azure providers, and versions, in their modules:
provider
min version
max version
permitted use
Azure/azapi
>= 2.12
< 3.0
All Azure control-plane resources and supported data-plane operations
hashicorp/azurerm
>= 4.0
< 5.0
Only a specific unsupported data-plane/non-ARM API operation under the exception below
Pattern modules MAY also use other Microsoft-maintained providers when required by the pattern. Examples include integrations/github, microsoft/azuredevops, microsoft/fabric, and microsoft/msgraph. Each provider MUST be declared with minimum and maximum major version constraints as required by TFNFR26.
Resource and utility modules MUST NOT use these additional providers. Except for the narrow AzureRM exception below, third-party providers MUST NOT be used by any AVM Terraform module, regardless of module classification.
Note
The AzAPI floor is 2.12 because TFFR8 requires every module to expose the ignore_body_changes argument, which was introduced in Azure/azapi v2.12.0. Modules pinned below that version will fail to plan because the argument is absent from the provider schema.
This prohibition applies to every Terraform configuration shipped with the module, including:
The root module and all submodules.
Every configuration under examples/, including examples executed as end-to-end tests.
Terraform tests, test fixtures, and supporting setup configurations.
Terraform snippets in _header.md, _footer.md, generated documentation, and other repository documentation.
Supporting control-plane resources needed by an example, end-to-end test, or fixture MUST use AzAPI. AzureRM MUST NOT be used for resource groups, role assignments, monitoring resources, networking, or any other ARM control-plane resource.
Exception β unsupported data-plane/non-ARM API operations
An AVM Terraform module that is otherwise built with AzAPI MAY declare the AzureRM provider only for a specific data-plane or non-ARM API operation whose functionality is genuinely unavailable through azapi_data_plane_resource, azapi_resource, azapi_resource_action, or azapi_update_resource. This exception is intended for isolated operations such as a data-plane resource whose AzureRM implementation calls a service endpoint rather than Azure Resource Manager. It is not a general fallback for a missing or inconvenient AzAPI schema. Every azurerm_* block MUST independently satisfy this exception; one permitted block does not authorize any other AzureRM use.
Where this exception applies, the module MUST:
Continue to declare and use AzAPI as its required, primary Azure provider.
Scope every azurerm_* resource or data source to the exact unsupported data-plane/non-ARM operation.
Pin the AzureRM provider to ~> 4.0 in required_providers.
Use AzAPI for every control-plane resource and every data-plane operation that AzAPI supports.
Document the exception in the module’s README.md, including each azurerm_* block, the data-plane/non-ARM API it wraps, why AzAPI cannot implement it, and the upstream AzAPI issue or pull request tracking support.
Replace the azurerm_* block with AzAPI in the next module release after the required capability ships.
Examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets MAY configure or exercise AzureRM only when required by that exact permitted data-plane operation. All supporting control-plane resources in those surfaces MUST use AzAPI.
This exception MUST NOT be used to:
Implement any ARM control-plane resource.
Avoid AzAPI because its body schema is more verbose or less convenient.
Avoid raising an AzAPI capability gap for an unsupported control-plane operation.
Side-step any AzAPI-specific specification that applies to the module’s AzAPI resources.
The azurerm remote state backend and the final segment of a published Terraform Registry module address, such as /azurerm in an existing AVM module source, are names and are not provider declarations. They MAY appear where required for state storage or to reference an existing published AVM module. A dependency’s provider implementation is governed by that dependency’s own repository; its Registry address does not by itself justify a direct hashicorp/azurerm declaration or azurerm_* block in the consuming module repository. Any such direct use MUST independently satisfy the data-plane exception above.
Authors MUST use the required_providers block in their module to enforce the provider versions.
Authors MUST specify the response_export_values argument when using the AzAPI provider:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US"response_export_values = [] # must be specified, even if empty
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
If you require read-only properties to be returned from the resource, you SHOULD include them as follows:
resource"azapi_resource""example" {
type = "Microsoft.Example/resourceType@2021-01-01"name = "example-resource"location = "West US" # Example as a list:
response_export_values = ["properties.readOnlyProperty"] # Example as a map:
# response_export_values = {
# read_only_property = "properties.readOnlyProperty"
# }
body = {
properties = {
exampleProperty = "exampleValue" }
}
}
output"read_only_property" { # Example if response_export_values is a list:
value = azapi_resource.example.output.properties.readOnlyProperty # Example if response_export_values is a map:
# value = azapi_resource.example.output.read_only_property
}
Authors MUST omit replace_triggers_refs when no body properties require replacement. When one or more body properties require replacement, authors MUST set replace_triggers_refs to a non-empty static list of JMESPath expressions that identify those paths.
Each expression MUST be valid JMESPath syntax, non-blank, and unique within the list. Do not include name or location, as AzAPI already replaces the resource when either changes. When the resource body is statically evaluable, every declared expression MUST resolve against that body.
This is to ensure that changes to properties that require replacement of the resource are handled correctly by Terraform. Authors remain responsible for identifying every property that actually requires replacement. Current Bicep-generated schemas do not reliably preserve whether a property is create-only or updateable, so the rule validates declared paths but cannot prove that the list is semantically complete.
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, authors MUST NOT hard-code the type argument of a supported AzAPI resource inline.
Instead, every AzAPI resource type string used by the module MUST be sourced from a single object variable named resource_types.
resource_types keys vs Terraform resource labels
These are two unrelated concepts and the spec treats them independently:
Keys in var.resource_types name the AzAPI resource type and are derived from the ARM type by the naming rule below. They appear on the right of an assignment as the value of the type argument.
Terraform resource labels (e.g. azapi_resource.this) name the graph node and govern how the resource is referenced elsewhere in HCL. The primary resource label MUST be this, per TFRMNFR2.
A typical primary-resource declaration therefore reads:
resource"azapi_resource""this" { # label per TFRMNFR2
type = var.resource_types.example_widgets # key per the naming rule below
# ...
}
this and example_widgets describe different things and are derived by different rules. They MUST NOT be made to coincide β this is never a valid resource_types key.
Key naming
Each resource_types key (at every level of nesting) MUST be the snake_case form of the ARM resource type, with the Microsoft. prefix dropped:
Drop the Microsoft. prefix.
Render the provider namespace as a single lowercase token β do not split internal camelCase (KeyVault β keyvault, DocumentDB β documentdb, EventHub β eventhub).
Convert each resource path segment after the provider from camelCase to snake_case (virtualNetworks β virtual_networks, roleAssignments β role_assignments).
Join the provider token and each path segment with _.
ARM type
Key
Microsoft.Example/widgets
example_widgets
Microsoft.Example/widgets/parts
example_widgets_parts
Microsoft.Example/widgets/parts/components
example_widgets_parts_components
Microsoft.Authorization/locks
authorization_locks
Microsoft.Authorization/roleAssignments
authorization_role_assignments
Microsoft.Insights/diagnosticSettings
insights_diagnostic_settings
Microsoft.KeyVault/vaults/secrets
keyvault_vaults_secrets
Microsoft.Network/virtualNetworks/subnets
network_virtual_networks_subnets
The rule is deterministic so consumers, lint checks and tooling can derive the expected key for any ARM type without consulting the module source. Authors MUST NOT invent shorter aliases (e.g. widgets instead of example_widgets).
Variable shape
The resource_types variable MUST:
Be a single object({...}) (not a map(string)) so typos at call sites error at plan time and per-key defaults are visible in the variable declaration.
Default the variable itself to {} so consumers only need to supply the keys they wish to override.
Be nullable = false.
Declare one optional(string, "<provider>/<resource>@<api-version>") field for every AzAPI resource the module itself declares, defaulting each to the latest API version the module has been tested against. The default MUST be a stable (non-preview) API version unless the module’s primary resource only ships a preview API.
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource and therefore exposes its own resource_types variable (see TFRMNFR1). The shape of the nested object MUST match that submodule’s own resource_types variable exactly. The parent MUST NOT repeat the submodule’s defaults β the inner string attributes are declared as optional(string) (no default) so the submodule remains the single source of truth for its own tested API versions.
Document every field in the variable’s description.
Cascading to submodules
Because the nested slot in the parent mirrors the submodule’s variable, the parent cascades the slot through unchanged:
No renaming, repacking, or null filtering is required. When the consumer omits a key or sets it explicitly to null, Terraform substitutes the default declared on the owning module’s variable (per Terraform’s optional-attribute semantics).
The rationale for the variable is to let consumers:
Target sovereign clouds (e.g., Azure US Government, Azure China) where older API versions may be the latest available.
Opt into a newer preview API version without waiting for a module release.
Pin a specific API version for compliance or reproducibility reasons.
Nesting submodule slots inside the parent’s resource_types (rather than flattening every AzAPI resource into a single top-level namespace):
Keeps each module’s defaults co-located with the resource it owns.
Lets a submodule add or rename its own resources without forcing a breaking change on parent-module consumers who never touched those keys.
Makes the override surface mirror the actual module tree β a consumer looking at the parent’s variable can see, in shape, every resource managed beneath it.
Example β root, child and grandchild
A module managing Microsoft.Example/widgets, with a parts submodule for Microsoft.Example/widgets/parts, which in turn instantiates a component sibling submodule for Microsoft.Example/widgets/parts/components (per TFRMNFR1):
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the retry and timeouts blocks of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code values inline that the consumer cannot override.
To meet this requirement, the module MUST expose two variables:
retry β an object variable controlling the AzAPI retry block.
timeouts β an object variable controlling the AzAPI timeouts block.
Diff suppression via the AzAPI ignore_body_changes argument is covered separately by TFFR8, because its values are scoped to a single resource’s body and therefore MUST NOT be cascaded to submodules unchanged.
Both variables:
MAY define module-level defaults (e.g., a default error_message_regex such as "ScopeLocked" for resources that race with lock removal, or a default delete = "5m").
MUST allow the consumer to override the defaults β either by supplying a non-null value at the variable level, or by allowing per-field overrides through optional(...) attributes.
MUST be applied to every azapi_resource (and equivalent AzAPI resources) declared by the module.
MUST cascade to applicable submodules β the parent module’s retry and timeouts values MUST be passed through to each submodule it instantiates that directly declares a supported AzAPI resource (see TFRMNFR1). Submodules MAY additionally expose per-item overrides for cases where individual resources need different settings.
variable"retry" {
type = object({
error_message_regex = optional(list(string))
interval_seconds = optional(number)
max_interval_seconds = optional(number)
})
default = nulldescription = <<DESCRIPTIONRetry configuration applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (no custom retry).
- `error_message_regex` - (Optional) A list of regex patterns matching error messages that trigger a retry.
- `interval_seconds` - (Optional) Initial interval between retries in seconds.
- `max_interval_seconds` - (Optional) Maximum interval between retries in seconds.
See <https://registry.terraform.io/providers/Azure/azapi/latest/docs/resources/resource#retry> for full semantics.
DESCRIPTION}
variable"timeouts" {
type = object({
create = optional(string)
read = optional(string)
update = optional(string)
delete = optional(string)
})
default = nulldescription = <<DESCRIPTIONDefault per-operation timeouts applied to every supported AzAPI resource declared by the module and its applicable submodules. Defaults to `null` (provider defaults). Each value is a Go duration string (e.g. `30m`, `1h`).
- `create` - (Optional) Timeout for create operations.
- `read` - (Optional) Timeout for read operations.
- `update` - (Optional) Timeout for update operations.
- `delete` - (Optional) Timeout for delete operations.
DESCRIPTION}
resource"azapi_resource""this" {
type = var.resource_types.example_widgetsname = var.nameparent_id = var.parent_idbody = { /* ... */ } # `retry` is an attribute on `azapi_resource`, so the variable can be
# assigned directly. `timeouts` is a block, so a `dynamic "timeouts"`
# block is required to honor the variable's `null` default.
retry = var.retrydynamic"timeouts" {
for_each = var.timeouts ==null? [] : [var.timeouts]
content {
create = timeouts.value.createread = timeouts.value.readupdate = timeouts.value.updatedelete = timeouts.value.delete }
}
response_export_values = []
}
module"child" {
source = "./modules/child" # Cascade retry and timeouts to the submodule.
retry = var.retrytimeouts = var.timeouts # ...other arguments...
}
TFFR6, TFFR7, and TFFR8 apply independently to each module and submodule scope. Together they require resource_types, retry, timeouts, and ignore_body_changes only when that scope directly declares at least one managed resource block of a supported AzAPI type:
azapi_resource
azapi_data_plane_resource
azapi_resource_action
azapi_update_resource
A provider declaration alone, AzAPI data sources alone (including data "azapi_client_config" and data "azapi_resource"), or supported AzAPI resources declared only inside a child module do not trigger these requirements in the parent scope. Each submodule is evaluated independently and triggers when it directly declares a supported block. A count or for_each condition does not exempt a directly declared block.
Within an applicable scope, the ignore_body_changes argument of every supported AzAPI resource MUST be configurable by the consumer. Authors MUST NOT hard-code an inline list that the consumer cannot override, and MUST NOT omit the argument.
To meet this requirement, every applicable module or submodule (see TFRMNFR1) MUST expose a variable named ignore_body_changes.
ignore_body_changes lets a consumer suppress plan diffs for a set of body paths that are mutated outside Terraform (for example tags applied by Azure Policy, or an autoscaler adjusting a capacity property). It is the supported fallback for lifecycle.ignore_changes when the paths must be derived from variables, locals or other non-static values, which lifecycle blocks cannot accept.
Without this variable a consumer has no way to reach the argument, because lifecycle.ignore_changes cannot be applied to a resource from outside the module that declares it. This is exactly the same problem that TFFR7 solves for retry and timeouts.
The module’s Azure/azapi constraint in required_providersMUST allow v2.12.0 or later, which is the release that introduces the argument (see TFFR3).
A consumer supplying a non-empty value MUST be running Terraform 1.11 or later. Modules MUST NOT raise their required_version floor for this reason alone (see TFNFR25); instead they MUST emit null when the list is empty so that consumers on earlier Terraform versions who do not use the feature are unaffected. See Applying the variable.
Important
Because the value is held in provider-private state, a change to ignore_body_changes only takes effect after an apply. A consumer who adds a path will still see the pending diff for that path in the same plan, and a consumer who removes a path will not see the suppressed diff reappear until the next plan. Module documentation SHOULD call this out.
Variable shape
Unlike retry and timeouts, which are resource-agnostic and therefore cascade unchanged, ignore_body_changes values are dot-notation paths into one specific resource’sbody. A path such as properties.addressSpace is meaningful only for the resource that owns it, so passing a parent’s list straight through to a submodule would apply meaningless paths to a different resource.
The variable is therefore scoped per resource and per submodule, using exactly the same shape and key-naming rule as resource_types (TFFR6).
The ignore_body_changes variable MUST:
Be a single object({...}) (not a map(list(string))) so typos at call sites error at plan time and the full override surface is visible in the variable declaration.
Default the variable itself to {} and be nullable = false, per TFNFR20 and TFNFR21.
Declare one optional(list(string), []) field for every AzAPI resource the module itself declares, keyed by the snake_case form of the ARM resource type with the Microsoft. prefix dropped β the identical key used in resource_types (for example Microsoft.Example/widgets β example_widgets).
Declare one nested optional(object({...}), {}) field for every submodule the module instantiates that directly declares a supported AzAPI resource, keyed by that submodule’s primary ARM resource type. The shape of the nested object MUST match that submodule’s own ignore_body_changes variable exactly, and the parent MUST cascade the slot through unchanged.
Document every field in the variable’s description, including what ignore_body_changes does, that paths use dot notation, and that changes take effect only after an apply.
Module owners MAY ship module-level defaults where the resource is known to be mutated outside Terraform. To do so, supply the default inside the optional(list(string), [...]) wrapper. Consumers MUST still be able to override any individual field, and a module-level default MUST NOT be used to work around a bug that belongs in the module body.
Modules MAY additionally expose per-item overrides on the collection variable that drives a for_each submodule, for cases where individual instances need different paths. Where they do, the per-item value MUST take precedence over the shared slot.
Path syntax
Values are dot-notation paths relative to the resource’s body, for example tags or properties.sku.name. Each element MUST be a non-empty string.
Individual list items MUST NOT be targeted (there is no index syntax) β ignore the entire list property instead.
Authors and consumers MUST understand that an ignored path is not merely hidden from the plan: configuration changes at that path are not sent to Azure until the path is removed from the list.
Applying the variable
ignore_body_changes is an attribute (not a block) on azapi_resource, so the relevant field of the variable is assigned directly. The assignment MUST collapse an empty list to null so that the write-only argument is absent when the feature is unused:
ID: TFFR9 - Category: Inputs/Outputs - AzAPI - Tag Propagation
Applicability
This requirement applies independently to every root module and submodule that directly declares a managed AzAPI resource. The avm_azapi_resource_tags_required rule uses its embedded AVM-generated capability snapshot to classify the resource type’s tags property as writable, read-only, or unsupported.
Requirement
For every resource type with a statically writable tags property, the resource MUST expose consumer-settable tags through the standard tags interface and set the tags argument. A direct assignment remains valid for modules that use only the module-wide fallback:
resource"azapi_resource""this" {
type = var.resource_types.example_widgetstags = var.tags}
When the module exposes the optional resource_tags interface, a non-null override for the Terraform resource block label MUST replace var.tags completely. An omitted or null override MUST inherit var.tags, and an empty map MUST remain an intentional empty replacement. The implementation MUST NOT merge the fallback and override maps.
Resource override keys identify Terraform resource block labels, not ARM resource types. Submodule overrides MUST use the deterministic typed resource_tags.modules.<module_label> shape defined by the standard tags interface. The separate resources and modules namespaces MUST resolve identical resource and module labels without ambiguity.
For every resource type with a statically read-only or unsupported tags property, the resource MUST NOT set a tags argument. Do not use a conditional, dynamic value, or an empty map to force tags onto these types.
The validation skips dynamic or otherwise unevaluable type expressions to avoid false positives. Authors SHOULD keep resource types statically resolvable through var.resource_types as required by TFFR6.
The embedded AVM-generated capability snapshot, rather than a hand-maintained module allowlist or an AzAPI import, is the authority for this classification.
Where descriptions for variables and outputs spans multiple lines. The description MAY provide variable input examples for each variable using the HEREDOC format and embedded markdown.
Example:
variable"my_complex_input" {
type = map(object({
param1 = stringparam2 = optional(number, null)
}))
description = <<DESCRIPTION A complex input variable that is a map of objects.
Each object has two attributes:
- `param1`: A required string parameter.
- `param2`: (Optional) An optional number parameter.
Example Input:
```terraform
my_complex_input = {
"object1" = {
param1 = "value1"
param2 = 2
}
"object2" = {
param1 = "value2"
}
}
```
DESCRIPTION }
Sometimes we need to ensure that the resources created are compliant to some rules at a minimum extent, for example a subnet has to be connected to at least one network_security_group. The user SHOULD pass in a security_group_id and ask us to make a connection to an existing security_group, or want us to create a new security group.
The disadvantage of this approach is if the user create a security group directly in the root module and use the id as a variable of the module, the expression which determines the value of count will contain an attribute from another resource, the value of this very attribute is “known after apply” at plan stage. Terraform core will not be able to get an exact plan of deployment during the “plan” stage.
For this kind of parameters, wrapping with object type is RECOMMENDED:
variable"security_group" {
type:object({
id = string })
default = null}
The advantage of doing so is encapsulating the value which is “known after apply” in an object, and the object itself can be easily found out if it’s null or not. Since the id of a resource cannot be null, this approach can avoid the situation we are facing in the first example, like the following:
ID: TFNFR14 - Category: Inputs - Not allowed variables
Since Terraform 0.13, count, for_each and depends_on are introduced for modules, module development is significantly simplified. Module’s owners MUST NOT add variables like enabled or module_depends_on to control the entire module’s operation. Boolean feature toggles are acceptable however.
variable used as feature switches SHOULD apply a positive statement, use xxx_enabled instead of xxx_disabled. Avoid double negatives like !xxx_disabled.
Please use xxx_enabled instead of xxx_disabled as name of a variable.
ID: TFNFR17 - Category: Code Style - Variables with Descriptions
The target audience of description is the module users.
For a newly created variable (Eg. variable for switching dynamic block on-off), it’s descriptionSHOULD precisely describe the input parameter’s purpose and the expected data type. descriptionSHOULD NOT contain any information for module developers, this kind of information can only exist in code comments.
For object type variable, description can be composed in HEREDOC format:
variable"kubernetes_cluster_key_management_service" {
type:object({
key_vault_key_id = stringkey_vault_network_access = optional(string)
})
default = nulldescription = <<DESCRIPTION- `key_vault_key_id` - (Required) Identifier of Azure Key Vault key. See [key identifier format](https://learn.microsoft.com/en-us/azure/key-vault/general/about-keys-secrets-certificates#vault-name-and-object-name) for more details. When Azure Key Vault key management service is enabled, this field is required and must be a valid key identifier. When `enabled` is `false`, leave the field empty.
- `key_vault_network_access` - (Optional) Network access of the key vault Network access of key vault. The possible values are `Public` and `Private`. `Public` means the key vault allows public access from all networks. `Private` means the key vault disables public access and enables private link. Defaults to `Public`.
DESCRIPTION}
You MUST remove all trailing whitespace so that terraform-docs renders the readme properly.
ID: TFNFR19 - Category: Code Style - Sensitive Data Variables
If variable’s type is object and contains one or more fields that would be assigned to a sensitive argument, then this whole variableSHOULD be declared as sensitive = true, otherwise you SHOULD extract sensitive field into separated variable block with sensitive = true.
Nullable SHOULD be set to false for collection values (e.g. sets, maps, lists) when using them in loops. However for scalar values like string and number, a null value MAY have a semantic meaning and as such these values are allowed.
MAPOTF removes redundant explicit nullable = true. That formatting cleanup does not change this requirement and does not imply that a collection is semantically safe to make nullable.
nullable = trueMUST be avoided. MAPOTF removes redundant explicit nullable = true; this cleanup is distinct from, and does not satisfy, the requirement to set nullable = false where a meaningful zero value exists.
Variables MUST be declared with nullable = false whenever the variable’s type has a meaningful zero value ({} for objects/maps, [] for lists/sets, "" for strings where empty has the same meaning as absent, etc.). Consumers should signal “no value” by omitting the input, not by explicitly passing null.
Exception β behavior-toggle inputs
A small, well-defined class of inputs MAY keep the implicit nullable = true (i.e. default = null) where null carries a distinct semantic meaning of “no override β use the underlying provider/AVM defaults”, and where representing that state with the type’s zero value would be ambiguous or wrong. Examples include:
var.retry and var.timeouts (per TFFR7) β null means “do not emit a retry/timeouts block; use the AzAPI provider defaults”.
var.lock (per the AVM lock interface) β null means “do not create a management lock”.
Optional sub-objects that toggle whole feature blocks on/off, where {} would be indistinguishable from “feature enabled with all defaults”.
Where this exception applies, the variable MUST:
Use default = null (the implicit nullable = true is permitted only for this purpose).
State explicitly in its description what null means.
Be consumed with a null-aware pattern (e.g. count = var.lock != null ? 1 : 0, or dynamic "timeouts" { for_each = var.timeouts == null ? [] : [var.timeouts] }).
This exception does not extend to required inputs, to collection-shaped inputs (TFNFR20), or to nested attributes inside an object β those MUST use nullable = false and the type’s zero value.
variable"example_map" {
type =map(string)
default = {}
description ="An example map variable with an empty default value." sensitive =true}
Bad example:
variable"example_string" {
type =string default ="sensitive_value" description ="An example string variable with a sensitive default value." sensitive =true}
Sometimes we will find names for some variable are not suitable anymore, or a change SHOULD be made to the data type. We want to ensure forward compatibility within a major version, so direct changes are strictly forbidden. The right way to do this is move this variable to an independent deprecated_variables.tf file, then redefine the new parameter in variable.tf and make sure it’s compatible everywhere else.
Deprecated variableMUST be annotated as DEPRECATED at the beginning of the description, at the same time the replacement’s name SHOULD be declared. E.g.,
variable"enable_network_security_group" {
type = stringdefault = nulldescription = "DEPRECATED, use `network_security_group_enabled` instead; Whether to generate a network security group and assign it to the subnet. Changing this forces a new resource to be created."}
A cleanup of deprecated_variables.tfSHOULD be performed during a major version release.
The terraform.tf file MUST only contain one terraform block.
The first line of the terraform block MUST define a required_version property for the Terraform CLI. The standard Terraform TFLint plugin validates the requirement; MAPOTF keeps it first.
The required_version property MUST include a constraint on the minimum version of the Terraform CLI. Previous releases of the Terraform CLI can have unexpected behavior.
The required_version property MUST include a constraint on the maximum major version of the Terraform CLI. Major version releases of the Terraform CLI can introduce breaking changes and MUST be tested.
The required_version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
ID: TFNFR26 - Category: Code Style - Providers in required_providers
The terraform block in terraform.tfMUST contain the required_providers block.
Each provider used directly in the module MUST be specified with the source and version properties. The standard Terraform TFLint plugin validates the used-provider source and version requirements. MAPOTF sorts the required_providers entries alphabetically.
Do not add providers to the required_providers block that are not directly required by this module. If submodules are used then each submodule SHOULD declare its requirements in its own terraform.tf file.
The source property MUST be in the format of namespace/name. If this is not explicitly specified, it can cause failure.
The version property MUST include a constraint on the minimum version of the provider. Older provider versions may not work as expected.
The version property MUST include a constraint on the maximum major version. A provider major version release may introduce breaking change, so updates to the major version constraint for a provider MUST be tested.
The version property constraint SHOULD use the ~> #.# or the >= #.#.#, < #.#.# format.
Note: You can read more about Terraform version constraints in the documentation.
By rule, every published AVM module and submodule MUST NOT declare a provider block. Provider configuration belongs exclusively to the consuming root module.
When a module requires an alternate provider instance, it MUST declare that alias through configuration_aliases in terraform.required_providers and the consumer MUST pass the configured alias through the module’s providers map. A provider block containing only alias is not permitted in an AVM module.
Module owners MUST set a branch protection policy on their GitHub Repositories for AVM modules against their default branch, typically main, to do the following:
Requires a Pull Request before merging
Require approval of the most recent reviewable push
Dismiss stale pull request approvals when new commits are pushed
Require linear history
Prevents force pushes
Not allow deletions
Require CODEOWNERS review
Do not allow bypassing the above settings
Above settings MUST also be enforced to administrators
Tip
If you use the template repository as mentioned in the contribution guide, the above will automatically be set.
Sometimes we notice that the name of certain output is not appropriate anymore, however, since we have to ensure forward compatibility in the same major version, its name MUST NOT be changed directly. It MUST be moved to an independent deprecated_outputs.tf file, then redefine a new output in output.tf and make sure it’s compatible everywhere else in the module.
A cleanup SHOULD be performed to deprecated_outputs.tf and other logics related to compatibility during a major version upgrade.
ID: TFNFR31 - Category: Code Style - locals.tf for Locals Only
In locals.tf, file we could declare multiple locals blocks, but only locals blocks are allowed.
You MAY declare locals blocks next to a resource block or data block for some advanced scenarios, like making a fake module to execute some light-weight tests aimed at the expressions.
This specification applies only to existing legacy modules that still use AzureRM while they are being migrated. It does not apply to a new module that uses AzureRM solely for the narrow unsupported data-plane/non-ARM API exception in TFFR3, because that exception does not permit AzureRM resource-group management.
In a legacy AzureRM module, the prevent_deletion_if_contains_resources provider setting SHOULD be set to false until the module is migrated. Azure Policy remediation can add resources during a test run, and the provider’s default behavior can then prevent cleanup of the test resource group.
newres is a command-line tool that generates Terraform configuration files for a specified resource type. It automates the process of creating variables.tf and main.tf files, making it easier to get started with Terraform and reducing the time spent on manual configuration.
Module owners MAY use newres when they’re trying to add new resource block, attribute, or nested block. They MAY generate the whole block along with the corresponding variable blocks in an empty folder, then copy-paste the parts they need with essential refactoring.
ID: TFNFR38 - Category: Inputs/Outputs - Resource ID Variable Validation
Every input variable (or nested attribute) that holds an Azure ARM resource ID MUST be validated using the AzAPI provider-defined function provider::azapi::parse_resource_id, called with a literal string naming the expected resource type, and wrapped in can(...).
Hand-rolled regex, startswith, length, or split checks MUST NOT be used to validate resource IDs. The provider function knows the canonical ARM ID grammar for every resource type, is fixed in lockstep with the provider, and produces a single consistent error model β including for IDs whose grammar contains anomalies (such as classic resources, extension resources, or scope-based IDs).
This rule covers, but is not limited to:
Top-level scope variables such as parent_id (see TFRMFR1).
Variables that reference other Azure resources by ID (e.g. subnet_resource_id, key_vault_resource_id, workspace_resource_id, private_dns_zone_resource_ids, user_assigned_resource_ids).
Nested attributes inside object, map(object), set(object), or list(object) types that hold resource IDs.
Rules
The resource type passed to parse_resource_idMUST be a literal string (e.g. "Microsoft.Network/virtualNetworks/subnets"). It MUST NOT be a reference to another variable, local, or expression. This keeps each validation block self-contained and avoids requiring cross-variable validation.
For optional / nullable variables, the validation MUST short-circuit on null (e.g. var.x == null || can(provider::azapi::parse_resource_id("...", var.x))) so that callers omitting the value do not trip validation.
For collection-valued variables (set(string), list(string), map(string)), the validation MUST iterate the collection with alltrue([for v in ... : can(...)]).
For nested attributes within object types, the validation MUST iterate the parent collection (or reference the object directly) and validate each nested resource ID, again handling null for optional nested attributes.
Where a variable can legitimately hold IDs of more than one resource type (rare β e.g. marketplace_partner_resource_id in the diagnostic-settings interface), this rule does not apply and the variable SHOULD be left without resource-ID validation rather than validated against a single arbitrary type.
Examples
A required, single-value resource ID:
variable"key_vault_resource_id" {
type = stringnullable = falsevalidation {
condition = can(provider::azapi::parse_resource_id("Microsoft.KeyVault/vaults", var.key_vault_resource_id))
error_message = "`key_vault_resource_id` must be a valid Azure Key Vault resource ID." }
description = "The resource ID of the Key Vault that holds the customer-managed key."}
An optional, single-value resource ID:
variable"workspace_resource_id" {
type = stringdefault = nullnullable = truevalidation {
condition = var.workspace_resource_id ==null|| can(provider::azapi::parse_resource_id("Microsoft.OperationalInsights/workspaces", var.workspace_resource_id))
error_message = "`workspace_resource_id` must be a valid Log Analytics workspace resource ID, or `null`." }
description = "The resource ID of the Log Analytics workspace to send diagnostics to."}
A collection of resource IDs:
variable"user_assigned_resource_ids" {
type = set(string)
default = []
nullable = falsevalidation {
condition = alltrue([
foridin var.user_assigned_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.ManagedIdentity/userAssignedIdentities", id))
])
error_message = "Each entry in `user_assigned_resource_ids` must be a valid user-assigned managed identity resource ID." }
description = "A set of user-assigned managed identity resource IDs to attach to the resource."}
A nested resource ID inside a map(object(...)):
variable"private_endpoints" {
type = map(object({
subnet_resource_id = stringprivate_dns_zone_resource_ids = optional(set(string), []) # ...other attributes...
}))
default = {}
nullable = falsevalidation {
condition = alltrue([
for_, vin var.private_endpoints: can(provider::azapi::parse_resource_id("Microsoft.Network/virtualNetworks/subnets", v.subnet_resource_id))
])
error_message = "Each `private_endpoints[*].subnet_resource_id` must be a valid subnet resource ID." }
validation {
condition = alltrue(flatten([
for_, vin var.private_endpoints: [
foridinv.private_dns_zone_resource_ids: can(provider::azapi::parse_resource_id("Microsoft.Network/privateDnsZones", id))
]
]))
error_message = "Each entry in `private_endpoints[*].private_dns_zone_resource_ids` must be a valid private DNS zone resource ID." }
}
Notes
The rule applies regardless of whether the resource ID is required or optional, single-valued or collection-valued, top-level or nested.
parse_resource_id errors when (a) the input is not a well-formed ARM ID, or (b) the input does not parse as the supplied resource type. Wrapping in can(...) converts both failure modes into a single boolean suitable for a validation block’s condition.
This rule supersedes any older guidance suggesting startswith(var.x, "/") or hand-written regex for resource ID validation.
ID: TFNFR39 - Category: Code Style - Standard File Layout
Every Terraform AVM module (root module and every submodule) MUST organize its top-level Terraform code into the following files at the module’s root directory:
File
Required
Contents
terraform.tf
MUST
The single terraform { β¦ } block β required_version, required_providers, and any backend configuration (root module only). Provider configuration blocks MUST NOT appear here.
variables.tf
MUST
All variable blocks for the module. MAY be split into additional variables.<topic>.tf files (see below).
outputs.tf
MUST
All output blocks for the module. MAY be split into additional outputs.<topic>.tf files (see below).
main.tf
MUST
The module’s primary resource, data, and module blocks. MAY be split into additional main.<topic>.tf files (see below).
locals.tf
SHOULD
All locals blocks. Required if the module declares any locals. MAY be split into additional locals.<topic>.tf files (see below). MAY be omitted only when the module has no locals at all.
Splitting and naming additional files
For larger modules the contents of main.tf, variables.tf, outputs.tf, and locals.tfMAY each be split into multiple files along logical / topic lines. When this is done:
Additional Terraform files MUST use the canonical filename (main, variables, outputs, or locals) as the prefix, followed by a ., a short descriptive topic name, and the .tf extension β for example main.diagnostic_settings.tf, variables.diagnostic_settings.tf, outputs.diagnostic_settings.tf, locals.diagnostic_settings.tf.
The same topic name SHOULD be used across the four file types when they describe the same logical concern, so that (for example) main.private_endpoints.tf, variables.private_endpoints.tf, outputs.private_endpoints.tf, and locals.private_endpoints.tf all relate to the same feature.
Each split file MUST contain only the block kind matching its prefix:
main.<topic>.tf β only resource, data, and module blocks.
variables.<topic>.tf β only variable blocks.
outputs.<topic>.tf β only output blocks.
locals.<topic>.tf β only locals blocks.
The terraform { β¦ } block MUST appear exactly once per module, in terraform.tf. It MUST NOT be split.
Files that MUST NOT appear at the module root
A providers.tf file β provider requirements belong in terraform.tf; provider configurations belong only in the consumer’s root module, never in an AVM module (per SFR2).
A single monolithic module.tf or everything.tf β the canonical filenames above MUST be used.
Rationale
Standardizing file layout means that any reviewer or consumer can find a module’s interface (variables.tf, outputs.tf), provider constraints (terraform.tf), and primary logic (main.tf / main.<topic>.tf) in the same place across every AVM Terraform module, without having to grep. It also makes the cascade rules in TFFR6, TFFR7, and TFRMNFR1 reviewable at a glance.
Submodules (per TFRMNFR1) follow the same layout in their own root directory under modules/<subresource>/. The submodule’s terraform.tfMUST declare the same set of required_providers it actually consumes.
Auto-generated documentation files (README.md, _header.md, _footer.md) and tooling configuration files (.terraform-docs.yml, .tflint.hcl, etc.) are out of scope of this rule and follow their own specs.
Structured values that are passed as JSON or YAML MUST be constructed with jsonencode or yamlencode, rather than a literal JSON or YAML heredoc. Native HCL objects, lists, conditionals, and for expressions keep the structure reviewable and let Terraform perform correct escaping.
Terraform interpolation (${...}), template directives (%{...}), unknown values, and dynamically generated lists or maps are not exceptions: construct the native HCL value and pass it to the encoder.
A heredoc MAY be used only when the value is not JSON or YAML, or when the receiving system requires opaque source text for a downstream templating engine or syntax that jsonencode or yamlencode cannot represent without changing its meaning. The heredoc must not use Terraform interpolation to assemble JSON or YAML in that case, and its reason must be clear from the surrounding configuration.
ID: TFNFR41 - Category: Code Style - Output Definition Order
output blocks in a module SHOULD be ordered alphabetically by output name. This applies to outputs.tf and every outputs.<topic>.tf file in the root module and each submodule.
output"id" {
value = azapi_resource.this.id}
output"name" {
value = azapi_resource.this.name}
We can use count and for_each to deploy multiple resources, but using count with an ordered collection can create an index anti-pattern where removing one item unexpectedly changes other resource addresses.
You can use count to create some kind of resources under certain conditions, for example:
The module’s owners MUST use map(xxx) or set(xxx) as resource’s for_each collection, the map’s key or set’s element MUST be static literals.
Good example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_map // `map(string)`, when user call this module, it could be: `{ "subnet0": "subnet0" }`, or `{ "subnet0": azapi_resource.subnet0.name }`
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
Bad example:
resource"azapi_resource""subnet_pair" {
for_each = var.subnet_name_set // `set(string)`, when user use `toset([azapi_resource.subnet0.name])`, it would cause an error.
type = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"name = "${each.value}-pair"parent_id = azapi_resource.virtual_network.idbody = {
properties = {
addressPrefixes = ["10.0.1.0/24"]
}
}
response_export_values = []
}
There are 3 types of assignment statements in a resource or data block: argument, meta-argument and nested block. The argument assignment statement is a parameter followed by =:
location = azapi_resource.example.location
or:
tags = {
environment = "Production"}
Nested block is a assignment statement of parameter followed by {} block:
subnet {
name = "subnet1"address_prefix = "10.0.1.0/24"}
Meta-arguments are assignment statements can be declared by all resource or data blocks. They are:
count
depends_on
for_each
lifecycle
provider
The order of declarations within resource or data blocks is:
All the meta-arguments SHOULD be declared on the top of resource or data blocks in the following order:
provider
count
for_each
Then followed by:
required arguments
optional arguments
required nested blocks
optional nested blocks
All ranked in alphabetical order.
These meta-arguments SHOULD be declared at the bottom of a resource block with the following order:
depends_on
lifecycle
The parameters of lifecycle block SHOULD show up in the following order:
create_before_destroy
ignore_changes
prevent_destroy
parameters under depends_on and ignore_changes are ranked in alphabetical order.
Meta-arguments, arguments and nested blocked are separated by blank lines.
dynamic nested blocks are ranked by the name comes after dynamic, for example:
ID: TFRMFR1 - Category: Inputs/Outputs - Resource Module Parent ID
A Terraform resource module MUST expose its parent scope to consumers as a single string variable named parent_id, and MUST assign that variable to the parent_id argument of every primary azapi_resource (or equivalent AzAPI resource) it manages.
parent_id is the AzAPI provider’s universal way of expressing where a resource lives in the Azure Resource Manager hierarchy. Depending on the resource type, it can be:
A subscription ID (e.g. /subscriptions/{subscriptionId}) β for tenant- or subscription-scoped resources.
A management group ID (e.g. /providers/Microsoft.Management/managementGroups/{name}) β for management-group-scoped resources.
A resource group ID (e.g. /subscriptions/{subscriptionId}/resourceGroups/{rgName}) β for the most common case of resources that live inside a resource group.
The resource ID of a parent ARM resource (e.g. the ID of a virtual network for subnets, the ID of a storage account for blob containers) β for child / nested resources.
Because the same variable describes every possible parent scope, modules MUST NOT expose resource_group_name, resource_group_resource_id, or any other parent-scope-specific variable. The fully-qualified ARM ID supplied via parent_id is sufficient and works uniformly for every kind of Azure resource.
parent_idMUST be validated using the AzAPI provider’s provider-defined functions, per TFNFR38. The required function is provider::azapi::parse_resource_id, called with the expected parent resource type for the module’s primary resource (for example Microsoft.Resources/resourceGroups for resources that live inside a resource group, or Microsoft.Network/virtualNetworks for a subnet module). Hand-rolled regex, startswith, or length checks MUST NOT be used.
This rule supersedes the Terraform clause of RMFR3 (which historically required a resource_group_name variable in Terraform). RMFR3 still applies to Bicep modules; for AVM Terraform modules the rules in this spec take precedence.
Variable declaration
variable"parent_id" {
type = stringnullable = falsevalidation { # Validate via the AzAPI provider's `parse_resource_id` function. The function
# errors if `parent_id` is malformed OR if it does not parse as the expected
# parent resource type (e.g. passing a subscription ID where a resource group
# is required). Replace `Microsoft.Resources/resourceGroups` with the parent
# resource type expected by this module's primary resource (for example
# `Microsoft.Network/virtualNetworks` for a subnet module).
condition = can(provider::azapi::parse_resource_id("Microsoft.Resources/resourceGroups", var.parent_id))
error_message = "`parent_id` must be a valid Azure resource group resource ID." }
description = <<DESCRIPTIONThe fully-qualified ARM resource ID of the scope into which the resource managed by this module will be deployed. Examples:
- Subscription scope: `/subscriptions/00000000-0000-0000-0000-000000000000`
- Management group scope: `/providers/Microsoft.Management/managementGroups/example-mg`
- Resource group scope: `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg`
- Parent resource scope: `/subscriptions/.../resourceGroups/example-rg/providers/Microsoft.Network/virtualNetworks/example-vnet`
This module **does not** create the parent scope. The consumer (or composing pattern module) is responsible for providing a `parent_id` for an existing scope.
DESCRIPTION}
The resource type passed to parse_resource_idMUST be a literal string naming the expected parent resource type for the module’s primary resource (e.g. "Microsoft.Resources/resourceGroups" for a resource that lives inside a resource group, or "Microsoft.Network/virtualNetworks" for a subnet module). It MUST NOT be a reference to another variable. This keeps the validation block self-contained.
Modules MUST NOT accept resource_group_name, resource_group_resource_id, or any other parent-scope-specific variable. If a module needs to be told which resource group (or subscription, or management group) to deploy into, it does so exclusively via parent_id.
Modules MUST NOT create the parent scope themselves (see RMFR3 for the resource-group case). The consumer or composing pattern module supplies an existing scope’s ARM ID.
Submodules (per TFRMNFR1) MUST also expose parent_id and follow the same rules. The parent module typically passes its own primary resource’s ID to each child, e.g. parent_id = azapi_resource.this.id.
Modules MAY expose additional, narrower scope variables only when a single resource genuinely needs two different parent scopes (rare). In that case the additional variable MUST still be a parent_id-shaped string (fully-qualified ARM ID), validated with the same provider-defined function pattern, and MUST NOT be named after a specific scope kind such as resource_group_name.
Exception β extension-resource modules
A small class of resource modules manages an Azure extension resource (a resource type that attaches to any parent ARM resource, regardless of its provider). Examples include modules whose primary resource is Microsoft.Authorization/locks, Microsoft.Authorization/roleAssignments, Microsoft.Insights/diagnosticSettings, Microsoft.Resources/tags, or similar. For these modules, the parent resource type is intentionally polymorphic and a literal parse_resource_id("Microsoft.X/y", var.parent_id) validation MUST NOT be used.
Where this exception applies, the module MUST still:
Expose the parent scope as the variable named parent_id (no other name), of type string, required, and nullable = false.
Validate that parent_id is a non-empty fully-qualified ARM ID using a generic check, e.g.:
validation {
condition = length(var.parent_id) >0&& (startswith(var.parent_id, "/subscriptions/") ||startswith(var.parent_id, "/providers/"))
error_message = "`parent_id` must be a fully-qualified ARM resource ID starting with `/subscriptions/` or `/providers/`."}
Document in the variable’s description that any ARM resource ID is accepted because the module manages an extension resource.
Document the exception in the module’s README.md so reviewers immediately understand why the standard parse_resource_id validation is absent.
ID: TFRMNFR1 - Category: Composition - Subresources as submodules
Resource modules MUST implement each ARM subresource (a child resource type as defined in the API spec, for example Microsoft.Example/widgets/parts is a subresource of Microsoft.Example/widgets) as a Terraform submodule.
Submodules MUST be located in a direct modules/<subresource-singular-name>/ child directory at the repository root, where <subresource-singular-name> is the singular form of the ARM subresource name as per PMNFR1. Nested Terraform module roots are prohibited: modules/<name>/modules/<name>/ is not an AVM module scope.
Terraform example roots follow the same one-layer convention: each example MUST be a direct examples/<name>/ child directory. Nested example roots are prohibited.
Avm.Authoring convention validation enforces the direct modules/* and examples/* scope structure. Consequently, directory-specific TFLint overrides apply only at those direct roots; see TFLint configuration overrides.
For example, a resource module for Microsoft.Example/widgets would have the following layout:
The parent module MUST reference and compose its submodules so that supported subresources can be expressed through the parent module, but each submodule MUST also be independently consumable.
“Independently consumable” means a caller can source the submodule directly and use it without relying on hidden behavior in the parent module. Therefore, a submodule MUST follow the same interface and specification rules as a root AVM Terraform module (as listed below), even when the parent module also instantiates it.
Submodule cardinality
Submodules MUST deploy exactly one instance of the resource they manage. The submodule’s primary azapi_resource (or equivalent) MUST NOT declare count or for_each, and the submodule MUST NOT otherwise create multiple instances of its primary resource.
Cardinality is the parent module’s responsibility: the parent module MUST use count or for_each on its submodule call to control how many instances of the subresource are deployed. This keeps each submodule’s variables, outputs and tests focused on a single resource and pushes cardinality concerns up to the consumer.
This rule applies equally when a submodule is consumed through its parent module and when the same submodule is consumed directly by another caller.
For example, a parent module deploying multiple parts calls its part submodule using for_each, cascades the matching nested slot from its own resource_types (see TFFR6 for the naming rule and nested-slot pattern), passes retry and timeouts through unchanged (see TFFR7), and cascades the matching nested slot from its own ignore_body_changes (see TFFR8):
When the ARM subresource type is more than one level deep (for example Microsoft.Example/widgets/parts/components), its Terraform module root still MUST be a direct child of modules/. Use a descriptive direct name such as modules/part-component/; do not create modules/part/modules/component/. The parent module composes all direct submodules and exposes the required nested interface values without creating nested Terraform roots.
The following pattern is NOT allowed inside a submodule, because it pushes cardinality into the submodule itself:
Submodules MAY reference a direct sibling submodule using a relative path:
# Inside modules/part/main.tf, calling the direct sibling modules/sub-part/
module"sub_part" {
source = "../sub-part" # ...other arguments...
}
This pattern is useful when an ARM resource provider exposes child resources nested more than one level deep, while preserving the required one-layer module-root layout.
Submodules MUST NOT reference a sibling submodule via the Terraform Registry (for example Azure/avm-res-example-widget/azure//modules/part) or via a Git URL when the sibling lives in the same repository. Using a relative path keeps the entire module tree as a single unit that can be developed, tested and released atomically.
Submodule documentation files
Each submodule directory MUST contain its own _header.md and _footer.md files at the root of the submodule (alongside main.tf). These files are consumed by the AVM terraform-docs documentation generation pipeline (see TFNFR2) to produce the submodule’s README.md. Without them, the generated submodule documentation will be missing its introduction and footer sections and the documentation pipeline will not produce a complete README.md.
The submodule _header.md and _footer.mdMUST:
Describe the subresource the submodule manages, not the parent resource.
Be checked in to source control (they are inputs to documentation generation, not generated artifacts).
Be present in every submodule under modules/, even if the submodule is not intended to be consumed independently.
Submodules are full AVM modules
Submodules MUST meet every requirement that applies to a top-level AVM Terraform resource module, including (but not limited to):
All shared specifications (SFR and SNFR prefixed specs).
All resource module specifications (RMFR and RMNFR prefixed specs).
All Terraform specifications (TFFR and TFNFR prefixed specs), including:
TFFR3 β AzAPI is mandatory for every control-plane resource and supported data-plane operation in every module and submodule; AzureRM is permitted only for the documented unsupported data-plane/non-ARM API exception.
TFFR6 β resource_types variable. Each submodule declares its own resource_types for the resources it owns; the parent declares a nested optional(object({...}), {}) slot per submodule that mirrors the submodule’s variable exactly, and cascades it through unchanged.
TFFR7 β retry and timeouts variables, which the parent module MUST cascade to each submodule unchanged.
TFFR8 β ignore_body_changes variable. Each submodule declares its own for the resources it owns; the parent declares a nested optional(object({...}), {}) slot per submodule that mirrors the submodule’s variable exactly, and cascades it through unchanged. The parent’s own paths MUST NOT be cascaded, because they are scoped to the parent’s body.
All applicable interface specifications (managed identities, role assignments, locks, diagnostic settings, private endpoints, customer-managed keys, tags) β for any interface that is supported by the underlying ARM subresource.
To avoid duplication, this specification deliberately states the requirement once: every requirement that applies to a top-level resource module applies equally to every one of its submodules. Where a requirement contradicts the submodule’s nature (for example, a submodule that is never published independently still MUST include all required documentation files but is not itself listed in the registry), the requirement is interpreted in the context of the submodule.
Rationale
Implementing subresources as submodules:
Provides a clean, narrowly-scoped Terraform interface per ARM resource type, mirroring the ARM/AzAPI model where each resource type has its own type identifier and API version.
Allows consumers to use only the subresources they need, without paying the cost of unused resources.
Keeps each submodule’s variables, outputs and tests focused, which improves readability, testability and review velocity.
Aligns with the equivalent Bicep guidance in BCPRMNFR3 so that AVM resource modules in both languages share a consistent structure.
The primary azapi_resource (or equivalent AzAPI resource) declared in a Terraform resource module MUST be named this. The same rule applies to the primary resource declared in any submodule (per TFRMNFR1).
The “primary resource” is the single Azure resource that the module exists to manage β the one whose ARM resource type appears in the module’s name (per RMNFR1). Every other resource declared by the module (locks, role assignments, diagnostic settings, private endpoints, private DNS zone groups, child / extension resources required by the primary resource, etc.) is a satellite resource and MUST NOT be named this; instead, satellites MUST be named after what they represent (for example azapi_resource.lock, azapi_resource.role_assignments, azapi_resource.diagnostic_settings, azapi_resource.private_endpoints).
Standardizing on this for the primary resource lets consumers, CI checks, and the AVM interface utility module reference it predictably β most notably as azapi_resource.this.id for downstream parent_id wiring, and azapi_resource.this.output for exported values.
Example
The resource label (this) and the var.resource_types.<key> argument supplied to type = are independent concerns: the label is governed by this spec, the key by the naming rule in TFFR6. this is therefore never a valid resource_types key β the key names the AzAPI resource type, not the Terraform graph node.
The this rule MAY be relaxed only when all of the following are true:
The module is a utility module (per Module Classifications) OR the module’s primary functionality is implemented by two or more azapi_resource declarations that are peers (no resource is the ARM parent of any other, and no resource depends on another resource’s ID for its own creation).
No single azapi_resource would, on its own, be a meaningful handle for downstream consumers (i.e. there is no resource whose id would be the obvious value of a single canonical resource_id output).
A module where one azapi_resource is the ARM parent of, or a hard dependency for, another azapi_resource is NOT exempted β the parent resource is the primary and MUST be named this.
Where this exception applies, each resource MUST be named after what it represents, and the module’s README.mdMUST document why the this convention does not apply.
Notes
This rule applies regardless of whether the primary resource uses azapi_resource, azapi_resource_action, azapi_update_resource, or any other AzAPI resource type.
The rule applies independently to every submodule: each submodule has its own this (the primary resource it manages) β that is the contract enabling the parent module to write module.<submodule>.resource_id.
The rule does not apply to data sources or to azapi_resource_list lookups; those SHOULD still be named after what they represent.
Utility Modules MUST follow the below naming conventions (all lower case).
Important
The module’s approved name is captured in the module proposal issue. The related module index page and CSV file remain published lookup references.
Module owners must use the name approved in the module proposal, not construct a new one. If it differs from the index, confirm the correction with the AVM core team.
Correct descriptive fields through the metadata review process. Changing moduleDisplayName does not rename the module or change its repository path.
Example: avm/utl/general/get-environment or avm/utl/types/avm-common-types
Segments:
utl defines this as a utility module
<hyphenated grouping/category name> is a hierarchical grouping of utility modules by category, with each word separated by dashes, such as: general or types
<hyphenated utility module name> is a term describing the module’s function, with each word separated by dashes, e.g., get-environment = to get environmental details; avm-common-types = to use common types.
Terraform Utility Module Naming
Naming convention:
avm-utl-<utility module name> (Module name for registry)
terraform-<provider>-avm-utl-<utility module name> (GitHub repository name to meet registry naming requirements)
Example: avm-utl-sku-finder or avm-utl-naming
Segments:
<provider> is a legacy requirement of the Terraform registry. For AVM Terraform utility modules this MUST be set to azure (for example Azure/avm-utl-naming/azure). Older utility modules may still use the azurerm or azuread segments. These segments are names only and do not permit use of the AzureRM provider; TFFR3 still requires every module to be built with AzAPI.
utl defines this as a utility module
<utility module name> is a term describing the module’s function, e.g., sku-finder = to find available SKUs; naming = to handle naming conventions.
Contributing
Summary
This section lists all contribution guidance available to module owners and contributors.
If you cannot find guidance for what you need, please let us know via GitHub Issues π
Subsections of Contributing
Bicep Contribution Guide
Important
While this page describes and summarizes important aspects of contributing to AVM, it may not reference All of the shared and language specific requirements.
Therefore, this contribution guide MUST be used in conjunction with the Bicep specifications. ALL AVM modules (Resource and Pattern modules) MUST meet the respective requirements described in these specifications!
Summary
This section lists AVM’s Bicep-specific contribution guidance.
While this page describes and summarizes important aspects of the composition of AVM modules, it may not reference All of the shared and language specific requirements.
Therefore, this guide MUST be used in conjunction with the Bicep specifications. ALL AVM modules (Resource and Pattern modules) MUST meet the respective requirements described in these specifications!
Important
Before jumping on implementing your contribution, please review the AVM Module specifications, in particular the Bicep specification page, to make sure your contribution complies with the AVM module’s design and principles.
For new modules, the files can be created automatically, once the parent folder exists. This example shows how to create a res module res/compute/virtual-machine.
Modules enable you to reuse code from a Bicep file in other Bicep files. As such, for resource modules they’re normally leveraged for deploying child resources (e.g., file services in a storage account), cross referenced resources (e.g., network interface in a virtual machine) or extension resources (e.g., role assignments in a key vault). Pattern modules, normally reuse resource modules combined together.
Make sure to review all specifications covering module properties and usage.
Tip
See examples in specifications BCPFR1 for resource modules and PMNFR2 for pattern modules.
Outputs
Make sure to review all specifications of Category: Inputs/Outputs within the Bicep specific pages.
This section is only relevant for contributions to resource modules.
To meet RMFR4 and RMFR5 AVM resource modules must leverage consistent interfaces for all the optional features/extension resources supported by the AVM module primary resource.
Please refer to the Bicep Interfaces page. If the primary resource of the AVM resource module you are developing supports any of the listed features/extension resources, please follow the corresponding provided Bicep schema to develop them.
Deprecation
Breaking changes are sometimes not avoidable. The impact should be kept as low as possible. A recommendation is to deprecate parameters, instead of completely removing them for a couple of versions. The Semantic Versioning sections offers information about versioning AVM modules.
In case you need to deprecate an input parameter, this sample shows you how this can be achieved.
Note
Since all modules are versioned, nothing will change for existing deployments, as the parameter usage does not change for any existing versions.
Example-Scenario
An AVM module is modified, and the parameters will change, which breaks backward compatibility.
parameters are changing to a custom type
the parameter structure is changing
backward compatibility will be maintained
Existing input parameters used to be defined as follows (reducing the examples to the minimum):
Before you begin to modify anything, it is recommended to create a new test case (e.g. deprecated), in addition to the already existing tests, to make sure that the changes are not breaking backward compatibility until you decide to finally remove the deprecated parameters (see BCPRMNFR1 - Category: Testing - Expected Test Directories for more details about the requirements).
The test should include all previously used parameters to make sure they are covered before any changes to the new parameter layout are done.
Code Changes
The new parameter structure requires a change to the used parameters and moves them to a different location and looks like:
// main.bicep:param item itemType?
type itemtype: {
name: string // the name parameter did not change properties ={
osType: 'Linux' | 'Windows'? // the new place for the osType variant: {
size: string? // the new place for the variant size }?
}
// keep these for backward compatibility in the new type @description('Optional. Note: This is a deprecated property, please use the corresponding `properties.osType` instead.')
osType: string? // the old parameter location @description('Optional. Note: This is a deprecated property, please use the corresponding `properties.variant.size` instead.')
variant: string? // the old parameter location}
The original parameter item is of type object and does not give the user any clue of what the syntax is and what is expected to be added to it. The tests could bring light into the darkness, but this is not ideal. In order to retain backward compatibility, the previously used parameters need to be added to the new type, as they would be invalid otherwise. Now that the new type is in place, some logic needs to be implemented to make sure the module can handle the different sources of data (new and old parameters).
resource<modulename>'Microsoft.xy/yz@2024-01-01' = {
name: name
properties: {
osType: item.?properties.?osType ?? item.?osType ??'Linux'// add a default here, if needed variant: {
size: item.?properties.?variant.?size ?? item.?variant
}
}
}
By choosing this order for the Coalesce operator, the new format takes precedence over the old syntax. Also note the safe-dereference ensures that no null reference exception will occure if the property has optional parameters.
The tests can now be changed to adapt the new parameter structure for the new version of the module. They will not cover the old parameter structure anymore.
Changes to modules (resource or pattern) can bei implemented in two ways.
Implement changes with backward compatibility
In this scenario, you need to make sure that the code does not break backward compatibility by:
adding new parameters
marking other parameters as deprecated
create a test case for the old usage syntax
increase the minor version number of the module (0.x)
Introduce breaking changes
The easier way to introduce a new major version requires fewer steps:
adding new parameters
create a test case for the usage
increase the major version number of the module (x.0.0)
Note
Be aware that currently no module has been released as 1.0.0 (or beyond), which lets you implement breaking changes without increasing the major version.
---
config:
nodeSpacing: 20
rankSpacing: 20
diagramPadding: 50
padding: 5
flowchart:
wrappingWidth: 300
padding: 5
layout: elk
elk:
mergeEdges: true
nodePlacementStrategy: LINEAR_SEGMENTS
---
flowchart TD
A("1 - Fork the module source repository")
click A "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#1-fork-the-module-source-repository"
B(2 - Configure a deployment identity in Azure)
click B "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#2-configure-a-deployment-identity-in-azure"
C("3 - Configure CI environment for module tests")
click C "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#3-configure-your-ci-environment"
D("4 - Implementing your contribution<br>(Refer to Gitflow Diagram below)")
click D "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#4-implement-your-contribution"
E(5 - Workflow test completed successfully?)
click E "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#5-createupdate-and-run-tests"
F(6 - Create a pull request to the upstream repository)
click F "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#6-create-a-pull-request-to-the-public-bicep-registry"
G(7 - Get your pull request approved)
click G "/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#7-get-your-pull-request-approved"
A --> B
B --> C
C --> D
D --> E
E -->|yes|F
E -->|no|D
F --> G
GitFlow for contributors
The GitFlow process outlined here introduces a central anchor branch. This branch should be treated as if it were a protected branch. It serves to synchronize the forked repository with the original upstream repository. The use of the anchor branch is designed to give contributors the flexibility to work on several modules simultaneous.
When implementing the GitFlow process as described, it is advisable to configure the local clone with a remote for the upstream repository. This will enable the Git CLI and local IDE to merge changes directly from the upstream repository. Using GitHub Desktop, this is configured automatically when cloning the forked repository via the application.
PowerShell Helper Script To Setup Fork & CI Test Environment
Now defaults to OIDC setup
The PowerShell Helper Script has recently added support for the OIDC setup and configuration as documented in detail on this page. This is now the default for the script.
The easiest way to get yourself set back up, is to delete your fork repository, including the local clone of it that you have and start over with the script. This will ensure you have the correct setup for the OIDC authentication method for the AVM CI.
Important
To simplify the setup of the fork, clone and configuration of the required GitHub Environments, Secrets, User-Assigned Managed Identity (UAMI), Federated Credentials and RBAC assignments in your Azure environment for the CI framework to function correctly in your fork, we have created a PowerShell script that you can use to do steps 1, 2 & 3 below.
The script performs the following steps:
Forks the Azure/bicep-registry-modules to your GitHub Account.
Clones the repo locally to your machine, based on the location you specify in the parameter: -GitHubRepositoryPathForCloneOfForkedRepository.
Prompts you and takes you directly to the place where you can enable GitHub Actions Workflows on your forked repo.
Creates an User-Assigned Managed Identity (UAMI) and federated credentials for OIDC with your forked GitHub repo and grants it the RBAC roles of Owner at Management Group level, if specified in the -GitHubSecret_ARM_MGMTGROUP_ID parameter, and at Azure Subscription level if you provide it via the -GitHubSecret_ARM_SUBSCRIPTION_ID parameter.
Creates the required GitHub Environments & required Secrets in your forked repo as per step 3, based on the input provided in parameters and the values from resources the script creates and configures for OIDC. Also set the workflow permissions to Read and write permissions as per step 3.3.
Pre-requisites
You must have the Azure PowerShell Modules installed and you need to be logged with the context set to the desired Tenant. You must have permissions to create an SPN and grant RBAC over the specified Subscription and Management Group, if provided.
You must have the GitHub CLI installed and need to be authenticated with the GitHub user account you wish to use to fork, clone and work with on AVM.
The New-AVMBicepBRMForkSetup.ps1 can be downloaded from here.
Once downloaded, you can run the script by running the below - Please change all the parameter values in the below script usage example to your own values (see the parameter documentation in the script itself)!:
.\<PATH-TO-SCRIPT-DOWNLOAD-LOCATION>\New-AVMBicepBRMForkSetup.ps1 -GitHubRepositoryPathForCloneOfForkedRepository "<pathToCreateForkedRepoIn>" -GitHubSecret_ARM_MGMTGROUP_ID "<managementGroupId>" -GitHubSecret_ARM_SUBSCRIPTION_ID "<subscriptionId>" -GitHubSecret_ARM_TENANT_ID "<tenantId>" -GitHubSecret_TOKEN_NAMEPREFIX "<unique3to5AlphanumericStringForAVMDeploymentNames>" -UAMIRsgLocation "<Azure Region/Location of your choice such as 'uksouth'>"
For more examples, see the below script’s parameters section.
ο»Ώ[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification = "Coloured output required in this script")]
#Requires-PSEdition Core#Requires-Modules @{ ModuleName="Az.Accounts"; ModuleVersion="2.19.0" }#Requires-Modules @{ ModuleName="Az.Resources"; ModuleVersion="6.16.2" }<#
.SYNOPSISThis function creates and sets up everything a contributor to the AVM Bicep project should need to get started with their contribution to a AVM Bicep Module.
.DESCRIPTIONThis function creates and sets up everything a contributor to the AVM Bicep project should need to get started with their contribution to a AVM Bicep Module. This includes:
- Forking and cloning the `Azure/bicep-registry-modules` repository
- Creating a new SPN and granting it the necessary permissions for the CI tests and configuring the forked repositories secrets, as per: https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#2-configure-a-deployment-identity-in-azure
- Enabling GitHub Actions on the forked repository
- Disabling all the module workflows by default, as per: https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/enable-or-disable-workflows/
Effectively simplifying this process to a single command, https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/
.PARAMETER GitHubRepositoryPathForCloneOfForkedRepository
Mandatory. The path to the GitHub repository to fork and clone. Directory will be created if does not already exist. Can use either relative paths or full literal paths.
.PARAMETER GitHubSecret_ARM_MGMTGROUP_ID
Optional. The group ID of the management group to test-deploy modules in. Is needed for resources that are deployed to the management group scope. If not provided CI tests on Management Group scoped modules will not work and you will need to manually configure the RBAC role assignments for the SPN and associated repository secret later.
.PARAMETER GitHubSecret_ARM_SUBSCRIPTION_ID
Mandatory. The ID of the subscription to test-deploy modules in. Is needed for resources that are deployed to the subscription scope.
.PARAMETER GitHubSecret_ARM_TENANT_ID
Mandatory. The tenant ID of the Azure Active Directory tenant to test-deploy modules in. Is needed for resources that are deployed to the tenant scope.
.PARAMETER GitHubSecret_TOKEN_NAMEPREFIX
Mandatory. Required. A short (3-5 character length), unique string that should be included in any deployment to Azure. Usually, AVM Bicep test cases require this value to ensure no two contributors deploy resources with the same name - which is especially important for resources that require a globally unique name (e.g., Key Vault). These characters will be used as part of each resourceβs name during deployment.
.PARAMETER SPNName
Optional. The name of the SPN (Service Principal) to create. If not provided, a default name of `spn-avm-bicep-brm-fork-ci-<GitHub Organization>` will be used.
.PARAMETER UAMIName
Optional. The name of the UAMI (User Assigned Managed Identity) to create. If not provided, a default name of `id-avm-bicep-brm-fork-ci-<GitHub Organization>` will be used.
.PARAMETER UAMIRsgName
Optional. The name of the Resource Group to create for the UAMI (User Assigned Managed Identity) to create. If not provided, a default name of `rsg-avm-bicep-brm-fork-ci-<GitHub Organization>-oidc` will be used.
.PARAMETER UAMIRsgLocation
Optional. The location of the Resource Group to create for the UAMI (User Assigned Managed Identity) to create. Also UAMI will be created in this location. This is required for OIDC deployments.
.PARAMETER UseOIDC
Optional. Default is `$true`. If set to `$true`, the script will use the OIDC (OpenID Connect) authentication method for the SPN instead of secrets as per https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#31-set-up-secrets. If set to `$false`, the script will use the Client Secret authentication method for the SPN and not OIDC.
.EXAMPLE.\<PATH-TO-SCRIPT-DOWNLOAD-LOCATION>\New-AVMBicepBRMForkSetup.ps1 -GitHubRepositoryPathForCloneOfForkedRepository "D:\GitRepos\" -GitHubSecret_ARM_MGMTGROUP_ID "alz" -GitHubSecret_ARM_SUBSCRIPTION_ID "1b60f82b-d28e-4640-8cfa-e02d2ddb421a" -GitHubSecret_ARM_TENANT_ID "c3df6353-a410-40a1-b962-e91e45e14e4b" -GitHubSecret_TOKEN_NAMEPREFIX "ex123" -UAMIRsgLocation "uksouth"
Example Subscription & Management Group scoped deployments enabled via OIDC with default generated UAMI Resource Group name of `rsg-avm-bicep-brm-fork-ci-<GitHub Organization>-oidc` and UAMI name of `id-avm-bicep-brm-fork-ci-<GitHub Organization>`.
.EXAMPLE.\<PATH-TO-SCRIPT-DOWNLOAD-LOCATION>\New-AVMBicepBRMForkSetup.ps1 -GitHubRepositoryPathForCloneOfForkedRepository "D:\GitRepos\" -GitHubSecret_ARM_MGMTGROUP_ID "alz" -GitHubSecret_ARM_SUBSCRIPTION_ID "1b60f82b-d28e-4640-8cfa-e02d2ddb421a" -GitHubSecret_ARM_TENANT_ID "c3df6353-a410-40a1-b962-e91e45e14e4b" -GitHubSecret_TOKEN_NAMEPREFIX "ex123" -UAMIRsgLocation "uksouth" -UAMIName "my-uami-name" -UAMIRsgName "my-uami-rsg-name"
Example with provided UAMI Name & UAMI Resource Group Name.
.EXAMPLE.\<PATH-TO-SCRIPT-DOWNLOAD-LOCATION>\New-AVMBicepBRMForkSetup.ps1 -GitHubRepositoryPathForCloneOfForkedRepository "D:\GitRepos\" -GitHubSecret_ARM_SUBSCRIPTION_ID "1b60f82b-d28e-4640-8cfa-e02d2ddb421a" -GitHubSecret_ARM_TENANT_ID "c3df6353-a410-40a1-b962-e91e45e14e4b" -GitHubSecret_TOKEN_NAMEPREFIX "ex123" -UseOIDC $false
DEPRECATED - USE OIDC INSTEAD.
Example Subscription scoped deployments enabled only with default generated SPN name of `spn-avm-bicep-brm-fork-ci-<GitHub Organization>`.
.EXAMPLE.\<PATH-TO-SCRIPT-DOWNLOAD-LOCATION>\New-AVMBicepBRMForkSetup.ps1 -GitHubRepositoryPathForCloneOfForkedRepository "D:\GitRepos\" -GitHubSecret_ARM_MGMTGROUP_ID "alz" -GitHubSecret_ARM_SUBSCRIPTION_ID "1b60f82b-d28e-4640-8cfa-e02d2ddb421a" -GitHubSecret_ARM_TENANT_ID "c3df6353-a410-40a1-b962-e91e45e14e4b" -GitHubSecret_TOKEN_NAMEPREFIX "ex123" -SPNName "my-spn-name" -UseOIDC $false
DEPRECATED - USE OIDC INSTEAD.
Example with provided SPN name.
#>[CmdletBinding(SupportsShouldProcess = $false)]
param (
[Parameter(Mandatory = $true)]
[string] $GitHubRepositoryPathForCloneOfForkedRepository,
[Parameter(Mandatory = $false)]
[string] $GitHubSecret_ARM_MGMTGROUP_ID,
[Parameter(Mandatory = $true)]
[string] $GitHubSecret_ARM_SUBSCRIPTION_ID,
[Parameter(Mandatory = $true)]
[string] $GitHubSecret_ARM_TENANT_ID,
[Parameter(Mandatory = $true)]
[string] $GitHubSecret_TOKEN_NAMEPREFIX,
[Parameter(Mandatory = $false)]
[string] $SPNName,
[Parameter(Mandatory = $false)]
[string] $UAMIName,
[Parameter(Mandatory = $false)]
[string] $UAMIRsgName = "rsg-avm-bicep-brm-fork-ci-oidc",
[Parameter(Mandatory = $false)]
[string] $UAMIRsgLocation,
[Parameter(Mandatory = $false)]
[bool] $UseOIDC = $true
)
# Check if the GitHub CLI is installed$GitHubCliInstalled = Get-Command gh -ErrorAction SilentlyContinue
if ($null -eq $GitHubCliInstalled) {
throw'The GitHub CLI is not installed. Please install the GitHub CLI and try again. Install link for GitHub CLI: https://github.com/cli/cli#installation'}
Write-Host 'The GitHub CLI is installed...' -ForegroundColor Green
# Check if GitHub CLI is authenticated$GitHubCliAuthenticated = gh auth status
if ($LASTEXITCODE -ne0) {
Write-Host $GitHubCliAuthenticated -ForegroundColor Red
throw"Not authenticated to GitHub. Please authenticate to GitHub using the GitHub CLI command of 'gh auth login', and try again."}
Write-Host 'Authenticated to GitHub with following details...' -ForegroundColor Cyan
Write-Host ''gh auth status
Write-Host ''# Ask the user to confirm if it's the correct GitHub accountdo {
Write-Host "Is the above GitHub account correct to coninue with the fork setup of the 'Azure/bicep-registry-modules' repository? Please enter 'y' or 'n'." -ForegroundColor Yellow
$userInput = Read-Host
$userInput = $userInput.ToLower()
switch ($userInput) {
'y' {
Write-Host '' Write-Host 'User Confirmed. Proceeding with the GitHub account listed above...' -ForegroundColor Green
Write-Host ''break }
'n' {
Write-Host ''throw"User stated incorrect GitHub account. Please switch to the correct GitHub account. You can do this in the GitHub CLI (gh) by logging out by running 'gh auth logout' and then logging back in with 'gh auth login'" }
default {
Write-Host '' Write-Host "Invalid input. Please enter 'y' or 'n'." -ForegroundColor Red
Write-Host '' }
}
} while ($userInput -ne'y'-and $userInput -ne'n')
# Fork and clone repository locallyWrite-Host "Changing to directory $GitHubRepositoryPathForCloneOfForkedRepository ..." -ForegroundColor Magenta
if (-not (Test-Path -Path $GitHubRepositoryPathForCloneOfForkedRepository)) {
Write-Host "Directory does not exist. Creating directory $GitHubRepositoryPathForCloneOfForkedRepository ..." -ForegroundColor Yellow
New-Item -Path $GitHubRepositoryPathForCloneOfForkedRepository -ItemType Directory -ErrorAction Stop
Write-Host ''}
Set-Location -Path $GitHubRepositoryPathForCloneOfForkedRepository -ErrorAction stop
$CreatedDirectoryLocation = Get-Location
Write-Host "Forking and cloning 'Azure/bicep-registry-modules' repository..." -ForegroundColor Magenta
gh repo fork 'Azure/bicep-registry-modules' --default-branch-only --clone=true
if ($LASTEXITCODE -ne0) {
throw"Failed to fork and clone the 'Azure/bicep-registry-modules' repository. Please check the error message above, resolve any issues, and try again."}
$ClonedRepoDirectoryLocation = Join-Path $CreatedDirectoryLocation 'bicep-registry-modules'Write-Host ''Write-Host "Fork of 'Azure/bicep-registry-modules' created successfully directory in $CreatedDirectoryLocation ..." -ForegroundColor Green
Write-Host ''Write-Host "Changing into cloned repository directory $ClonedRepoDirectoryLocation ..." -ForegroundColor Magenta
Set-Location $ClonedRepoDirectoryLocation -ErrorAction stop
# Check is user is logged in to Azure$UserLoggedIntoAzure = Get-AzContext -ErrorAction SilentlyContinue
if ($null -eq $UserLoggedIntoAzure) {
throw'You are not logged into Azure. Please log into Azure using the Azure PowerShell module using the command of `Connect-AzAccount` to the correct tenant and try again.'}
$UserLoggedIntoAzureJson = $UserLoggedIntoAzure | ConvertTo-Json -Depth 10 | ConvertFrom-Json
Write-Host "You are logged into Azure as '$($UserLoggedIntoAzureJson.Account.Id)' ..." -ForegroundColor Green
# Check user has access to desired subscription$UserCanAccessSubscription = Get-AzSubscription -SubscriptionId $GitHubSecret_ARM_SUBSCRIPTION_ID -ErrorAction SilentlyContinue
if ($null -eq $UserCanAccessSubscription) {
throw"You do not have access to the subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)'. Please ensure you have access to the subscription and try again."}
Write-Host "You have access to the subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)' ..." -ForegroundColor Green
Write-Host ''# Get GitHub Login/Org Name$GitHubUserRaw = gh api user
$GitHubUserConvertedToJson = $GitHubUserRaw | ConvertFrom-Json -Depth 10$GitHubOrgName = $GitHubUserConvertedToJson.login
$GitHubOrgAndRepoNameCombined = "$($GitHubOrgName)/bicep-registry-modules"# Create SPN if not using OIDCif ($UseOIDC -eq $false) {
if ($SPNName -eq'') {
Write-Host "No value provided for the SPN Name. Defaulting to 'spn-avm-bicep-brm-fork-ci-<GitHub Organization>' ..." -ForegroundColor Yellow
$SPNName = "spn-avm-bicep-brm-fork-ci-$($GitHubOrgName)" }
$newSpn = New-AzADServicePrincipal -DisplayName $SPNName -Description "Service Principal Name (SPN) for the AVM Bicep CI Tests in the $($GitHubOrgName) fork. See: https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/#2-configure-a-deployment-identity-in-azure" -ErrorAction Stop
Write-Host "New SPN created with a Display Name of '$($newSpn.DisplayName)' and an Object ID of '$($newSpn.Id)'." -ForegroundColor Green
Write-Host ''# Create RBAC Role Assignments for SPN Write-Host 'Starting 120 second sleep to allow the SPN to be created and available for RBAC Role Assignments (eventual consistency) ...' -ForegroundColor Yellow
Start-Sleep -Seconds 120 Write-Host "Creating RBAC Role Assignments of 'Owner' for the Service Principal Name (SPN) '$($newSpn.DisplayName)' on the Subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)' ..." -ForegroundColor Magenta
New-AzRoleAssignment -ApplicationId $newSpn.AppId -RoleDefinitionName 'Owner' -Scope "/subscriptions/$($GitHubSecret_ARM_SUBSCRIPTION_ID)" -ErrorAction Stop
Write-Host "RBAC Role Assignments of 'Owner' for the Service Principal Name (SPN) '$($newSpn.DisplayName)' created successfully on the Subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)'." -ForegroundColor Green
Write-Host ''if ($GitHubSecret_ARM_MGMTGROUP_ID -eq'') {
Write-Host "No Management Group ID provided as input parameter to '-GitHubSecret_ARM_MGMTGROUP_ID', skipping RBAC Role Assignments upon Management Groups" -ForegroundColor Yellow
Write-Host '' }
if ($GitHubSecret_ARM_MGMTGROUP_ID -ne'') {
Write-Host "Creating RBAC Role Assignments of 'Owner' for the Service Principal Name (SPN) '$($newSpn.DisplayName)' on the Management Group with the ID of '$($GitHubSecret_ARM_MGMTGROUP_ID)' ..." -ForegroundColor Magenta
New-AzRoleAssignment -ApplicationId $newSpn.AppId -RoleDefinitionName 'Owner' -Scope "/providers/Microsoft.Management/managementGroups/$($GitHubSecret_ARM_MGMTGROUP_ID)" -ErrorAction Stop
Write-Host "RBAC Role Assignments of 'Owner' for the Service Principal Name (SPN) '$($newSpn.DisplayName)' created successfully on the Management Group with the ID of '$($GitHubSecret_ARM_MGMTGROUP_ID)'." -ForegroundColor Green
Write-Host '' }
}
# Create UAMI if using OIDCif ($UseOIDC) {
if ($UAMIName -eq'') {
Write-Host "No value provided for the UAMI Name. Defaulting to 'id-avm-bicep-brm-fork-ci-<GitHub Organization>' ..." -ForegroundColor Yellow
$UAMIName = "id-avm-bicep-brm-fork-ci-$($GitHubOrgName)" }
if ($UAMIRsgName -eq'') {
Write-Host "No value provided for the UAMI Resource Group Name. Defaulting to 'rsg-avm-bicep-brm-fork-ci-<GitHub Organization>-oidc' ..." -ForegroundColor Yellow
$UAMIRsgName = "rsg-avm-bicep-brm-fork-ci-$($GitHubOrgName)-oidc" }
Write-Host "Selecting the subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)' to create Resource Group & UAMI in for OIDC ..." -ForegroundColor Magenta
Select-AzSubscription -Subscription $GitHubSecret_ARM_SUBSCRIPTION_ID
Write-Host ''if ($UAMIRsgLocation -eq'') {
Write-Host "No value provided for the UAMI Location ..." -ForegroundColor Yellow
$UAMIRsgLocation = Read-Host -Prompt "Please enter the location for the UAMI and the Resource Group to be created in for OIDC deployments. e.g. 'uksouth' or 'eastus', etc..." $UAMIRsgLocation = $UAMIRsgLocation.ToLower()
$availableLocations = Get-AzLocation | Where-Object {$_.RegionType -eq'Physical'} | Select-Object -ExpandProperty Location
if ($availableLocations -notcontains $UAMIRsgLocation) {
Write-Host "Invalid location provided. Please provide a valid location from the list below ..." -ForegroundColor Yellow
Write-Host '' Write-Host "Available Locations: $($availableLocations -join ', ')" -ForegroundColor Yellow
do {
$UAMIRsgLocation = Read-Host -Prompt "Please enter the location for the UAMI and the Resource Group to be created in for OIDC deployments. e.g. 'uksouth' or 'eastus', etc..." } until (
$availableLocations -icontains $UAMIRsgLocation
)
}
}
Write-Host "Creating Resource Group for UAMI with the name of '$($UAMIRsgName)' and location of '$($UAMIRsgLocation)'..." -ForegroundColor Magenta
$newUAMIRsg = New-AzResourceGroup -Name $UAMIRsgName -Location $UAMIRsgLocation -ErrorAction Stop
Write-Host "New Resource Group created with a Name of '$($newUAMIRsg.ResourceGroupName)' and a Location of '$($newUAMIRsg.Location)'." -ForegroundColor Green
Write-Host '' Write-Host "Creating UAMI with the name of '$($UAMIName)' and location of '$($UAMIRsgLocation)' in the Resource Group with the name of '$($UAMIRsgName)..." -ForegroundColor Magenta
$newUAMI = New-AzUserAssignedIdentity -ResourceGroupName $newUAMIRsg.ResourceGroupName -Name $UAMIName -Location $newUAMIRsg.Location -ErrorAction Stop
Write-Host "New UAMI created with a Name of '$($newUAMI.Name)' and an Object ID of '$($newUAMI.PrincipalId)'." -ForegroundColor Green
Write-Host '' Write-Host 'Starting 120 second sleep to allow the UAMI to be created and available for Federated Credential creation and RBAC Role Assignments (eventual consistency) ...' -ForegroundColor Yellow
Start-Sleep -Seconds 120# Create Federated Credentials for UAMI for OIDC Write-Host "Creating Federated Credentials for the User-Assigned Managed Identity Name (UAMI) for OIDC ... '$($newUAMI.Name)' for OIDC ..." -ForegroundColor Magenta
New-AzFederatedIdentityCredentials -ResourceGroupName $newUAMIRsg.ResourceGroupName -IdentityName $newUAMI.Name -Name 'avm-gh-env-validation' -Issuer "https://token.actions.githubusercontent.com" -Subject "repo:$($GitHubOrgAndRepoNameCombined):environment:avm-validation" -ErrorAction Stop
Write-Host ''# Create RBAC Role Assignments for UAMI Write-Host "Creating RBAC Role Assignments of 'Owner' for the User-Assigned Managed Identity Name (UAMI) '$($newUAMI.Name)' on the Subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)' ..." -ForegroundColor Magenta
New-AzRoleAssignment -ObjectId $newUAMI.PrincipalId -RoleDefinitionName 'Owner' -Scope "/subscriptions/$($GitHubSecret_ARM_SUBSCRIPTION_ID)" -ErrorAction Stop
Write-Host "RBAC Role Assignments of 'Owner' for the User-Assigned Managed Identity Name (UAMI) '$($newUAMI.Name)' created successfully on the Subscription with the ID of '$($GitHubSecret_ARM_SUBSCRIPTION_ID)'." -ForegroundColor Green
Write-Host ''if ($GitHubSecret_ARM_MGMTGROUP_ID -eq'') {
Write-Host "No Management Group ID provided as input parameter to '-GitHubSecret_ARM_MGMTGROUP_ID', skipping RBAC Role Assignments upon Management Groups" -ForegroundColor Yellow
Write-Host '' }
if ($GitHubSecret_ARM_MGMTGROUP_ID -ne'') {
Write-Host "Creating RBAC Role Assignments of 'Owner' for the User-Assigned Managed Identity Name (UAMI) '$($newSpn.DisplayName)' on the Management Group with the ID of '$($GitHubSecret_ARM_MGMTGROUP_ID)' ..." -ForegroundColor Magenta
New-AzRoleAssignment -ObjectId $newUAMI.PrincipalId -RoleDefinitionName 'Owner' -Scope "/providers/Microsoft.Management/managementGroups/$($GitHubSecret_ARM_MGMTGROUP_ID)" -ErrorAction Stop
Write-Host "RBAC Role Assignments of 'Owner' for the User-Assigned Managed Identity Name (UAMI) '$($newUAMI.Name)' created successfully on the Management Group with the ID of '$($GitHubSecret_ARM_MGMTGROUP_ID)'." -ForegroundColor Green
Write-Host '' }
}
# Set GitHub Repo Secrets (non-OIDC)if ($UseOIDC -eq $false) {
Write-Host "Setting GitHub Secrets on forked repository (non-OIDC) '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Magenta
Write-Host 'Creating and formatting secret `AZURE_CREDENTIALS` with details from SPN creation process (non-OIDC) and other parameter inputs ...' -ForegroundColor Cyan
$FormattedAzureCredentialsSecret = "{ 'clientId': '$($newSpn.AppId)', 'clientSecret': '$($newSpn.PasswordCredentials.SecretText)', 'subscriptionId': '$($GitHubSecret_ARM_SUBSCRIPTION_ID)', 'tenantId': '$($GitHubSecret_ARM_TENANT_ID)' }" $FormattedAzureCredentialsSecretJsonCompressed = $FormattedAzureCredentialsSecret | ConvertFrom-Json | ConvertTo-Json -Compress
if ($GitHubSecret_ARM_MGMTGROUP_ID -ne'') {
gh secret set ARM_MGMTGROUP_ID --body $GitHubSecret_ARM_MGMTGROUP_ID -R $GitHubOrgAndRepoNameCombined
}
gh secret set ARM_SUBSCRIPTION_ID --body $GitHubSecret_ARM_SUBSCRIPTION_ID -R $GitHubOrgAndRepoNameCombined
gh secret set ARM_TENANT_ID --body $GitHubSecret_ARM_TENANT_ID -R $GitHubOrgAndRepoNameCombined
gh secret set AZURE_CREDENTIALS --body $FormattedAzureCredentialsSecretJsonCompressed -R $GitHubOrgAndRepoNameCombined
gh secret set TOKEN_NAMEPREFIX --body $GitHubSecret_TOKEN_NAMEPREFIX -R $GitHubOrgAndRepoNameCombined
Write-Host '' Write-Host "Successfully created and set GitHub Secrets (non-OIDC) on forked repository '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Green
Write-Host ''}
# Set GitHub Repo Secrets & Environment (OIDC)if ($UseOIDC) {
Write-Host "Setting GitHub Environment (avm-validation) and required Secrets on forked repository (OIDC) '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Magenta
Write-Host "Creating 'avm-validation' environment on forked repository' ..." -ForegroundColor Cyan
$GitHubEnvironment = gh api --method PUT -H "Accept: application/vnd.github+json""repos/$($GitHubOrgAndRepoNameCombined)/environments/avm-validation" $GitHubEnvironmentConvertedToJson = $GitHubEnvironment | ConvertFrom-Json -Depth 10if ($GitHubEnvironmentConvertedToJson.name -ne'avm-validation') {
throw"Failed to create 'avm-validation' environment on forked repository. Please check the error message above, resolve any issues, and try again." }
Write-Host "Successfully created 'avm-validation' environment on forked repository' ..." -ForegroundColor Green
Write-Host '' Write-Host "Creating and formatting secrets for 'avm-validation' environment with details from UAMI creation process (OIDC) and other parameter inputs ..." -ForegroundColor Cyan
gh secret set VALIDATE_CLIENT_ID --body $newUAMI.ClientId -R $GitHubOrgAndRepoNameCombined -e 'avm-validation' gh secret set VALIDATE_SUBSCRIPTION_ID --body $GitHubSecret_ARM_SUBSCRIPTION_ID -R $GitHubOrgAndRepoNameCombined -e 'avm-validation' gh secret set VALIDATE_TENANT_ID --body $GitHubSecret_ARM_TENANT_ID -R $GitHubOrgAndRepoNameCombined -e 'avm-validation' Write-Host "Creating and formatting secrets for repo with details from UAMI creation process (OIDC) and other parameter inputs ..." -ForegroundColor Cyan
if ($GitHubSecret_ARM_MGMTGROUP_ID -ne'') {
gh secret set ARM_MGMTGROUP_ID --body $GitHubSecret_ARM_MGMTGROUP_ID -R $GitHubOrgAndRepoNameCombined
}
gh secret set ARM_SUBSCRIPTION_ID --body $GitHubSecret_ARM_SUBSCRIPTION_ID -R $GitHubOrgAndRepoNameCombined
gh secret set ARM_TENANT_ID --body $GitHubSecret_ARM_TENANT_ID -R $GitHubOrgAndRepoNameCombined
gh secret set TOKEN_NAMEPREFIX --body $GitHubSecret_TOKEN_NAMEPREFIX -R $GitHubOrgAndRepoNameCombined
Write-Host '' Write-Host "Successfully created and set GitHub Secrets in 'avm-validation' environment and repo (OIDC) on forked repository '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Green
Write-Host ''}
Write-Host "Opening browser so you can enable GitHub Actions on newly forked repository '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Magenta
Write-Host "Please select click on the green button stating 'I understand my workflows, go ahead and enable them' to enable actions/workflows on your forked repository via the website that has appeared in your browser window and then return to this terminal session to continue ..." -ForegroundColor Yellow
Start-Process "https://github.com/$($GitHubOrgAndRepoNameCombined)/actions" -ErrorAction Stop
Write-Host ''$GitHubWorkflowPlatformToggleWorkflows = '.Platform - Toggle AVM workflows'$GitHubWorkflowPlatformToggleWorkflowsFileName = 'platform.toggle-avm-workflows.yml'do {
Write-Host "Did you successfully enable the GitHub Actions/Workflows on your forked repository '$($GitHubOrgAndRepoNameCombined)'? Please enter 'y' or 'n'." -ForegroundColor Yellow
$userInput = Read-Host
$userInput = $userInput.ToLower()
switch ($userInput) {
'y' {
Write-Host '' Write-Host "User Confirmed. Proceeding to trigger workflow of '$($GitHubWorkflowPlatformToggleWorkflows)' to disable all workflows as per: https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/enable-or-disable-workflows/..." -ForegroundColor Green
Write-Host ''break }
'n' {
Write-Host '' Write-Host 'User stated no. Ending script here. Please review and complete any of the steps you have not completed, likely just enabling GitHub Actions/Workflows on your forked repository and then disabling all workflows as per: https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/enable-or-disable-workflows/' -ForegroundColor Yellow
exit
}
default {
Write-Host '' Write-Host "Invalid input. Please enter 'y' or 'n'." -ForegroundColor Red
Write-Host '' }
}
} while ($userInput -ne'y'-and $userInput -ne'n')
Write-Host "Setting Read/Write Workflow permissions on forked repository '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Magenta
gh api --method PUT -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28""/repos/$($GitHubOrgAndRepoNameCombined)/actions/permissions/workflow"-f"default_workflow_permissions=write"Write-Host ''Write-Host "Triggering '$($GitHubWorkflowPlatformToggleWorkflows) on '$($GitHubOrgAndRepoNameCombined)' ..." -ForegroundColor Magenta
Write-Host ''gh workflow run $GitHubWorkflowPlatformToggleWorkflows -R $GitHubOrgAndRepoNameCombined
Write-Host ''Write-Host 'Starting 120 second sleep to allow the workflow run to complete ...' -ForegroundColor Yellow
Start-Sleep -Seconds 120Write-Host ''Write-Host "Workflow '$($GitHubWorkflowPlatformToggleWorkflows) on '$($GitHubOrgAndRepoNameCombined)' should have now completed, opening workflow in browser so you can check ..." -ForegroundColor Magenta
Start-Process "https://github.com/$($GitHubOrgAndRepoNameCombined)/actions/workflows/$($GitHubWorkflowPlatformToggleWorkflowsFileName)" -ErrorAction Stop
Write-Host ''Write-Host "Script execution complete. Fork of '$($GitHubOrgAndRepoNameCombined)' created and configured and cloned to '$($ClonedRepoDirectoryLocation)' as per Bicep contribution guide: https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/ you are now ready to proceed from step 4. Opening the Bicep Contribution Guide for you to review and continue..." -ForegroundColor Green
Start-Process 'https://azure.github.io/Azure-Verified-Modules/contributing/bicep/bicep-contribution-flow/'
Each time in the following sections we refer to ‘your xyz’, it is an indicator that you have to change something in your own environment.
Bicep AVM Modules (Resource, Pattern and Utility modules) are located in the /avm directory of the Azure/bicep-registry-modules repository, as per SNFR19.
Module owners are expected to fork the Azure/bicep-registry-modules repository and work on a branch from within their fork, before creating a Pull Request (PR) back into the Azure/bicep-registry-modules repository’s upstream main branch.
To do so, simply navigate to the Public Bicep Registry repository, select the 'Fork' button to the top right of the UI, select where the fork should be created (i.e., the owning organization) and finally click ‘Create fork’.
1.1 Create a GitHub environment
Create the avm-validation environment in your fork.
β How to: Create an environment in GitHub
Navigate to the repository’s Settings.
In the list of settings, expand Environments. You can create a new environment by selecting New environment on the top right.
In the opening view, provide avm-validation for the environment Name. Click on the Configure environment button.
Make sure to use a Managed Identity for OIDC as instructed below, not a Service Principal. Azure access token issued by Managed Identities is expected to have an expiration of 24 hours by default. With Service Principal, instead, it would be only 1 hour - which is not sufficient for many deployment pipelines.
Create a new or leverage an existing user-assigned managed identity with at least Contributor & User Access Administrator permissions on the Management-Group/Subscription you want to test the modules in. You may find creating an Owner role assignment is more efficient and avoids some validation failures for some modules. You might find the following links useful:
Some Azure resources may require additional roles to be assigned to the deployment identity. An example is the avm/res/aad/domain-service module, which requires the deployment identity to have the Domain Services Contributor Azure role to create the required Domain Services resources.
In those cases, for the first PR adding such modules to the public registry, we recommend the author to reach out to AVM maintainers or, alternatively, to create a CI environment GitHub issue in BRM, specifying the additional prerequisites. This ensures that the required additional roles get assigned in the upstream CI environment before the corresponding PR gets merged.
Configure a federated identity credential on a user-assigned managed identity to trust tokens issued by GitHub Actions to your GitHub repository.
In the Microsoft Entra admin center, navigate to the user-assigned managed identity you created. Under Settings in the left nav bar, select Federated credentials and then Add Credential.
In the Federated credential scenario dropdown box, select GitHub Actions deploying Azure resources
For the Organization, specify your GitHub organization name, for the Repository the value bicep-registry-modules.
For the Entity type, select Environment and specify the value avm-validation.
Add a Name for the federated credential, for example, avm-gh-env-validation.
The Issuer, Audiences, and Subject identifier fields auto-populate based on the values you entered.
Select Add to configure the federated credential.
You might find the following links & information useful:
If configuring the federated credential via API (e.g. Bicep, PowerShell etc.), you will need the following information points that are configured automatically for you via the portal experience:
β Option 2 [Deprecated]: Configure Service Principal + Secret
Create a new or leverage an existing Service Principal with at least Contributor & User Access Administrator permissions on the Management-Group/Subscription you want to test the modules in. You may find creating an Owner role assignment is more efficient and avoids some validation failures for some modules. You might find the following links useful:
To use the Continuous Integration environment’s workflows you should set up the following repository secrets:
Secret Name
Example
Description
ARM_MGMTGROUP_ID
11111111-1111-1111-1111-111111111111
The group ID of the management group to test-deploy modules in. Is needed for resources that are deployed to the management group scope.
ARM_SUBSCRIPTION_ID
22222222-2222-2222-2222-222222222222
The ID of the subscription to test-deploy modules in. Is needed for resources that are deployed to the subscription scope. Note: This repository secret will be deprecated in favor of the VALIDATE_SUBSCRIPTION_ID environment secret required by the OIDC authentication.
ARM_TENANT_ID
33333333-3333-3333-3333-333333333333
The tenant ID of the Azure Active Directory tenant to test-deploy modules in. Is needed for resources that are deployed to the tenant scope. Note: This repository secret will be deprecated in favor of the VALIDATE_TENANT_ID environment secret required by the OIDC authentication.
TOKEN_NAMEPREFIX
cntso
Required. A short (3-5 character length), unique string that should be included in any deployment to Azure. Usually, AVM Bicep test cases require this value to ensure no two contributors deploy resources with the same name - which is especially important for resources that require a globally unique name (e.g., Key Vault). These characters will be used as part of each resource’s name during deployment. For more information, see the [Special case: TOKEN_NAMEPREFIX] note below.
Special case: TOKEN_NAMEPREFIX
To lower the barrier to entry and allow users to easily define their own naming conventions, we introduced a default ’name prefix’ for all deployed resources.
This prefix is only used by the CI environment you validate your modules in, and doesn’t affect the naming of any resources you deploy as part of any solutions (applications/workloads) based on the modules.
Each workflow in AVM deploying resources uses a logic that automatically replaces “tokens” (i.e., placeholders) in any module test file. These tokens are, for example, included in the resources names (e.g. 'name: kvlt-${namePrefix}'). Tokens are stored as repository secrets to facilitate maintenance.
β How to: Add a repository secret to GitHub
Navigate to the repository’s Settings.
In the list of settings, expand Secrets and select Actions. You can create a new repository secret by selecting New repository secret on the top right.
In the opening view, you can create a secret by providing a secret Name, a secret Value, followed by a click on the Add secret button.
3.1.2 Authentication secrets
In addition to shared repository secrets detailed above, additional GitHub secrets are required to allow the deploying identity to authenticate to Azure.
Expand and follow the option corresponding to the deployment identity setup chosen at Step 2 and use the information you gathered during that step.
β Option 1 [Recommended]: Authenticate via OIDC
Create the following environment secrets in the avm-validation GitHub environment created at Step 1
Secret Name
Example
Description
VALIDATE_CLIENT_ID
44444444-4444-4444-4444-444444444444
The login credentials of the deployment principal used to log into the target Azure environment to test in. See the deployment credentials format.
VALIDATE_SUBSCRIPTION_ID
22222222-2222-2222-2222-222222222222
Same as the ARM_SUBSCRIPTION_ID repository secret set up above. The ID of the subscription to test-deploy modules in. Is needed for resources that are deployed to the subscription scope.
VALIDATE_TENANT_ID
33333333-3333-3333-3333-333333333333
Same as the ARM_TENANT_ID repository secret set up above. The tenant ID of the Azure Active Directory tenant to test-deploy modules in. Is needed for resources that are deployed to the tenant scope.
β How to: Add an environment secret to GitHub
Navigate to the repository’s Settings.
In the list of settings, select Environments. Click on the previously created avm-validation environment.
In the Environment secrets Section click on the Add environment secret button.
In the opening view, you can create a secret by providing a secret Name, a secret Value, followed by a click on the Add secret button.
β Option 2 [Deprecated]: Authenticate via Service Principal + Secret
Create the following environment repository secret:
The login credentials of the deployment principal used to log into the target Azure environment to test in. See the deployment credentials format. For more information, see the [Special case: AZURE_CREDENTIALS] note below.
Special case: AZURE_CREDENTIALS
This secret represent the service connection to Azure, and its value is a compressed JSON object that must match the following format:
Make sure you create this object as one continuous string as shown above - using the information you collected during Step 2. Failing to format the secret as above, causes GitHub to consider each line of the JSON object as a separate secret string. See the deployment credentials format for more information.
3.1.3 Custom CI parameters
For test-specific template inputs, create GitHub Actions secrets or variables at repository scope or in the avm-validation environment. Prefer readable CI_ names such as CI_MY_SECRET for mySecret; underscores after the prefix are ignored. Use CI__ to preserve literal underscores in parameter names. Use secrets for private values and variables only for clearly non-sensitive configuration. These inputs are separate from the OIDC authentication secrets above.
See Custom CI parameters for parameter naming, secure handling, precedence, and migration from the deprecated CI_KEY_VAULT_NAME Key Vault fallback.
3.2. Enable actions
Finally, ‘GitHub Actions’ are disabled by default and hence, must be enabled first.
To do so, perform the following steps:
Navigate to the Actions tab on the top of the repository page.
Next, select ‘I understand my workflows, go ahead and enable them’.
3.3. Set Read/Write Workflow permissions
To let the workflow engine publish their results into your repository, you have to enable the read / write access for the GitHub actions.
Navigate to the Settings tab on the top of your repository page.
Within the section Code and automation click on Actions and General
Make sure to enable Read and write permissions
Tip
Once you enabled the GitHub actions, your workflows will behave as they do in the upstream repository. This includes a scheduled trigger to continuously check that all modules are working and compliant with the latest tests. However, testing all modules can incur substantial costs with the target subscription. Therefore, we recommend disabling all workflows of modules you are not working on. To make this as easy as possible, we created a workflow that disables/enables workflows based on a selected toggle & naming pattern. For more information on how to use this workflow, please refer to the corresponding documentation.
4. Implement your contribution
To implement your contribution, we kindly ask you to first review the Bicep specifications and composition guidelines in particular to make sure your contribution complies with the repository’s design and principles.
If you’re working on a new module, we’d also ask you to create its corresponding workflow file. Each module has its own file, but only differs in very few details, such as its triggers and pipeline variables. As a result, you can either copy & update any other module workflow file (starting with 'avm.[res|ptn|utl].') or leverage the following template:
β Module workflow template
# >>> UPDATE to for example "avm.res.key-vault.vault" and remove this commentname: "avm.[res|ptn|utl].[provider-namespace].[resource-type]"on:
workflow_dispatch:
inputs:
staticValidation:
type: booleandescription: "Execute static validation"required: falsedefault: truedeploymentValidation:
type: booleandescription: "Execute deployment validation"required: falsedefault: trueremoveDeployment:
type: booleandescription: "Remove deployed module"required: falsedefault: truecustomLocation:
type: stringdescription: "Default location overwrite (e.g., eastus)"required: falsepush:
branches:
- mainpaths:
# >>> UPDATE to for example ".github/workflows/avm.res.key-vault.vault.yml" and remove this comment - ".github/workflows/avm.[res|ptn|utl].[provider-namespace].[resource-type].yml"# >>> UPDATE to for example "avm/res/key-vault/vault/**" and remove this comment - "avm/[res|ptn|utl]/[provider-namespace]/[resource-type]/**" - "!*/**/README.md" - "!avm/**/metadata.json"env:
# >>> UPDATE to for example "avm/res/key-vault/vault" and remove this commentmodulePath: "avm/[res|ptn|utl]/[provider-namespace]/[resource-type]"# >>> Update to for example ".github/workflows/avm.res.key-vault.vault.yml" and remove this commentworkflowPath: ".github/workflows/avm.[res|ptn|utl].[provider-namespace].[resource-type].yml"concurrency:
group: ${{ github.workflow }}jobs:
############################ Initialize pipeline ############################job_initialize_pipeline:
runs-on: ubuntu-latestname: "Initialize pipeline"if: ${{ !cancelled() && !(github.repository != 'Azure/bicep-registry-modules' && github.event_name != 'workflow_dispatch') }}steps:
- name: "Checkout"uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09# v5.1.0with:
fetch-depth: 0 - name: "Set input parameters to output variables"id: get-workflow-paramuses: ./.github/actions/templates/avm-getWorkflowInputwith:
workflowPath: "${{ env.workflowPath}}" - name: "Get module test file paths"id: get-module-test-file-pathsuses: ./.github/actions/templates/avm-getModuleTestFileswith:
modulePath: "${{ env.modulePath }}"outputs:
workflowInput: ${{ steps.get-workflow-param.outputs.workflowInput }}moduleTestFilePaths: ${{ steps.get-module-test-file-paths.outputs.moduleTestFilePaths }}psRuleModuleTestFilePaths: ${{ steps.get-module-test-file-paths.outputs.psRuleModuleTestFilePaths }}modulePath: "${{ env.modulePath }}"############################### Call reusable workflow ###############################call-workflow-passing-data:
name: "Run"permissions:
id-token: write# For OIDCcontents: write# For release tagsneeds:
- job_initialize_pipelineuses: ./.github/workflows/avm.template.module.ymlwith:
workflowInput: "${{ needs.job_initialize_pipeline.outputs.workflowInput }}"moduleTestFilePaths: "${{ needs.job_initialize_pipeline.outputs.moduleTestFilePaths }}"psRuleModuleTestFilePaths: "${{ needs.job_initialize_pipeline.outputs.psRuleModuleTestFilePaths }}"modulePath: "${{ needs.job_initialize_pipeline.outputs.modulePath}}"secrets: inherit
Note
The workflow is configured to be triggered by changes in the main branch of Upstream (i.e., Azure/bicep-registry-modules) that could affect the module or its validation. Changes limited to README.md or metadata.json files, including child-module metadata, do not trigger the workflow or a release. To publish a metadata change, including a telemetryIdPrefix change, include it with a normal source or version release change.
In a fork, the workflow is stopped immediately after being triggered due to the condition:
# Only run if not canceled and not in a fork, unless triggered by a workflow_dispatch eventif: ${{ !cancelled() && !(github.repository != 'Azure/bicep-registry-modules' && github.event_name != 'workflow_dispatch') }}
This condition prevents accidentally triggering a large amount of module workflows, e.g., when merging upstream changes into your fork.
In forks, workflow validation remains possible through explicit runs (that is, by using the Β workflow_dispatchΒ event).
Tip
After any change to a module and before running tests, we highly recommend running the Set-AVMModule utility to update all module files that are auto-generated (e.g., the main.json & readme.md files).
5. Create/Update and run tests
Before opening a Pull Request to the Bicep Public Registry, ensure your module is ready for publishing, by validating that it meets all the Testing Specifications as per SNFR1, SNFR2, SNFR3, SNFR4, SNFR5, SNFR6, SNFR7.
For example, to meet SNFR2, ensure the updated module is deployable against a testing Azure subscription and compliant with the intended configuration.
Depending on the type of contribution you implemented (for example, a new resource module feature) we would kindly ask you to also update the e2e test run by the pipeline. For a new parameter this could mean to either add its usage to an existing test file, or to add an entirely new test as per BCPRMNFR1.
Once the contribution is implemented and the changes are pushed to your forked repository, we kindly ask you to validate your updates in your own cloud environment before requesting to merge them to the main repo. Test your code leveraging the forked AVM CI environment you configured before
Tip
In case your contribution involves changes to a module, you can also optionally leverage the Validate module locally utility to validate the updated module from your local host before validating it through its pipeline.
Creating end-to-end tests
As per BCPRMNFR1, a resource module must contain a minimum set of deployment test cases, while for pattern modules there is no restriction on the naming each deployment test must have. In either case, you’re free to implement any additional, meaningful test that you see fit. Each test is implemented in its own test folder, containing at least a main.test.bicep and optionally any amount of extra deployment files that you may require (e.g., to deploy dependencies using a dependencies.bicep that you reference in the test template file).
To get started implementing your test in the main.test.bicep file, we recommend the following guidelines:
As per BCPNFR13, each main.test.bicep file should implement metadata to render the test more meaningful in the documentation
The main.test.bicep file should deploy any immediate dependencies (e.g., a resource group, if required) and invoke the module’s main template while providing all parameters for a given test scenario.
Parameters
Each file should define a parameter serviceShort. This parameter should be unique to this file (i.e, no two test files should share the same) as it is injected into all resource deployments, making them unique too and account for corresponding requirements.
As a reference you can create a identifier by combining a substring of the resource type and test scenario (e.g., in case of a Linux Virtual Machine Deployment: vmlin).
For the substring, we recommend to take the first character and subsequent ‘first’ character from the resource type identifier and combine them into one string. Following you can find a few examples for reference:
db-for-postgre-sql/flexible-server with a test folder default could be: dfpsfsdef
storage/storage-account with a test folder waf-aligned could be: ssawaf
π‘ If the combination of the servicesShort with the rest of a resource name becomes too long, it may be necessary to bend the above recommendations and shorten the name. This can especially happen when deploying resources such as Virtual Machines or Storage Accounts that only allow comparatively short names.
If the module deploys a resource-group-level resource, the template should further have a resourceGroupName parameter and subsequent resource deployment. As a reference for the default name you can use dep-<namePrefix><providerNamespace>.<resourceType>-${serviceShort}-rg.
Each file should also provide a location parameter that may default to the deployments default location
It is recommended to define all major resource names in the main.test.bicep file as it makes later maintenance easier. To implement this, make sure to pass all resource names to any referenced module (including any resource deployed in the dependencies.bicep).
Further, for any test file (including the dependencies.bicep file), the usage of variables should be reduced to the absolute minimum. In other words: You should only use variables if you must use them in more than one place. The idea is to keep the test files as simple as possible
References to dependencies should be implemented using resource references in combination with outputs. In other words: You should not hardcode any references into the module template’s deployment. Instead use references such as nestedDependencies.outputs.managedIdentityPrincipalId
Important
As per BCPNFR12 you must use the header module testDeployment '../.*main.bicep' = when invoking the module’s template.
The dependencies.bicep should optionally be used if any additional dependencies must be deployed into a nested scope (e.g. into a deployed Resource Group).
Note that you can reuse many of the assets implemented in other modules. For example, there are many recurring implementations for Managed Identities, Key Vaults, Virtual Network deployments, etc.
A special case to point out is the implementation of Key Vaults that require purge protection (for example, for Customer Managed Keys). As this implies that we cannot fully clean up a test deployment, it is recommended to generate a new name for this resource upon each pipeline run using the output of the utcNow() function at the time.
π If your test case requires environment-specific inputs (e.g., tenant-specific object IDs or secrets), use Custom CI parameters to supply them from GitHub Actions secrets or variables. The CI passes matching values as deployment parameters; it does not substitute them into the test source.
Reusable assets
The e2e template assets provide additional scripts and utilities that may be of use to module owners/contributors. These contain both scripts and Bicep templates that you can re-use in your test files (e.g., to deploy standadized dependencies, or to generate keys using deployment scripts).
Example: Certificate creation script
If you need a Deployment Script to set additional non-template resources up (for example certificates/files, etc.), we recommend to store it as a file in the shared utilities/e2e-template-assets/scripts folder and load it using the template function loadTextContent() (for example: scriptContent: loadTextContent('../../../../../../utilities/e2e-template-assets/scripts/New-SSHKey.ps1')). This approach makes it easier to test & validate the logic and further allows reusing the same logic across multiple test cases.
Example: Diagnostic Settings dependencies
To test the numerous diagnostic settings targets (Log Analytics Workspace, Storage Account, Event Hub, etc.) the AVM core team have provided a dependencies .bicep file to help create all these pre-requisite targets that will be needed during test runs.
β Diagnostic Settings Dependencies - Bicep File
// ========== //// Parameters //// ========== //@description('Required. The name of the storage account to create.')
@maxLength(24)
param storageAccountName string
@description('Required. The name of the log analytics workspace to create.')
param logAnalyticsWorkspaceName string
@description('Required. The name of the event hub namespace to create.')
param eventHubNamespaceName string
@description('Required. The name of the event hub to create inside the event hub namespace.')
param eventHubNamespaceEventHubName string
@description('Optional. The location to deploy resources to.')
param location string = resourceGroup().location
// ============ //// Dependencies //// ============ //resource storageAccount 'Microsoft.Storage/storageAccounts@2021-08-01' = {
name: storageAccountName
location: location
kind: 'StorageV2' sku: {
name: 'Standard_LRS' }
properties: {
allowBlobPublicAccess: false }
}
resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2021-12-01-preview' = {
name: logAnalyticsWorkspaceName
location: location
}
resource eventHubNamespace 'Microsoft.EventHub/namespaces@2021-11-01' = {
name: eventHubNamespaceName
location: location
resource eventHub 'eventhubs@2021-11-01' = {
name: eventHubNamespaceEventHubName
}
resource authorizationRule 'authorizationRules@2021-06-01-preview' = {
name: 'RootManageSharedAccessKey' properties: {
rights: [
'Listen''Manage''Send' ]
}
}
}
// ======= //// Outputs //// ======= //@description('The resource ID of the created Storage Account.')
output storageAccountResourceId string = storageAccount.id
@description('The resource ID of the created Log Analytics Workspace.')
output logAnalyticsWorkspaceResourceId string = logAnalyticsWorkspace.id
@description('The resource ID of the created Event Hub Namespace.')
output eventHubNamespaceResourceId string = eventHubNamespace.id
@description('The resource ID of the created Event Hub Namespace Authorization Rule.')
output eventHubAuthorizationRuleId string = eventHubNamespace::authorizationRule.id
@description('The name of the created Event Hub Namespace Event Hub.')
output eventHubNamespaceEventHubName string = eventHubNamespace::eventHub.name
6. Create a Pull Request to the Public Bicep Registry
Finally, once you are satisfied with your contribution and validated it, open a pull request for review. Make sure you:
Provide a meaningful title in the form of feat: <module name> to align with the Semantic PR Check.
Provide a meaningful description.
Follow instructions you find in the PR template.
If applicable (i.e., a module is created/updated), please reference the badge status of your pipeline run. This badge will show the reviewer that the code changes were successfully validated & tested in your environment. To create a badge, first select the three dots (...) at the top right of the pipeline, and then chose the Create status badge option.
In the opening pop-up, you first need to select your branch and then click on the Copy status badge Markdown
Note
If you receive any comments for your pull request, please adhere to the following practices
If it is a ‘suggestion’ that you agree with, you can directly commit it into your branch by selecting the ‘Apply suggestion’ button, auto-resolving the comment
If it’s a regular comment that you agree with, please address its ask and leave a comment indicating the same. Do not resolve it yourself as this renders a re-review a lot harder for the reviewer.
7. Get your pull request approved
To publish a new module or a new version of an existing module, each Pull Request (PR) MUST be reviewed and approved before being merged and published in the Public Bicep Registry. A contributor (the submitter of the PR) cannot approve their own PR.
The reviewer-routing workflow requests module owners from root metadata.json and applies triage labels when active. Reviewer requests do not set approval requirements.
Important
As part of the PR review process, the submitter (contributor) MUST address any comments raised by the reviewers and request a new review - and repeat this process until the PR is approved. Once the PR is merged, the module owner MUST ensure that the related GitHub Actions workflow has successfully published the new version of the module.
7.1. Publishing a new module
When publishing a net new module for the first time ever, the PR MUST be reviewed and approved by a member of the core team.
7.2. Publishing a new version of an existing module
For ordinary code changes in an existing Bicep module, any eligible BRM repository team member may approve and merge under repository rules; a module owner’s approval is not mandatory. If you are the sole owner and author, request another eligible reviewer. Changes to metadata.json still require metadata code-owner review. Other protected paths follow their applicable CODEOWNERS rules.
Subsections of Contribution Flow
Child Module Publishing
Child resources are resources that exist only within the scope of another resource. For example, a virtual network subnet cannot exist without a virtual network. The subnet is a child resource of the virtual network.
In the context of AVM, particularly AVM Bicep resource modules, child modules are modules deploying child resources. They are implemented within the scope of their corresponding parent resource modules. For example, the module avm/res/network/virtual-network/subnet deploys a virtual network subnet and is a child module of its parent virtual network module avm/res/network/virtual-network.
By default, child modules are not published to the public bicep registry independently from their parents. They need to be explicitly enabled for publishing to be directly referenced from the registry.
This page covers step-by-step guidelines to publish a bicep child module.
Important
The child module publishing process is currently in a pilot/preview phase. This means it may not be as smooth as the general module publishing.
The core team is currently working on additional automation, with the goal of improving efficiency in addressing child module publishing requests.
Note
Child module publishing currently only applies to resource modules.
Supporting child module publishing for other module categories, such as pattern and utility modules, is not planned at this time.
Quick guide
Use this section for a fast overview on how to publish a child module. For a step-by-step explanation with detailed instructions, refer to the following sections.
Child module template: Add enableTelemetry parameter and avmTelemetry deployment to child main.bicep template.
Parent module template: In the main.bicep template of the child module direct parent, add a enableReferencedModulesTelemetry variable with a value of false, and pass it as the enableTelemetry value down to the child module deployment.
Version: Add the version.json file to the child module folder and set version to 0.1.
Changelog: Add a new CHANGELOG.md file to the child module folder and update the changelog of all its versioned parents with a new patch version, up to the top-level parent.
Set-AVMModule: Run the Set-AVMModule utility explicitly on the affected bicep modules, i.e., the child module(s) and all their parent modules up to the top-level module, test your changes and raise a PR.
Prerequisites
Before jumping into the implementation, make sure the following prerequisites are in place:
Please understand the difference between publishing an existing child module and extending a parent module with a not yet implemented child module functionality.
The Bicep Child Module Proposal issue primarily intends to cover the former, i.e. to publish a child module already existing in the BRM (Bicep Registry Modules) repository source code. However, the same issue allows also to request the development of the child module functionality, although the best way to address new functionality is to raise a feature request via the the AVM Module issue.
Telemetry ID prefix assigned
Follow the below steps to check the child module telemetry ID prefix.
Note
If the Bicep Child Module Proposal issue was just created, please allow a few days for the telemetry ID prefix to be assigned before reaching out.
Check telemetryIdPrefix in the child’s own metadata.json and keep it consistent with the child module source. Record only the assigned identifier through metadata review. Ownership is inherited from the root.
You can also look up the assigned prefix in the published index:
Search for the child module name in the ModuleName field.
Verify if the corresponding value exists in the TelemetryIdPrefix field. Note down the value as you will need it in the implementation phase.
If not found, please reach out to the core team, mentioning the @Azure/azure-verified-modules-tooling-contributors via the Bicep Child Module Proposal issue.
If the identifier is missing or conflicts with the index, ask the core team to resolve it. Do not invent an identifier or copy the parent’s prefix.
Module registered in the MAR-file
Ensure that the child module is registered in the MAR file. If not, please reach out to the core team, mentioning the @Azure/azure-verified-modules-tooling-contributors via the Bicep Child Module Proposal issue.
Metadata approval does not replace MAR registration or approval to publish the child module.
Note
The MAR-file can only be accessed by Microsoft FTEs. If you are missing access, please reach out to the parent module owner for help.
Implementation
The quickest way to get the child module published is to enable it yourself, contributing via a pull request to the BRM repository.
Note
Publishing a child module does not change the folder hierarchy of the parent and child modules. The child module remains in its existing location within the parent module’s folder structure. No files or folders need to be moved or reorganized.
Please follow the steps below:
Make sure the child module name is listed in the publishing allowed list child-module-publish-allowed-list.json. If not, add it to the file, keeping an alphabetical order. This step is relevant until the process is in a pilot phase.
Update the child module main.bicep template to support telemetry, as per SFR4, SFR3 and BCPFR4
Add the enableTelemetry parameter with a default value of true. Place it as the last param declaration, immediately before the first var declaration.
Add the avmTelemetry deployment, referencing below template. Make sure to replace the <ReplaceWith-TelemetryIdPrefix> placeholder with the assigned telemetry ID prefix value that you noted down when checking prerequisites.
Update the main.bicep template of the child module direct parent, as per BCPFR7.
Add the enableReferencedModulesTelemetry variable with a default value of false. Place it as the last var declaration, immediately before the first resource declaration.
var enableReferencedModulesTelemetry = false
Pass the enableReferencedModulesTelemetry variable as the enableTelemetry value down to the child module deployment.
enableTelemetry: enableReferencedModulesTelemetry
Add the version.json file to the child module folder and set version to 0.1.
Add a new CHANGELOG.md file to the child module folder, with the following sample content. Make sure to replace the <avm/res/path/to/child-module> placeholder with the name of the child module.
# Changelog
The latest version of the changelog can be found [here](https://github.com/Azure/bicep-registry-modules/blob/main/<avm/res/path/to/child-module>/CHANGELOG.md).
## 0.1.0
### Changes
- Initial version
### Breaking Changes
- None
Check the list of affected modules. Update the changelog of all the affected modules with a version.json. Add a new patch version for each. Refer below for an example content section:
Run the Set-AVMModule utility, calling it explicitly on all affected modules.
foreach ($modulePath in $affectedModulePaths) {
Set-AVMModule -ModuleFolderPath $modulePath
}
Test your changes via the top-level module pipeline, raise a PR and attach a status badge proving successful validation.
Note
Existing tests for the parent module do not need to be updated when publishing a child module. The changes required for child module publishing (telemetry support, version file, and changelogs) do not affect the module’s test cases.
Tip
Reference This pull request as an example for proposing a child module for publishing.
Custom CI Parameters
Use GitHub Actions secrets or variables to supply environment-specific inputs to your main.test.bicep end-to-end tests, such as tenant-specific object IDs or credentials. This avoids hardcoding values that differ between your fork and the upstream AVM test environment. Never commit private values to test files.
These are additional template inputs, not Azure login credentials. Continue using OIDC with the avm-validation environment and its VALIDATE_CLIENT_ID, VALIDATE_TENANT_ID, and VALIDATE_SUBSCRIPTION_ID secrets, as described in Authentication secrets.
Forks and upstream validation
Configure values separately in your fork: upstream repository and environment secrets are not inherited. This feature does not bypass GitHub’s restrictions on secret availability for workflows triggered by contributions from forks.
When adding a required input, ask the maintainers to configure the corresponding GitHub secret or variable in the upstream environment before merging your contribution. Share the parameter name and purpose, never its private value.
Setup
Declare the parameters in your main.test.bicep file and reference them as normal Bicep parameters. Keep an empty default for these string inputs so PSRule scans have a value for every parameter.
For example:
@description('Required. Credential supplied by the CI_MY_SECRET GitHub Actions secret.')
@secure()
param mySecret string = ''@description('Optional. Non-sensitive label used by this test.')
param deploymentLabel string = ''
Add the corresponding values under Settings > Secrets and variables > Actions in your repository, or under Settings > Environments > avm-validation for environment-scoped values:
GitHub Actions name
Store as
Template parameter
Value
CI_MY_SECRET
Secret
mySecret
Set privately; do not put the value in source control or logs.
CI_DEPLOYMENT_LABEL
Variable
deploymentLabel
For example, the non-sensitive label avm-ci.
GitHub secret and variable names cannot contain hyphens. Prefer readable CI_ names for usual camelCase parameters; reserve CI__ for literal parameter names, including underscores.
With CI_, the CI strips the single prefix and removes all suffix underscores before matching. With CI__, it strips the double prefix and preserves suffix underscores. Both modes match actual declared test parameters case-insensitively and pass their canonical Bicep spelling. Only matching parameters are supplied.
These are alternative spellings; choose one name for each input:
GitHub Actions name
Matching template parameter
CI_ADMIN_MEMBERS_SECRET
adminMembersSecret
CI_ADMINMEMBERSSECRET
adminMembersSecret
CI__ADMIN_MEMBERS_SECRET
admin_members_secret, not adminMembersSecret
CI__ADMINMEMBERSSECRET
adminMembersSecret
CI___NAME
_name
Reserved name:CI_KEY_VAULT_NAME remains the existing vault selector and is excluded from template input mapping. To supply a test parameter named keyVaultName, use CI__KEYVAULTNAME.
String inputs, including secure strings, are used as supplied. For Boolean, integer, array, and object parameters (including secure objects), supply valid JSON matching the compiled template parameter type.
Protect sensitive inputs
Use GitHub secrets for private values, and variables only for clearly non-sensitive configuration. Keep @secure() on sensitive Bicep parameters. The CI converts secure strings to PowerShell SecureString values and parses secure objects into dictionaries, preserving the template’s ARM secureObject declaration. This also applies to inputs from GitHub variables. Neither @secure() nor these conversions make a GitHub variable’s stored value private.
How it works
Workflows use the resolved GitHub secrets and vars contexts. Both repository-scoped and environment-scoped values are supported; GitHub applies its own scope precedence within each context. Use the same GitHub spelling across scopes when overriding an input so GitHub can apply that scope precedence to the override.
After name resolution, values for the same template parameter are selected in this order:
Source priority comes first: a CI__ secret still beats a CI_ variable. Within one source category (secrets or variables), CI_ wins over CI__ when both resolve to the same parameter; for example, secret CI_FOO beats secret CI__FOO for foo.
Multiple aliases for the same parameter within a source category’s winning prefix remain ambiguous and fail. For example, secrets CI_ADMIN_MEMBERS_SECRET and CI_ADMINMEMBERSSECRET both resolve to adminMembersSecret through CI_; neither has priority over the other.
Names resolving to different declared parameters remain independent: CI_ADMIN_MEMBERS_SECRET supplies adminMembersSecret, while CI__ADMIN_MEMBERS_SECRET supplies admin_members_secret.
A configured empty winning value, including a CI_ value, still wins and does not trigger fallback to a lower-priority prefix or source.
The CI passes the resolved values through the PowerShell AdditionalParameters object to the applicable Test-Az*Deployment and New-Az*Deployment cmdlets. This is runtime deployment parameter injection, not source token substitution or a .bicepparam file mechanism.
Legacy Key Vault fallback
CI Key Vault support is deprecated
vars.CI_KEY_VAULT_NAME remains an optional fallback for existing setups. Using it emits a visible GitHub Actions deprecation warning, and support may be removed in a future release. Use GitHub Actions secrets or variables for new setups.
Existing setups can retain the CI_KEY_VAULT_NAME repository variable, the vault, and its CI--prefixed secrets. The legacy CI- suffix is matched literally and case-insensitively, unchanged by the GitHub naming rules. The CI identity still needs permission to list and read secrets, for example through the Key Vault Secrets User role. Matching Key Vault secrets are used only when no GitHub secret or variable supplies that parameter; keep the corresponding Bicep parameters secure.
Migrate existing inputs
Inventory the CI- secrets used by your test parameters and identify every workflow that depends on the vault. Prefer the preview-only migration helper for this inventory.
Map each source name to a readable GitHub CI_ name, or a CI__ name for literal underscores or a reserved-name conflict. For example, Key Vault secret CI-mySecret becomes GitHub secret CI_MY_SECRET, supplying mySecret.
Copy each value privately to the intended repository or environment scope. Default to a GitHub secret; choose a variable only after confirming the value is non-sensitive. Coordinate corresponding upstream inputs with the maintainers.
Confirm that all dependent workflows use the migrated inputs before removing CI_KEY_VAULT_NAME. Do not delete the vault or its secrets as part of this change without checking for other consumers.
Preview with the migration helper
Support is not released yet
The GitHub CI parameter support and migration helper are part of Azure/bicep-registry-modules#7339. Wait until the implementation is available in your checkout and dependent workflows before applying a migration.
The Copy-CIKeyVaultSecretsToGitHub helper requires PowerShell 7.2 or later, an authenticated Az.KeyVault session, and the GitHub CLI authenticated to github.com. From a bicep-registry-modules checkout containing the helper, replace the placeholders and preview selected inputs:
For new entries, the helper generates readable names from camelCase and acronyms: CI-mySecret becomes CI_MY_SECRET, CI-deploymentLabel becomes CI_DEPLOYMENT_LABEL, and CI-managedHSMResourceId becomes CI_MANAGED_HSM_RESOURCE_ID. Literal underscores or reserved-name conflicts use CI__ spelling.
Without -Apply, the helper lists names and metadata only: it does not read secret values or change GitHub settings. -SecretName is a literal, case-insensitive allowlist of source CI- names; omitting it selects all CI- entries. -VariableName accepts either CI_ or CI__ aliases that resolve to selected source parameters explicitly confirmed as non-sensitive; all other values remain secrets. Prefer the planned readable output names, as in the example. Omit -Environment to target repository scope.
Review the preview and obtain explicit operator approval before adding -Apply to copy values. When selecting an existing destination entry of the same kind for a parameter, the helper also prefers CI_ over CI__. It skips the winning entry by default and reuses and overwrites only that entry when -Overwrite is explicitly specified. Any losing CI__ alias is left unchanged, not deleted. Ambiguity within the winning prefix and opposite-kind matches for the same parameter are blocked.
The helper never deletes entries and sends version-pinned values through standard input, not command arguments or files. Complete the workflow confirmation above before removing CI_KEY_VAULT_NAME.
Enable or Disable Workflows
When forking the BRM repository, all workflows from the CI environment are also part of your fork. In an earlier step it was explained, how to set them up correctly, to verify your module development.
Due to the trigger mechanism of the workflows, eventually all of them run at some point in time, creating and deleting resources on Azure in your environment. That will also happen for modules, you are not working on. This will create costs in your own subscription and it can also create a queue for workflow runs, due to the lack of enough free agents.
To limit those workflow runs, you can manually disable each pipeline you do not want to run. As this is a time consuming task, there is script in the BRM repository, to disable (or enable) pipelines in a batch process, that can also be run via a workflow. You can also use RegEx to specify which pipelines should be included and which should be excluded.
Browse to Actions and select the workflow from the list
Run the workflow platform.toggle-avm-workflows and set the following settings:
Enable or disable workflows to enable or disable workflows
RegEx which workflows are included include a specific set of workflows, using a RegEx.
RegEx which workflows are excluded exclude a specific set of workflows, using a RegEx.
Typical use cases
Disable all but one workflow
Enable or disable workflows to Disable
RegEx which workflows are included to avm\.(?:res|ptn|utl) (this is the default setting)
RegEx which workflows are excluded to avm.res.compute.virtual-machine (use the name of your own workflow. This example uses the workflow for virtual machine)
Disable all but multiple workflows
Enable or disable workflows to Disable
RegEx which workflows are included to avm\.(?:res|ptn|utl) (this is the default setting)
RegEx which workflows are excluded to (?:avm.res.compute.virtual-machine|avm.res.compute.image|avm.res.compute.disk) (use the names of your own workflows. This example uses the workflows for virtual machine, image, and disk)
Enable all workflows
Enable or disable workflows to Enable
RegEx which workflows are included to avm\.(?:res|ptn|utl) (this is the default setting)
RegEx which workflows are excluded to ^$ (this is the default setting)
Limitations
Please keep in mind, that the workflow run disables all workflows that match the RegEx at that point in time. If you sync your fork with the original repository and new workflows are there, they will be synced to your repository and will be enabled by default. So you will need to run the workflow to disable the new ones again after the sync.
Important
The workflow can only be triggered in forks.
Owner Contribution Flow
This section describes the contribution flow for module owners who are responsible for creating and maintaining Bicep Modules.
Important
This contribution flow is for Module Owners only.
As a Bicep Module Owner you need to be aware of the AVM Contribution Process Overview, Bicep specifications (including Bicep Interfaces) as these need to be followed during pull request reviews for the modules you own. The purpose of this Owner Contribution Flow is to simplify and list the most important activities of an owner and to help you understand your responsibilities as an owner.
Note
Additional internal content for ongoing module maintenance available for Microsoft FTEs, here.
Access is managed through the shared @Azure/azure-verified-modules-module-contributors team.
Maintain every approved handle in the owners array in your module’s root metadata.json. Coordinate changes with the AVM Core Team and follow the metadata review process. The reviewer-routing workflow uses these handles to request reviews; it does not generate per-module CODEOWNERS entries.
Ensure your module has been tested before raising a PR. You can do this your own or in another module contributor’s environment - if any. Also, once a PR is raised, a GitHub workflow pipeline is required to be run successfully before the PR can be merged. This is to ensure that the module is working as expected and is compliant with the AVM specifications.
Note
For ordinary Bicep code changes, any eligible BRM repository team member may approve and merge under repository rules. If you are the sole owner and author, request another eligible reviewer; you cannot approve your own pull request. Changes to metadata.json still require metadata code-owner review.
Ensure that the module(s) you own are compliant with the AVM Bicep specifications and are working as expected.
Watch Pull Request (PR) activity for your module(s) in the BRM repository (Bicep Registry Modules repository - where all Bicep AVM modules are published) and ensure that PRs are reviewed and merged in a timely manner as outlined in SNFR11.
Watch AVM module issue and AVM question/feedback activity for your module(s) in the BRM repository.
2. Module Handover Activities
Under certain circumstances, you may find yourself unable to continue as the module owner. In such cases, it is advisable to designate a new module owner. The following steps outline this transition:
Follow the hot-swapping module owners process. Transfer ownership in one root metadata change and wait for approval from either metadata code-owner team and merge before finalizing the handover.
Do not remove shared AVM access solely because one module changes owners; it may still be needed for other modules.
If a new module owner cannot be identified then the module will need to be “Orphaned”. Please follow the step outlined when-a-module-becomes-orphaned.
3. Adopting an Orphaned Module
Follow the adoption process. Add approved owners to the root metadata.json through metadata code-owner review and complete the eligibility, consent, access approval, and notice-removal steps.
4. GitHub Notification Settings
As a module owner, it’s important that you receive notifications when any of your AVM modules experience activity or when you or any groups you belong to are explicitly mentioned (using the @ operator). This document describes how to configure your GitHub and Email settings to ensure you receive email notifications for these types of scenarios within GitHub.
Ensure your Default Notifications Email address is set to the email address you intend to use.
(Optional) If you would like to automatically watch repositories that you are active in, ensure Automatically watch repositories is set to “On.”
(Required) If you would like to automatically subscribe to team-level notifications whenever you join a new team, ensure Automatically watch teams is set to “On.”
(Required) To receive notifications whenever a change is made to a repository or conversation that you are Watching, ensure the Notify Me setting has at least Email enabled.
(Required)To receive notifications whenever you or a group you belong to are @mentioned, ensure the Notify Me setting has at least Email enabled.
Watch a Repository
Optionally, you may consider “watching” (following most or all activities in) an entire repository. The primary repository that owners should watch is the Bicep-Registry-Modules (BRM) repository. Notifications from this repository will notify you of issues concerning your module and any direct or team @mentions. It is important that you read and react to these messages.
To watch the BRM repository, visit Bicep-Registry-Modules, click the Watch button in the top-right of the page, then select Participating and @mentions. Optionally, if you would like to be notified for all activity within the repository, you can select All Activity.
Note
Enabling All Activity will result in a lot of notifications! If you choose to go this route, you should set up filters within your email client. See Configure Email Inbox Notification Filters.
Configure Email Inbox Notification Filters
GitHub uses a unique email address sender for each type of notification it sends. This allows us to set up filters within our email client to sort our inboxes depending on the type of notifications that was sent. The table below lists all of the relevant email addresses that may be useful for filtering notifications from GitHub.
Info
GitHub will use the following email addresses to Cc you if you’re subscribed to a conversation. The second Cc email address matches the notification reason.
This checklist can be used in the development of AVM Bicep Modules.
Before beginning any work a new module a valid Issue: New AVM Module Proposal needs to be created. Instructions for creating the module proposal are outlined in the issue template. Pay particular attention to the questions and associated links to fill out the proposal accurately. Please do not start work on your proposed module until you receive a notification that your proposal has been accepted.
Fork the bicep-registry-modules BRM repository. If you use an existing fork, ensure it’s up to date with origin/BRM.
Ensure all workflows are disabled by default once you forked the BRM repo, to prevent any accidental deployments into your Azure test environment resulted by an automated deployment.
Create a new branch from your forked repository to develop your module.
If you’re working on a new module you have to create its corresponding workflow file (see here).
In order to run your e2e tests in your fork, this workflow file has to be put into the main branch first, so it can be run against your feature branch (GitHub Workflows can only be run on feature branches when they are already present in the main branch).
Since all workflows are disabled by default you have to enable your module’s specific GitHub workflow to run your e2e tests.
In addition to testing your module via GitHub pipeline, you can also test-locally. The following helper script facilitates local testing.
β Local Test Helper Script
# Start pwsh if not started yetpwsh
# Set default directory$folder = "<your directory>/bicep-registry-modules"# Dot source functions. $folder/utilities/tools/Set-AVMModule.ps1
. $folder/utilities/tools/Test-ModuleLocally.ps1
# Variables$modules = @(
# "service-fabric/cluster", # Replace with your module"network/private-endpoint"# Replace with your module)
# Generate Readmeforeach ($module in $modules) {
Write-Output "Generating ReadMe for module $module" Set-AVMModule -ModuleFolderPath "$folder/avm/res/$module" -Recurse
# Set up test settings $testcases = "waf-aligned", "max", "defaults" $TestModuleLocallyInput = @{
TemplateFilePath = "$folder/avm/res/$module/main.bicep" ModuleTestFilePath = "$folder/avm/res/$module/tests/e2e/max/main.test.bicep" PesterTest = $true
ValidationTest = $false
DeploymentTest = $false
ValidateOrDeployParameters = @{
Location = '<your location>' SubscriptionId = '<your subscriptionId>' RemoveDeployment = $true
}
AdditionalTokens = @{
namePrefix = '<your prefix>' TenantId = '<your tenantId>' }
}
# Run testsforeach ($testcase in $testcases) {
Write-Output "Running test case $testcase on module $module" $TestModuleLocallyInput.ModuleTestFilePath = "$folder/avm/res/$module/tests/e2e/$testcase/main.test.bicep" Test-ModuleLocally @TestModuleLocallyInput
}
}
Create a PR and reference the status badge of your pipeline run - see here.
After a pull request has been created, it is important to update the AVM module proposal issue associated with your module, with a link to the pull request you created in BRM and mention the person who helped triage your module or the @Azure/azure-verified-modules-tooling-contributors team.
Once your BRM pull request has been approved and merged into main update the AVM module proposal issue associated with your module, with a Merged comment and mention the person who helped triage your module, or the @Azure/azure-verified-modules-tooling-contributors team.
Generate Bicep Module Files
As per the module design structure (BCPNFR23), every module in the AVM library requires
a up-to-date ReadMe markdown (readme.md) file documenting the set of deployable resource types, input and output parameters and a set of relevant template references from the official Azure Resource Reference documentation
an up-to-date compiled template (main.json) file
The Set-AVMModule utility aims to simplify contributing to the AVM library, as it supports
idempotently generating the AVM folder structure for a module (including any child resource)
generating the module’s ReadMe file from scratch or updating it
compiling/building the module template
To ease maintenance, you can run the utility with a Recurse flag from the root of your folder to update all files automatically.
To do so, it searches for any required folder path / file missing and adds them. For several files, it will also provide some default content to get you started. The sources files for this action can be found here
compiles its bicep template
updates the readme (recursively, specified)
If the intended readMe file does not yet exist in the expected path, it is generated with a skeleton (with e.g., a generated header name)
The script then goes through all sections defined as SectionsToRefresh (by default all) and refreshes the sections’ content (for example, for the Parameters) based on the values in the ARM/JSON Template. It detects sections by their header and always regenerates the full section.
Once all are refreshed, the current ReadMe file is overwritten. Note: The script can be invoked combining the WhatIf and Verbose switches to just receive an console-output of the updated content.
How to use it
For details on how to use the function, please refer to the script’s local documentation.
Note
The script must be loaded (’dot-sourced’) before the function can be invoked.
. 'C:/dev/Set-AVMModule.ps1'Set-AVMModule (...)
Tip
For modules that require the generation of files on multiple-levels (for example, a module with child modules such as the ‘Key Vault’ module with its ‘Secret’ child module) it is highly recommended to make use of the -Recurse parameter.
This parameter will ensure that the script not only generates the files for the provided module folder path, but also all its nested module folder paths.
Tip
While readme files are always generated from scratch, you can add custom content is specific places that the script will preserve:
The module’s description in the main.bicep file’s metadata
The description of parameters & outputs
A section with the header ## Notes
If the utility finds a section with the heading ## Notes, it temporarily saves this content when it regenerates the readme file and then re-inserts (i.e. appends) the section toward the end of the readme file. This section may contain images, which must be stored in a subfolder /src in the root directory of the module.
Both for the text & images, please make sure to only add what provides tangible value as the content must be manually maintained and should not run stale. Further, for images, please make sure to only store them with an appropriate resolution & size to keep their impact on the repository’s size manageable.
Validate Module Locally
Use this script to test a module from your PC locally, without a CI environment. You can use it to run only the static validation (Pester tests), a deployment validation (dryRun) or an actual deployment to Azure. In the latter cases the script also takes care to replace placeholder tokens in the used module test & template files for you.
If the switch for Pester tests (-PesterTest) is provided the script will
Invoke the module test for the provided template file path and run all tests for it.
If the switch for either the validation test (-ValidationTest) or deployment test (-DeploymentTest) is provided alongside a HashTable for the token replacement (-ValidateOrDeployParameters), the script will
Either fetch all module test files of the module’s tests folder (default) or you can specify a single module test file by leveraging the -ModuleTestFilePath parameter instead.
Create a dictionary to replace all tokens in these module test files with actual values. This dictionary will consist
of the subscriptionID & managementGroupID of the provided ValidateOrDeployParameters object,
add all key-value pairs of the -AdditionalTokens object to it,
and optionally also add all key-value pairs specified in the settings.yml, under the ’local tokens settings'.
If the -ValidationTest parameter was set, it runs a deployment validation using the Test-TemplateDeployment script.
If the -DeploymentTest parameter was set, it runs a deployment using the New-TemplateDeployment script (with no retries).
As a final step, it rolls the module test files back to their original state if either the -ValidationTest or -DeploymentTest parameters were provided.
How to use it
For details on how to use the function, please refer to the script’s local documentation.
Note
The script must be loaded (’dot-sourced’) before the function can be invoked.
Important: As the script emulates the testing logic of the CI environment, also tokens such as #_namePrefix_# are replaced by the script. However, in addition to the CI environment, it also reverses the token replacement to recover the files’ original state. As such, ensure that you use a namePrefix value that is unlikely to overlap with any string value in module folder you want to test.
For example, do not use avm, as the reverse token replacement would incorrectly replace the deployment name avmTelemetry found in each module to #_namePrefix_#Telemetry.
Bicep Contribution Prerequisites
GitHub Account Link and Access
You need to have a personal GitHub account which is linked to your Microsoft corporate identity. Once the link step is complete you must join the Azure organization.
Recommended Learning
Before you start contributing to the AVM, it is highly recommended that you complete the following Microsoft Learn paths, modules & courses:
To enhance streamlined integration during interactions with upstream repositories, GitHub Desktop will automatically configure your local git repository to use the upstream repository as a remote.
Contribution Q&A
Tip
Check out the FAQ for more answers to common questions about the AVM initiative in general.
Proposing a module
Who can propose a new module and where can I submit a new module proposal / request?
Everyone can propose a module
To propose a new module, simply create an issue/complete the form here.
Can I just propose / create any module?
For example, can I propose one for managed disks or NICs or diagnostic settings? What about patterns?
No, you cannot propose or create just any module. You can only propose modules that are aligned with requirements documented in the module specifications section.
Below, we provide some guidance on what modules you can / cannot propose.
Resource modules: resource modules have bring extra value to the end user (can’t just be simple wrappers) and MUST mapped 1:1 to RPs (resource providers) and top level resources. You MUST follow the module specifications and your modules SHOULD be WAF aligned.
Good examples:
Virtual machine: the VM module is highly complex and therefore, it brings extra value to the end user by providing a wide variety of features (e.g., diagnostics, RBAC, domain join, disk encryption, backup and more).
Storage account: even though, this module is mainly built around one RP, it brings extra value by providing easy access to its child resources, such as file/table/queue services, as well as additional standard interfaces (e.g., diagnostics, RBAC, encryption, firewall, etc.).
Bad examples:
NIC or Public IP (PIP) module: these would be simple wrappers around the NIC/PIP resource and wouldn’t bring any extra value. NICs and PIPs SHOULD be surfaced as part of the VM module (or any other primary resources that require them).
Diagnostic settings: these are too low-level “sub resources”, and highly dependent on their “primary resource’s” RP defined as “interfaces” and therefore MUST be used as part of a resource module holding a primary resource - see Diagnostic Settings documentation about the correct implementation.
Pattern modules: In case of pattern modules, ideally you should start from architectural patterns, published in the Azure Architecture Center, and build your pattern module by leveraging resource modules that are required to implement the pattern. AVM does not provide architectural guidance on how you should design your pattern, but you MUST follow the module specifications and your modules SHOULD be WAF aligned.
Good examples:
Landing zone accelerators for N-tier web application; AKS cluster; SAP: there are numerous examples for these architectures in Azure Architecture Center that already have baked in guidance / smart defaults that are WAF Aligned, therefore these are good candidates for pattern modules. Module owners MAY leverage resource modules to implement the pattern.
Hub and spoke topology: it’s a common pattern that is used by many customers and there are great examples available through Azure Architecture Center, as well as Azure Landing Zones. Also a good candidate for a pattern module.
Bad examples:
A pair of Virtual machines: being a simple wrapper, this solution wouldn’t bring any extra value as it doesn’t provide a complete solution.
Key Vault that deploys automatically generated secrets: this is aligned with the definition of a resource modules, therefore it should be categorized as such.
Where do I need to go to make sure the module I’d like to propose is not already in the works?
The AVM core team maintains the list of Bicep and Terraform modules and tracks the status of each module. Based on this list, you can check if the module you’d like to build is already in the works (e.g., it’s being worked on in a feature branch but hasn’t been published yet).
To see the formatted lists with additional information, please visit the AVM Module Indexes page.
I need a new module but I cannot own/author it for various reasons, what should I do?
You sign up to be a module owner (and optionally, you can find additional contributors to help you).
You find / request someone else to be the module owner (and optionally, you can be a contributor).
You propose a module and wait until the AVM core team finds a module owner for you (who then can optionally leverage the help of additional contributors).
As these options are increasingly more time consuming, we recommend you to start with considering option 1 and only if you cannot own the module, should you move to option 2 and then 3.
How long will it take for someone to respond and a module to be created/updated and published?
While there are SLAs defined for providing support for existing modules, there are currently no SLAs in place for the creation of new modules. The AVM core team is a small team and is currently working on automating the module creation process to make it as easy as possible for module owners to create and publish modules on their own.
Beside of providing program level governance, the AVM core team is mainly responsible for defining the module specifications, providing tooling (such as test frameworks and pipelines), guidance and support to module owners, as well as facilitating the creation of new modules by maintaining the module catalog and identifying volunteers for owning the modules. However, modules will be created and maintained by a broader community of module owners.
How do I let the AVM team know I really need an AVM module to unblock me / my project / my company?
If you’re an external user, you can propose a module here and provide as much context as possible under the “Module Details” section (e.g., why do you need the module, what’s the business impact of not having it, etc.).
If you’re a Microsoft employee and have already proposed a module here, you can reach out to the AVM core team directly via Teams to provide more details internally.
The AVM core team will then triage the request and get back to you with next steps. You can accelerate the process of creating the module by volunteering to be a module owner.
How will the AVM module index (catalog) be updated?
Submit module details and ownership changes to the module repository’s metadata.json through the metadata review process. Ownership is maintained in the root file and requires approval from either metadata code-owner team.
A catalog sync then regenerates the indexes and publishes them automatically every four hours, so a merged metadata change normally appears in the published index within about four hours.
For deprecation, follow the retirement process. The catalog derives Deprecated from Bicep’s DEPRECATED.md or Terraform’s repository archived flag.
Developing a module
Who is developing a modules?
Every module has an owner that is responsible for module development and maintenance. One owner can own one or multiple modules. An owner can develop modules alone or lead a team that will develop a module. If you want to join a team and to contribute on specific module, please contact module owner.
At this moment, only Microsoft FTEs can be module owners.
What do I need so I can start developing a module?
Feel free to reach out to the AVM Core team in case that additional help is needed.
What do I do about existing modules that are available doing a similar thing to my module that I am proposing to develop and release?
As part of the Module Proposal process, the AVM core team will work with you to triage your proposal. We also want to make sure that no similar existing modules from known Microsoft projects are already on their way to be migrated to AVM.
If there aren’t any, then you can proceed with developing your module from scratch once given approval to proceed by the AVM core team.
However, if there are existing modules from Microsoft projects we would invite you to help us complete the migration to AVM of this module; this may also entail working with the existing module owner/team.
For existing modules that may not be directly owned and developed by Microsoft or their employees you should first review the license applied to the GitHub repository hosting the module and understand its terms and conditions. More information on GitHub repositories and licenses can be found here in Licensing a repository Most modules will use a license that will allow you to take inspiration and copy all or parts from the module source code. However, to confirm, you should always check the license and any conditions you may have to meet by doing this.
What are the mandatory labels that needs to be used while managing issues, pull requests and discussions on GitHub repositories where module are held?
Where module will live? Do I need to create separate repo or to place it in specific folder?
Bicep
For Bicep, both Resource and Pattern, AVM Modules will be homed in the Azure/bicep-registry-modules repository and live within an avm directory that will be located at the root of the repository.
If you are module owner, it is expected that you will fork the Azure/bicep-registry-modules repository and work on a branch from within their fork, before then creating a Pull Request (PR) back into the Azure/bicep-registry-modules repositories main branch. In Bice contribution guide, you can discover Directory and File structure that will be used and examples.
Terraform
Each Terraform AVM module will have its own GitHub Repository in the Azure GitHub Organization. This repo will be created by the Module Owners and the AVM Core team collaboratively, including the configuration of permissions. To read more about how to start, navigate to Terraform AVM contribution guide.
I get the error ‘The repository ********** already exists on this account’ when I try to create a new repository, what should I do?
If you get this error, it means that the repository already exists in the Azure GitHub Organization. This can happen if someone has already created a repository with the same name in the past and then archived it.
To determine if this is the case you’ll need to navigate to the Microsoft Open Source Management Portal, then search for the repository name you are trying to create. Click on the repository and you will find the owner. Reach out the owner to ask them to transfer the repo to you or delete it. You’ll want them to delete it if it was not created from the template.
Where can I test my module during development?
During initial module development module owners/developers need to use your own environment (Azure subscriptions) to test module. In later phase, during publishing process, we will conduct automated test that will use AVM dedicated environment.
Updating and managing a module
I’m already using a module today, but its missing a feature, what should I do?
You should use GitHub issues to propose changes or improvements for specific module. Issue request will be routed to module owner that MUST respond to logged issues as per the defined support statement. In case that module currently don’t have owner, AVM Core Team will handle request.
I am using module without owner. What will happened if I need update?
AVM core team will work to assign owner for every module, but it can happen during a time that there are modules without owner. To volunteer, comment on the module’s orphaned module issue and follow the adoption process. At this moment, only Microsoft FTEs can be module owners. Add approved owners through a pull request to the root metadata file and complete access approval separately.
How will the support SLAs be automatically enforced?
All issues created in a module repo will be automatically be picked up and tracked by the GitHub Policy Service. This service will take the necessary steps when escalation is needed as per the SLAs defined in the Module Support chapter.
Module Metadata
Maintain a module’s details and ownership in metadata.json in its source repository. Submit changes through the review process below.
Find the correct file
Language
Root module metadata
Bicep
avm/{res,ptn,utl}/{group}/{module}/metadata.json in Azure/bicep-registry-modules. Use the existing module’s actual path.
Terraform
metadata.json at the root of the module’s own repository. Find that repository through the module indexes.
Child modules have reduced metadata.json files in their own folders. They inherit ownership from the root module, including when nested more than one level deep. Change owners only in the root file; child files must not contain owners.
Use the existing file as your starting point and preserve unrelated values. If metadata or an assigned value is missing, ask the AVM core team to confirm the required values.
Create metadata.json when scaffolding a new module
Every new Bicep or Terraform root module, and every new child module or submodule, MUST have a valid metadata.json created as part of scaffolding, not added later.
Root modules get the full metadata shape, including the owners array.
Child modules and submodules get the reduced, inherited-owner shape described above; they must not contain owners.
Use Initialize-AvmModuleMetadata from the Avm.Authoring PowerShell module to scaffold the file for either ecosystem. It validates the supplied values against the versioned schema and writes metadata.json without overwriting an existing file. You must supply the approved values yourself; the command never infers or backfills them.
-Ecosystem (bicep or terraform) and -ModuleType (resource, pattern, or utility) are required. Add -ChildModule to scaffold the reduced, owner-less shape for a child module or submodule, omitting owners from the input. -UpdateSource applies matching Bicep source literals and is not valid for Terraform. Run with -WhatIf first to review the plan, then re-run without it to write the file.
Validate an existing file with avm metadata validate, or inspect one with avm metadata show.
Approved modules may carry metadata.json before their source exists. The catalog treats a metadata-only module as Proposed until it is published.
Fields you can maintain
The versioned schema referenced by the required $schema URI defines the supported fields.
Field
Guidance
$schema
Keep the required versioned schema URI. It identifies the module metadata schema.
moduleDisplayName, moduleDescription
Maintain the module’s curated display name and description. For Bicep, moduleDescription must match the metadata description literal in main.bicep. moduleDisplayName is independent of the metadata name literal and does not have to match it.
canonicalType
The real ARM resource type, or the approved pattern/utility taxonomy. Helper submodules use helper.
owners
Root only: a flat array of strings containing every approved owner. Use bare GitHub handles for individuals and qualified handles such as @Azure/team-name for approved existing teams.
telemetryIdPrefix
Preserve the assigned identifier where required. Do not generate a replacement identifier as part of an ownership or descriptive edit.
alternativeNames, comments
Optional root-module aliases and notes. These are public metadata.
Pattern and utility canonicalType values can have one or more segments, such as naming for avm-utl-naming. Preserve the module’s approved mapping. Resource modules and non-helper resource children use their actual ARM resource type.
Module identity and parent relationships come from the repository layout. Changing moduleDisplayName does not rename a module or move its repository.
Helper submodules
Helper submodules use the exact "canonicalType": "helper" marker with the required $schema, moduleDisplayName, and moduleDescription. Ownership is inherited from the root. Use this marker only for helper children, not root modules or resource children.
Helper telemetry is optional; any supplied telemetryIdPrefix must pass validation. Helpers appear in the JSON catalog, not in the CSV indexes.
Terraform submodules are excluded from the CSV indexes entirely, not only helpers. Bicep child modules still have their own CSV rows, and the ParentModule column names the family root rather than the immediate parent.
Submit and review a change
Agree the change with the current owners and the AVM core team. For ownership changes, retain the eligibility checks, incoming owners’ written consent, and handover requirements in the owner-change process.
Edit the relevant metadata.json on a branch or in your fork of the module repository. Preserve all owners and other values that are not part of the agreed change.
Validate metadata using the repository’s approved tooling and satisfy its required reviews before merging. Approval from an eligible member of either team satisfies metadata code-owner review; approval from both teams is not required. Being listed in the module’s owners array does not by itself authorize someone to approve. Any code changes in the same pull request still need their normal code review and tests.
Follow the change through catalog generation and reviewed publication. Do not edit the generated CSV or JSON output to duplicate the metadata change.
Metadata-only changes must not trigger a module release. Do not change version files or create a release just to update owners or other metadata. A Bicep description correction may also require updating the metadata description literal in main.bicep; that is a source change and must follow normal validation and release rules, not be treated as metadata-only. Display names are independent of source literals and need no source change.
In Azure/bicep-registry-modules, the root owners array controls reviewer notifications, including for child modules. It does not generate per-module CODEOWNERS entries or require a module owner’s approval for ordinary code changes. An ownerless module is routed to @Azure/azure-verified-modules-module-owners for review. The final metadata.json rule in CODEOWNERS still protects metadata changes with the two metadata code-owner teams; an eligible member of either team can approve.
Editing metadata does not grant or revoke repository permissions, create teams, change identities, or provision Azure access. Every incoming owner still needs the separate access approval described in SNFR20. Do not remove shared access solely because someone stops owning one module.
Ownership changes
Add, remove, or transfer owners
Update the owners array in the root metadata file. Add the approved incoming handles and remove only the departing handles. Keep every continuing individual or team owner.
For a direct transfer, follow hot swapping module owners and make the outgoing and incoming owner changes together, so the module does not pass through an unowned state. Do not reopen a closed module proposal.
In the root metadata file, set "owners": [], removing all individual and team handles from the array. Keep the remaining metadata intact. A published module with no owners is shown as Orphaned. See how module status is calculated.
Adopt an orphaned module
Follow when a new owner is identified. After eligibility and consent are confirmed, add the approved incoming handles to the root metadata’s owners array and obtain approval from either metadata code-owner team.
Complete the separate access approval and notice-removal steps before closing the ownership issue. Adding owners does not revive a deprecated module.
Catalog updates
The catalog sync runs on a four-hourly schedule (01:33, 05:33, 09:33, 13:33, 17:33, and 21:33 UTC). Each scheduled run collects metadata from the module repositories, regenerates the six CSV indexes and v1/modules.json, and publishes them to the module indexes and CSV downloads automatically. A merged metadata change therefore appears in the published index within about four hours, without a separate request to the AVM core team.
The generated outputs are not the source of truth. Propose corrections in the module’s metadata.json rather than editing generated CSV or JSON files; the next scheduled run overwrites them. The AVM core team owns the catalog tooling and handles any run that is held back by a safeguard.
CSV owner columns show the first two individuals. Root metadata and the JSON catalog contain the full owner list.
Module status
The catalog calculates ModuleStatus from evidence, not from an authored field. The first matching condition wins:
Condition
Status
Deprecation evidence, or an existing Deprecated status in the CSV
Deprecated
Not published in the registry
Proposed
Published with no owners
Orphaned
Published with at least one owner
Available
A module that is both deprecated and unpublished is omitted from the CSV indexes and v1/modules.json altogether, and the run warns that its unused source or repository can be deleted.
Related processes
New proposals: Follow the module proposal and approval process. The approved name, description, and owners are agreed in the proposal issue. Once approved, metadata.json may be created before the module source exists; the module stays Proposed until it is published. Do not create metadata for a module that has not been approved.
Publication: Registry publication is required before a module is available. A metadata change does not publish a module.
Deprecation: Follow the deprecation process, including approval, notices, and language-specific retirement steps. The catalog derives deprecation from Bicep’s DEPRECATED.md or the Terraform repository’s archived flag, not an authored metadata status.
A Bicep marker applies to its module and descendants, not its parent or siblings. Terraform archival applies to every module entry in that repository. Changing owners does not deprecate or reactivate a module. A module that is deprecated before it was ever published is removed from the indexes rather than listed as Deprecated.
This page provides an overview of the contribution process for AVM modules.
New Module Proposal & Creation
Important
Each AVM module MUST have a Module Proposal issue created and approved by the AVM core team before it can be created/migrated!
Note
Record approved details in the proposal issue. Once the module is approved, maintain those details in its metadata.json through the metadata review process. Metadata may be created before the module source exists.
---
config:
nodeSpacing: 20
rankSpacing: 20
diagramPadding: 5
padding: 5
useWidth: 100
flowchart:
wrappingWidth: 400
padding: 5
---
flowchart TD
ModuleIdea[Consumer has an idea for a new AVM Module] -->CheckIndex(Check AVM Module Indexes)
click CheckIndex "/Azure-Verified-Modules/indexes/"
CheckIndex -->IndexExistenceCheck{Is the module<br>in the index?}
IndexExistenceCheck -->|No|A
IndexExistenceCheck -->|Yes|EndExistenceCheck(Review existing/proposed AVM module)
EndExistenceCheck -->OrphanedCheck{ Is the module<br>orphaned? }
click OrphanedCheck "/Azure-Verified-Modules/specs/shared/module-lifecycle/#3-orphaned-modules"
OrphanedCheck -->|No|ContactOwner[Contact module owner,<br> via GitHub issues on the related <br>repo, to discuss enhancements/<br>bugs/opportunities to contribute etc.]
OrphanedCheck -->|Yes|OrphanOwnerYes(Locate the related issue <br> and comment on:<br> - A feature/enhancement suggestion <br> - Indicating you wish to become the owner)
click OrphanOwnerYes "/Azure-Verified-Modules/specs/shared/module-lifecycle/#3-orphaned-modules"
OrphanOwnerYes -->B
A[[ Create Module Proposal ]] -->|GitHub Issue/Form Submitted| B{ AVM Core Team<br>Triage }
click A "https://aka.ms/avm/moduleproposal"
click B "/Azure-Verified-Modules/help-support/issue-triage/avm-issue-triage/#avm-core-team-triage-explained"
B -->|Module Approved for Creation| C[["Module Owner(s) Identified & assigned to GitHub issue/proposal" ]]
B -->|Module Rejected| D(Issue closed with reasoning)
C -->E[[ Approved proposal recorded by AVM Core Team]]
click E "/Azure-Verified-Modules/help-support/issue-triage/avm-issue-triage/#module-proposal-triage"
E -->E1[[Repo/Directory Created following the <br> Contribution Guide ]]
click E1 "/Azure-Verified-Modules/contributing/"
E1 -->F("Module Developed by Owner(s) & their Contributors")
F -->E2[[ Module metadata submitted and reviewed ]]
click E2 "/Azure-Verified-Modules/contributing/module-metadata/"
E2 -->G[[ Module & AVM Compliance Tests ]]
click G "/Azure-Verified-Modules/spec/SNFR3"
G -->|Tests Fail|I(Modules/Tests Fixed <br> To Make Them Pass)
I -->F
G -->|Tests Pass|J[[Version 0.1.0 created]]
J -->K[[Publish to Bicep/Terraform Registry]]
K -->L(Take Feedback from v0.1.0 Consumers)
L -->M{Anything<br>to be resolved <br> before 1.0.0<br>release? }
click M "/Azure-Verified-Modules/contributing/process/#avm-preview-notice"
M -->|Yes|FixPreV1("Module feedback incorporated by Owner(s) & their Contributors")
FixPreV1 -->PreV1Tests[[Self & AVM Module Tests]]
PreV1Tests -->|Tests Fail|PreV1TestsFix(Modules/Tests Fixed To Make Them Pass)
PreV1TestsFix -->N
M -->|No|N[[Publish 1.0.0 Release]]
N -->O[[Publish to IaC Registry]]
O -->P[[ Module BAU Starts ]]
click P "/Azure-Verified-Modules/help-support/module-support/"
Provide details for module proposals
When proposing a module, please include the information in the description that is mentioned for the triage process here:
The AVM framework continues to evolve, and several elements, such as Continuous Integration (CI) processes, module specifications and corresponding specificationβvalidation coverage, are not yet fully implemented. Hence, modules MUST NOT be published at version 1.0.0 or higher at this time.
All module MUST be published as a 0.x.y minor version (e.g., 0.1.0, 0.1.1, 0.2.0, etc.) until the AVM team provides guidance that publishing v1.0.0 is allowed.
However, it is important to note that this DOES NOT mean that the modules cannot be consumed and utilized. They CAN be leveraged in all types of environments (dev, test, prod etc.). Consumers can treat them just like any other IaC module and raise issues or feature requests against them as they learn from the usage of the module. Consumers should also read the release notes for each version, if considering updating to a more recent version of a module to see if there are any considerations or breaking changes etc.
Module Owner Has Issue/Is Blocked/Has A Request
In the event that a module owner has an issue or is blocked due to specific AVM missing guidance, test environments, permission requirements, etc. they should follow the below steps:
Tip
Common issues/blockers/asks/request are:
Subscription level features
Resource Provider Registration
Preview Services Enablement
Entra ID (formerly Azure Active Directory) configuration (SPN creation, etc.)
Please note for module specific issues, these should be logged in the module’s source repository, not the AVM repository.
Terraform Contribution Guide
Important
Every new AVM Terraform module MUST use AzAPI for all control-plane resources and supported data-plane operations. AzureRM is permitted only for a specific unsupported data-plane/non-ARM API operation under the narrow TFFR3 exception. This rule applies to the root module, submodules, examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets; supporting control-plane resources in every surface must use AzAPI.
While this page describes and summarizes important aspects of contributing to AVM, it only references some of the shared and language specific requirements.
Therefore, this contribution guide MUST be used in conjunction with the Terraform specifications. All AVM modules MUST meet the applicable requirements in those specifications.
Summary
This section lists AVM’s Terraform-specific contribution guidance.
AVM TFLint Rules β custom rules, their requirements, and supported overrides
Repository Setup β creating a new module repository (owners only)
Subsections of Terraform Modules
Prerequisites
GitHub Account
To contribute, you need a GitHub account. If you are a Microsoft employee, your account must be linked to your corporate identity and you must be a member of the Azure organization.
Module Owner Access (Microsoft FTEs only)
Note
This step is only required if you are (or are becoming) a Terraform module owner. External contributors and one-off contributors do not need this access.
Access for Terraform module owners is granted via the Azure Verified Modules (AVM) Module Contributors Entra access package. Request access here:
Once approved, you will be added to the azure-verified-modules-module-contributors Entra group, which is the source of truth for who is authorized to own and approve changes on AVM Terraform module repositories.
Tip
Until your access request is approved, you can continue to contribute by using JIT elevation and by raising PRs that are approved by an existing module owner.
Required Tooling
Tip
Avm.Authoring supports Windows, Linux, and macOS. Use PowerShell 7.4 or later on every platform.
Install-PSResource Avm.Authoring
Import-Module Avm.Authoring
avm doctor
Install-Module Avm.Authoring -Scope CurrentUser remains available for environments that use PowerShellGet v2. Run avm update to upgrade an existing installation. The module downloads, verifies, and caches its managed tools, including Terraform, on demand. Run avm doctor --install to preload every supported tool. Docker and Podman are not required.
This guide covers the end-to-end contribution flow for AVM Terraform modules. Whether you are a module owner or an external contributor, the core workflow is the same β the key differences are called out using tabs below.
Important
Every new AVM Terraform module MUST use AzAPI for every control-plane resource and supported data-plane operation. AzureRM is permitted only for a specific unsupported data-plane/non-ARM API operation under the narrow TFFR3 exception. The same rule applies to submodules, examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets.
This guide MUST be used in conjunction with the Terraform specifications. All AVM modules must meet the requirements described in those specifications.
Install-Module Avm.Authoring -Scope CurrentUser is also supported for environments that use PowerShellGet v2. Run avm with no arguments to list the supported verbs, then verify the installed version and diagnose your local environment:
avm
avm version
avm doctor
Run avm update whenever a newer Avm.Authoring release is available. Avm.Authoring downloads, verifies, and caches Terraform, TFLint, terraform-docs, Conftest, and mapotf on demand. Docker or Podman is not required. You can inspect or manage the tool cache:
avm tool list
avm tool which terraform
avm tool install terraform
avm doctor --install
Warning
The local Avm.Authoring migration and the centrally managed CI workflow rollout are separate changes. Do not pre-emptively rename required checks. After the updated workflow has run on a pull request, update branch protection to use the exact check names reported by that workflow. Per-example checks are derived from the repository’s example folders.
Overview
---
config:
nodeSpacing: 20
rankSpacing: 20
diagramPadding: 50
padding: 5
flowchart:
wrappingWidth: 300
padding: 5
layout: elk
elk:
mergeEdges: true
nodePlacementStrategy: LINEAR_SEGMENTS
---
flowchart TD
Z("1 - Fork [optional]")
click Z "#1-fork-optional"
A(2 - Branch)
click A "#2-branch"
B(3 - Implement your code change)
click B "#3-implement-your-code-change"
C(4 - Run avm pre-commit)
click C "#4-run-avm-pre-commit"
C2(5 - Run pr-check and test tiers locally)
click C2 "#5-run-pr-check-and-test-tiers-locally"
D(6 - Raise or Update PR)
click D "#6-raise-or-update-pr"
E("7 - Approve and monitor CI tests [owner]")
click E "#7-approve-and-monitor-ci-tests"
F{Tests passing?}
G(8 - Review and merge PR)
click G "#8-review-and-merge-pr"
H(9 - Cut a release)
click H "#9-cut-a-release"
Z --> A
A --> B
B --> C
C --> C2
C2 --> D
D --> E
E --> F
F -->|no| B
F -->|yes| G
G --> H
1. Fork [optional]
Note
This step is only needed if you do not have write access to the module repository. Module owners and invited collaborators can skip to step 2.
A fork is your own copy of the repository under your GitHub account. It lets you make changes without needing write access to the upstream repo. Once your changes are ready, you raise a pull request from your fork back to the original repository.
Navigate to the module repository in the Azure GitHub organization.
Click the Fork button in the top right.
Select your GitHub account (or organization) as the destination.
Click Create fork.
Clone your fork locally:
git clone https://github.com/<your-username>/terraform-azure-avm-res-<rp>-<modulename>.git
cd terraform-azure-avm-res-<rp>-<modulename>
Keep your fork in sync with the upstream repository before creating a new branch. You can do this from the GitHub UI by clicking Sync fork on your fork’s main page, or locally:
Create a branch from main to work on your changes:
git checkout -b <your-branch-name>
If this is a new module and the repository does not exist yet, module owners should first follow the Repository Creation Process.
Note
If the module repository does not exist yet, check the Terraform Resource Modules index for the module owner’s contact details (PrimaryModuleOwnerGHHandle column).
3. Implement your code change
Before writing code, review the Terraform specifications and composition guidelines to ensure your contribution complies with AVM’s design principles. For a new module, confirm first that every control-plane resource and supported data-plane operation uses AzAPI. Any AzureRM block must satisfy and document the unsupported data-plane exception in TFFR3.
Once you’ve made your changes, stage, commit, and push them:
git add -A
git commit -m "feat: description of your change"git push
Lifecycle hooks
Some examples need setup work before Terraform runs β deploying prerequisites, generating a terraform.tfvars, or seeding a random prefix. AVM supports optional hook scripts for this:
Terraform configurations created for examples, end-to-end tests, tests, or fixtures are part of the module repository and MUST follow TFFR3. Use AzAPI for every supporting control-plane resource. AzureRM may be configured or exercised only when the test covers the module’s documented unsupported data-plane operation; it must not be used to make setup more convenient.
Hook
Location
Runs
pre.ps1
examples/<name>/
before Terraform commands for the example during policy checks and e2e tests
post.ps1
examples/<name>/
after the example, including when its pre-hook or Terraform initialization fails
tflint-pre.ps1
examples/<name>/
after terraform init, before TFLint
setup.ps1
tests/<tier>/ or modules/<name>/tests/<tier>/
before terraform init and terraform test for the target
Warning
Hooks must be PowerShell. Avm.Authoring rejects per-example pre.sh, post.sh, and tflint-pre.sh files, plus setup.sh and teardown.sh files under tests/<tier>/, on presence alone. Adding a .ps1 while leaving the corresponding .sh in place still fails before Terraform runs:
The terraform unit test engine runs PowerShell hooks only.
Refactor these shell hooks to '.ps1': tests/unit/setup.sh
Legacy root-level examples/setup.sh and examples/teardown.sh files are different: Avm.Authoring does not execute or reject them, and there is no global PowerShell equivalent. Move required logic into idempotent per-example pre.ps1 and post.ps1 hooks. Coordinate removal of legacy global hooks with the repository’s centrally managed CI workflow migration.
Each hook runs in its own isolated pwsh subprocess, so environment variables it exports do not reach subsequent Terraform commands. An e2e pre.ps1 can pass values by writing KEY=VALUE lines to examples/<name>/.env; the runner reads the file after the hook and passes the values to the example’s Terraform subprocesses. A unit or integration setup.ps1 uses a .env file at its target root: the repository root or modules/<name>/. For these test hooks, the .env file is two directories above setup.ps1, not beside it.
Because hooks are invoked from an isolated process, anchor paths on $PSScriptRoot rather than relying on the current working directory. Note also that PowerShell does not stop on a failed native command the way set -e does in bash β check $LASTEXITCODE after each Terraform call and throw so a failed hook surfaces immediately instead of later as a confusing downstream error.
4. Run avm pre-commit
Before raising a pull request, run pre-commit to update your files:
avm pre-commit
For Terraform modules, this command:
Synchronizes the centrally governed managed files, which can add, update, or remove files.
Applies deterministic fixes for AVM convention rules.
Runs mapotf transformations.
Formats Terraform files.
Regenerates documentation.
The command intentionally updates the working tree. Review every change it makes, then commit and push again:
git add -A
git commit -m "chore: pre-commit fixes"git push
5. Run pr-check and test tiers locally
After committing the pre-commit changes, run the broader pull request checks:
az login
avm pr-check
avm pr-check requires a clean Git working tree and Azure credentials because its Conftest policy checks create Terraform plans for the examples. It checks managed-file, formatting, and transformation drift, then runs TFLint, Conftest policy checks, AVM convention checks, terraform validate, and documentation drift checks. It does not run the Terraform test tiers; those remain separate commands so failures are reported independently.
Unit testing
AVM convention checks require a unit test fixture under tests/unit. Use mocked providers to keep unit tests fast and free of external dependencies:
avm test unit
The command also runs unit test tiers found under direct modules/<name>/ submodules.
Integration testing
Integration tests under tests/integration deploy real resources and require Azure credentials:
az login
avm test integration
The command also runs integration test tiers found under direct modules/<name>/ submodules. A repository without integration tests reports the tier as skipped rather than passed.
Local e2e testing
Run the e2e test tier to deploy, check idempotency, and destroy resources for each example:
az login
avm test e2e
This tier requires real Azure credentials. Azure CLI authentication is sufficient for local development; no environment variables or service principals are needed. To run one example while iterating:
avm test e2e --example <name>
An example containing .e2eignore is excluded. Apply failures caused by transient region, SKU capacity, or quota errors are destroyed and retried up to two times by default; use -MaxRetry 0 to disable retries.
Local e2e testing is especially useful for external contributors, since only module owners can approve credentialed CI e2e runs.
6. Raise or Update PR
Tip
Raise your PR early β don’t wait until everything is perfect. An early PR lets you run validation and test tiers in CI and get feedback sooner. You can continue pushing commits to the same branch.
Navigate to the upstream repository on GitHub and click New pull request.
Set the base repository to the upstream AVM repo and base branch to main.
Set your head repository and compare branch to your fork and branch.
Click Create pull request.
Navigate to the repository on GitHub and click New pull request.
Set the base branch to main and the compare branch to your branch.
Click Create pull request.
7. Approve and monitor CI tests
Note
Credentialed CI jobs require approval from a module owner. Unit tests do not require Azure credentials, but external contributors should still run avm pr-check and all applicable test tiers locally before this step.
Once a PR is created, CI workflows are triggered automatically. A centrally managed Azure test subscription is provided for credentialed jobs, so contributors do not configure CI credentials themselves.
What CI runs
The centrally managed workflow keeps validation and test tiers in separate jobs so a failure produces an actionable signal:
PR validation β runs the equivalent of avm pr-check: managed-file and generated-file drift checks, Terraform formatting, mapotf transformations, TFLint, Conftest policy checks, AVM convention checks, terraform validate, and documentation checks.
Unit tests β runs avm test unit.
Integration tests β runs avm test integration when the repository has integration tests.
End-to-end tests β discovers runnable examples and tests each example independently with the equivalent of avm test e2e --example <name>.
Each e2e job deploys the example, checks idempotency with terraform plan, and destroys the resources. Examples containing .e2eignore are excluded.
If tests fail
Go back to step 3 β fix the issue, run avm pre-commit again, push your changes, and the CI tests will re-run automatically on the same PR.
Running e2e for external contributions
When approving a PR from an external contributor:
Review the code for security β check for any malicious code or changes to workflow files before running tests. If found, close the PR and report the contributor.
Create a release branch from main (e.g. release/<description>).
Change the PR’s base branch to the release branch and merge it.
Create a new PR from the release branch to main β this triggers the validation and test jobs.
Approve the run and wait for results.
If tests fail, send back to the contributor to fix and repeat from step 3.
Running e2e for your own contributions
For your own PRs, the tests trigger automatically β approve the run and wait for results.
8. Review and merge PR
Important
PR approvals are enforced on all AVM Terraform module repositories. A PR cannot be merged until it has been approved by an authorized module owner.
Finding an approver
First port of call β find a friendly module owner. Look up another active Terraform module owner from the azure-verified-modules-module-contributors Entra group and request a review from them directly. This is the fastest path to approval.
If no module owner is available, fall back to the AVM core team:
Assign the @Azure/azure-verified-modules-engineering-owners GitHub team as a reviewer on the PR.
Apply the Β Needs: Core Team π§Β label so the request is picked up during core team triage.
Address any review comments and push updates to your branch.
Request a re-review once changes are made.
The module owner will merge the PR once approved and tests pass.
For a brand new module being published for the first time, get the module reviewed by the AVM Core team by following the AVM Review Process before merging.
Owner responsibilities
Keep the root metadata.json up to date, including every approved owner, through the metadata review process. Complete owner access approval separately.
Watch PR and issue activity for your module and respond in a timely manner as per SNFR11.
This step is performed by the module owner only. Skip it for metadata-only changes: updates to metadata.json must not trigger a module release. See the metadata maintenance process.
After the PR is merged to main, create a release via GitHub Releases:
Go to the Releases tab and click Draft a new release.
Set Target to the main branch.
Type a new tag (e.g. v0.1.0 for first publish, or increment for subsequent releases). Tags MUST include the v prefix.
Use Generate release notes and credit external contributors.
Click Publish release.
First module publish
For a brand new module, contact the AVM core team (e.g. via the AVM - Module Triage project) to request initial publication to the HashiCorp Registry. Subsequent releases are published automatically.
Important
Continue publishing in the v0.x.y range (e.g., v0.1.0, v0.1.1, v0.2.0) until the AVM team notifies you that v1.0.0 is allowed.
Common mistakes to avoid
Search and update TODO comments that come from the template β remove them once addressed.
Do not commit terraform.lock.hcl β it is excluded by .gitignore.
Update _header.md and SUPPORT.md.
Do not commit terraform.tfvars files.
Do not commit .env files created by lifecycle hooks.
Do not add shell (.sh) lifecycle hooks β see Lifecycle hooks.
Terraform Composition
Important
AzAPI is the required Azure provider for new AVM Terraform modules. Every new resource, pattern, or utility module MUST use the Azure/azapi provider for every control-plane resource and supported data-plane operation.
AzureRM is permitted only for a specific unsupported data-plane/non-ARM API operation under the narrow TFFR3 exception. The exception applies only to that operation; supporting control-plane resources in the module, submodules, examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets MUST use AzAPI.
This guide MUST be used in conjunction with the Terraform specifications. All AVM modules MUST meet the applicable requirements in those specifications.
This repo will be created by the Module Owners and the AVM Core team collaboratively, including the configuration of permissions as per SNFR9
Directory and File Structure
Below is the directory and file structure expected for each AVM Terraform repository/module. See the Terraform AVM template repository. The azurerm segment in this legacy repository name is not a provider choice; modules created from the template MUST use AzAPI.
tests/ - (for unit tests and integration tests using Terraform test)
unit/ - (.tftest.hcl files for required unit testing with Terraform test)
setup.ps1 - (optional setup hook)
integration/ - (optional .tftest.hcl files for integration testing with Terraform test)
setup.ps1 - (optional setup hook)
modules/ - (for sub-modules only if used; each submodule root MUST be a direct modules/<name>/ child)
examples/ - (all examples must deploy successfully without requiring input and use AzAPI for supporting control-plane resources; AzureRM may appear only when exercising the module’s documented unsupported data-plane exception - these are customer facing and run as end-to-end tests)
<at least one folder> - (at least one example that uses the variable defaults minimum/required parameters/variables only)
pre.ps1 - (optional setup hook)
post.ps1 - (optional cleanup hook)
tflint-pre.ps1 - (optional setup hook for TFLint)
.e2eignore - (optional marker that excludes the example from e2e testing)
<other folders for examples as required> - (each example root MUST be a direct examples/<name>/ child)
/... - (Module files that live in the root of module directory)
_header.md - (required for documentation generation)
_footer.md - (required for documentation generation)
main.tf
locals.tf
variables.tf
outputs.tf
terraform.tf
README.md (autogenerated)
main.resource1.tf (If a larger module you may chose to use dot notation for each resource)
locals.resource1.tf
See Lifecycle hooks for hook execution, environment, and migration guidance.
Nested Terraform module and example roots are prohibited. Avm.Authoring convention validation enforces the one-layer modules/* and examples/* structure; see TFRMNFR1.
Code Styling
This section points to conventions to be followed when developing a module.
This section is only relevant for contributions to resource modules.
To meet RMFR4 and RMFR5 AVM resource modules must leverage consistent interfaces for all the optional features/extension resources supported by the AVM module primary resource.
Every Terraform AVM module MUST be built with AzAPI, and every resource module MUST implement the following AzAPI patterns. The cross-references point at the normative specs β this section only summarises them so that nothing here is missed during scaffolding.
Use Azure/azapi for every control-plane resource and supported data-plane operation in the module, submodules, examples/e2e tests, Terraform tests, fixtures, and documentation snippets. AzureRM is permitted only for a documented data-plane/non-ARM operation that AzAPI cannot implement.
Expose the parent scope as a single required parent_id string variable. Do not expose resource_group_name or any other scope-specific input. Validate with provider::azapi::parse_resource_id against the expected parent type.
Implement every ARM subresource as a Terraform submodule under a direct modules/<subresource-singular-name>/ child. Parent modules MUST reference submodules, and submodules MUST be independently consumable. Keep submodule primary resources single-instance only (no count / for_each on azapi_resource.this); cardinality belongs at the module call site. Nested module roots are prohibited.
Name the primary azapi_resourcethis. Satellite resources MUST be named after what they represent (e.g. azapi_resource.lock, azapi_resource.role_assignment, azapi_resource.diagnostic_setting, azapi_resource.private_endpoint), not this.
Always set response_export_values on every AzAPI resource (use [] when nothing needs exporting). Include any read-only properties the module’s outputs or downstream resources depend on.
Set replace_triggers_refs only when body paths require replacement. The non-empty static list MUST contain valid, unique JMESPath expressions; omit the argument when no paths are needed. name and location are already triggers, so don’t repeat them.
Source the type argument of every AzAPI resource from a single resource_types object variable instead of hard-coding type strings. Use one optional key per resource, defaulted to the tested API version, and cascade the relevant subset to each submodule.
Expose an ignore_body_changes object variable so consumers can suppress diffs on body paths derived from non-static values. Use one optional list(string) key per resource (same key naming as resource_types), collapse empty lists to null, and cascade the relevant nested slot to each submodule β never the parent’s own paths.
Validate every variable (or nested attribute) that holds an Azure ARM resource ID using can(provider::azapi::parse_resource_id("Microsoft.X/y", value)). Hand-rolled regex / startswith / length checks MUST NOT be used.
Use the standard file layout (terraform.tf, variables.tf, outputs.tf, main.tf, locals.tf). Larger modules MAY split main.tf into main.<topic>.tf files.
The interface schema files under static/includes/interfaces/tf/ are the canonical, copy-pasteable templates for the variables described by these specs. Treat them as authoritative.
Telemetry
To meet the requirements of SFR3 & SFR4, we use the modtm telemetry provider. This lightweight telemetry provider sends telemetry data to Azure Application Insights via a HTTP POST front end service.
The modtm telemetry provider is included in all Terraform modules and enabled by default through main.telemetry.tf, which is generated and maintained by Avm.Authoring. You do not need to change this configuration.
Make sure that the modtm provider is listed under the required_providers section in the module’s terraform.tf file using the following entry. This is also validated by the linter.
The AVM module review is a critical step before an AVM Terraform module gets published to the Terraform Registry and made publicly available for customers, partners and wider community to consume and contribute to. It serves as a quality assurance step to ensure that the AVM Terraform module complies with the Terraform specifications of AVM. The below process outlines the steps that both the module owner and module reviewer need to follow.
Important
A new module is not eligible for review or publication unless it uses AzAPI for every control-plane resource and supported data-plane operation. Reviewers MUST reject any AzureRM block that does not implement and document the narrow unsupported data-plane/non-ARM API exception in TFFR3. Review the root module, submodules, examples/end-to-end tests, Terraform tests, fixtures, and documentation snippets; all supporting control-plane resources must use AzAPI.
The module owner completes the development of the module in their branch or fork.
The module owner submits a pull request (PR) titled AVM-Review-PR and ensures that all checks are passing on that PR as that is a pre-requisite to request a review.
The module owner assigns the @Azure/azure-verified-modules-engineering-owners GitHub team as reviewer on the PR.
The module owner leaves the following comment as it is on the module proposal in the AVM - Module Triage project by searching for their module proposal by name there.
β AVM Terraform Module Review Request
I have completed my initial development of the module and I would like to request a review of my module before publishing it to the Terraform Registry. The latest code is in a PR titled [AVM-Review-PR](REPLACE WITH URL TO YOUR PR) on the module repo and all checks on that PR are passing.
The AVM team moves the module proposal from “In Development” to “In Review” in the AVM - Module Triage project.
The AVM team will assign a module reviewer who will open a blank issue on the module titled “AVM-Review” and populate it with the below mark down. This template already marks the specs as compliant which are covered by the checks that run on the PR. There are some specs which don’t need to be checked at the time of publishing the module therefore they are marked as NA.
β AVM Terraform Module Review Issue
Dear module owner,
As per the module ownership requirements and responsibilities at the time of [assignment](REPLACE WITH THE LINK TO THE AVM MODULE PROPOSAL), the AVM Team is opening this issue, requesting you to validate your module against the below AVM specifications and confirm its compliance.
Please don’t close this issue and merge your AVM-Review-PR until advised to do so. This review is a prerequisite for publishing your module’s v0.1.0 in the Terraform Registry. The AVM team is happy to assist with any questions you might have.
Requested Actions
Complete the below task list by ticking off the tasks.
Complete the below table by updating the Compliant column with Yes, No or NA as possible values.
Please use the comments columns to provide additional details especially if the Compliant column is updated to No or NA.
Tasks
Address comments on AVM-Review-PR if any
Ensure that all checks on AVM-Review-PR are passing
Confirm every control-plane resource and supported data-plane operation uses AzAPI across the root module, submodules, examples/e2e tests, Terraform tests, fixtures, and documentation snippets. Any AzureRM block must implement and document the narrow TFFR3 unsupported data-plane exception.
Tick this to acknowledge specs with comment “Module Owner to action this spec post-publish as appropriate” in the table below.
Please update the _header.md file as it contains instructions which - once actioned - need to be replaced with Module Name and Description.
The module reviewer can update the Compliance column for specs in line 42 to 47 to NA, in case the module being reviewed isn’t a pattern module.
The module reviewer reviews the code in the PR and leaves comments to request any necessary updates.
The module reviewer assigns the AVM-Review issue to the module owner and links the AVM-Review Issue to the AVM-Review-PR so that once the module reviewer approves the PR and the module owner merges the AVM-Review-PR, the AMV-Review issue is automatically closed. The module reviews responds to the module owner’s comment on the Module Proposal in AVM Repo with the following
Thank you for requesting a review of your module. The AVM module review process has been initiated, please perform the **Requested Actions** on the AVM-Review issue on the module repo.
The module owner updates the check list and the table in the AVM-Review issue and notifies the module reviewer in a comment.
The module reviewer performs the final review and ensures that all checks in the checklist are complete and the specifications table has been updated with no requirements having compliance as ‘No’.
The module reviewer approves the AVM-Review-PR, and leaves the following comment on the AVM-Review issue with the following comment.
Thank you for contributing this module and completing the review process per AVM specs. The AVM-Review-PR has been approved and once you merge it that will close this AVM-Review issue. Please create a release with an initial minor version of `v0.1.0` (tags **MUST** include the `v` prefix) and then contact the AVM core team to publish this module to the HashiCorp Terraform Registry via HCP Terraform. Please continue publishing future versions in the v0.x.y minor range (e.g., `v0.1.0`, `v0.1.1`, `v0.2.0`, etc.) until the AVM team notifies you that publishing `v1.0.0` is allowed.
**Requested Action**: Once the AVM core team has published the module, please update your [module proposal](REPLACE WITH THE LINK TO THE MODULE PROPOSAL) with the following comment.
"The initial review of this module is complete, and the module has been published to the registry by the AVM core team. Requesting AVM team to close this module proposal and mark the module available in the module index.
Terraform Registry Link: <REPLACEWITHTHELINKOFTHEMODULEINTERRAFORMREGISTRY>
GitHub Repo Link: <REPLACEWITHTHELINKOFTHEMODULEINGITHUB>"
Once the module owner perform the requested action in the previous step, the module reviewer updates the module proposal by performing the following steps:
Assign label Status: Module Available :green_circle: to the module proposal.
Verify the module’s root metadata.json, including all approved owners. Correct metadata through a pull request to the module repository using the metadata review process.
Confirm publication to the Terraform Registry. The four-hourly catalog sync publishes the module index automatically once the module is published and its metadata is correct. Close the module proposal after the index shows the module as Available, which moves it from “In Review” to “Done” in the AVM - Module Triage project.
Advanced Topics & FAQ
This page covers advanced scenarios and frequently asked questions that go beyond the standard contribution flow.
Offline and air-gapped module mirroring
The offline sync utility mirrors AVM Terraform modules and rewrites registry dependencies as git references for offline or air-gapped environments.
<br
This utility is an example for advanced users familiar with PowerShell, Git, and Terraform module management. It is provided as-is and is not supported for production use.
Using a custom Azure test subscription
By default, CI runs against a centrally managed Azure subscription. If your module needs a different environment (quota limits, tenant-level deployments, dedicated tenant), you can override the defaults.
Understand the environments first. The managed workflow runs jobs across several GitHub Environments:
subscription selection, unit tests, example discovery
No
Steps
Create a user-assigned managed identity in your target Azure environment.
Create one federated credential per Azure-authenticated environment (pr-check, integration-test, and examples-test). The managed identity’s federated credentials require an exact subject match, so a single credential cannot cover multiple environments. Use the Other issuer (custom) option rather than the “GitHub Actions deploying Azure resources” wizard, because the wizard emits repo:ORG/REPO:environment:NAME, which does not match what these workflows present.
The repository’s centrally managed OIDC configuration includes immutable owner/repository IDs and a job_workflow_ref segment identifying the reusable workflow. If authentication fails with AADSTS700213, compare the subject in the error message with the federated credential for that environment.
Find your IDs with:
gh api 'repos/<ORG>/<REPO>' --jq '{repository_id: .id, repository_owner_id: .owner.id}'
Assign appropriate Azure roles to the managed identity on the target subscription (and at management-group scope for pattern modules that assign policy or create role assignments).
Add repository Actions variables (Settings > Secrets and variables > Actions > Variables > New repository variable). These IDs are non-secret configuration. Module owners can manage repository variables; environment-scoped configuration is managed by the AVM core team.
ARM_CLIENT_ID_OVERRIDE - client ID of the managed identity.
ARM_TENANT_ID_OVERRIDE - tenant ID of the target Azure environment.
ARM_SUBSCRIPTION_ID_OVERRIDE - ID of the target Azure subscription.
Set all three values for the same target Azure environment. The workflow maps nonempty overrides to the corresponding ARM_* variables in each Azure-authenticated job. ARM_SUBSCRIPTION_ID_OVERRIDE takes precedence over the centrally selected subscription, so all example legs use your subscription instead of distributing deployments across the shared pool.
Do not change the repository defaults ARM_CLIENT_ID, ARM_TENANT_ID, or TEST_SUBSCRIPTION_IDS; these are managed by repository synchronization. Leave the shared subscription selection configured, because that job still runs before the overrides are applied. There is no TEST_SUBSCRIPTION_IDS_OVERRIDE.
Tip
ARM_*_OVERRIDE remains supported. The workflow merges variables first, then secrets, so a same-named override secret (including an environment secret) masks the variable. If your variables do not take effect, check for conflicting repository override secrets and ask the AVM core team to check for conflicting environment-scoped overrides.
Custom variables and secrets for end-to-end tests
The test environment in each module repository has approvals and secrets configured for e2e tests. If you need additional variables or secrets:
Add them to the test environment in your repository settings.
They must be prefixed with TF_VAR_ β other prefixes will be ignored.
OPA (Conftest) policy exceptions
Conftest checks the plan for compliance with the Well-Architected Framework using OPA policies.
If you get policy failures that need an exception, create a .rego file in the exceptions sub-directory of the relevant example:
TFLint checks AVM spec compliance using the AVM custom ruleset. See the AVM TFLint rules guide for every enabled AVM rule, its applicability, exact disable block, and override precedence.
To override a rule, create one of the following HCL files in the root of your module:
File
Scope
avm.tflint.override.hcl
Root module
avm.tflint_module.override.hcl
Submodules
avm.tflint_example.override.hcl
Examples
modules/<name>/avm.tflint.override.hcl
One direct submodule
examples/<name>/avm.tflint.override.hcl
One direct example
Example:
# Disable the required resource id output rule β this is a pattern module.
rule"avm_output_resource_id_required" {
enabled =false}
Include a comment explaining why the rule is disabled.
The target-directory override takes precedence over the matching repository-wide scope override and applies only to that direct submodule or example. AVM permits only modules/* and examples/* Terraform roots; nested module or example roots are prohibited and rejected by Avm.Authoring convention validation. Use a target override instead of weakening an all-submodule or all-example override.
Excluding examples from end-to-end testing
Create a file called .e2eignore in the example directory. Its contents should explain why the example is excluded from tests.
Global test setup and teardown
Avm.Authoring has no global setup or teardown hook. It does not execute or reject the legacy files:
examples/setup.sh
examples/teardown.sh
Move required setup and cleanup into idempotent per-example pre.ps1 and post.ps1 hooks. Coordinate removal of legacy global scripts with the repository’s centrally managed CI workflow migration because older workflows can still invoke them.
Per-example pre and post scripts
For example-specific setup/teardown:
examples/<example_name>/pre.ps1 (optional) β runs before Terraform commands for the example.
examples/<example_name>/post.ps1 (optional) β always runs after the example, including after a pre-hook or initialization failure.
Shell equivalents are rejected. Each PowerShell hook runs in an isolated process; see Lifecycle hooks for .env, path, and error-handling guidance.
Repository synchronization PRs
Repository sync regularly compares each module repository with the shared managed files and opens a PR when updates are available. These PRs are normally merged automatically. Module owners will be informed about one-off PRs that require intervention.
Sync uses the default branch’s root metadata.json for the display name and full owner list. Submit changes to those values through the metadata review process.
A synchronization update can include module source and managed configuration. Review any requested intervention accordingly; source changes need normal validation and release handling. A metadata-only change does not require a module release.
Eventual consistency
The Azure Resource Manager API can be eventually consistent. For example, data plane role assignments may not be available immediately after creation.
Use the AzAPI provider’s retry functionality to handle eventual consistency instead of arbitrary time_sleep delays. The AzAPI provider supports configurable retry with retry blocks that can match on specific error codes, providing a more reliable and efficient approach.
Repository Creation Process
Important
This page is for module owners only. If you are an external contributor, skip to the contribution flow.
Important
Every repository created through this process MUST use AzAPI for every control-plane resource and supported data-plane operation. AzureRM is permitted only for a specific unsupported data-plane/non-ARM API operation under the narrow TFFR3 exception. The exception must be documented and applies only to that operation in the root module, submodules, examples, end-to-end tests, Terraform tests, fixtures, and documentation snippets.
Important
If this process is not followed exactly, it may result in your repository and any in-progress code being permanently deleted.
1. Add yourself to the Module Owners Team and Open Source orgs
If you have already completed these steps, skip to step 2.
Open the Open Source Portal and ensure your GitHub account is linked to your Microsoft account.
Open the Open Source Portal and ensure you are a member of the Azure and Microsoft organizations.
Approved display name, passed as moduleDisplayName
Module description
Required approved description, passed as moduleDescription
Canonical type
Required approved ARM resource type or pattern/utility taxonomy, passed as canonicalType. Resource modules can instead supply both fields in the next row. Do not infer the value from the module name.
Resource provider namespace and resource type
For resource modules only, resourceProviderNamespace and resourceType together are an alternative to canonicalType (e.g. Microsoft.Network and virtualNetworks). They are not required when canonicalType is supplied.
Telemetry ID prefix
Optional telemetryIdPrefix. Supply the assigned identifier if the proposal has one. If you omit it, creation mints one in the fleet format 46d3xtrf.<res|ptn>.<7 lowercase hex characters> for resource and pattern modules. Never hand-pick an identifier yourself.
Owners
ownerGitHubHandles, a PowerShell string array of approved bare usernames or qualified @organization/team-slug entries. ownerTeam adds an approved owning team, and the legacy ownerPrimaryGitHubHandle and ownerSecondaryGitHubHandle parameters are still accepted.
Alternative names
Optional moduleAlternativeNames, a comma-separated string; the tooling splits it for JSON metadata
Record every approved owner. An empty owner array is valid for an unowned module, subject to the proposal and ownership processes. Metadata does not grant access. Later ownership changes use the metadata review process.
Supply the approved canonicalType below. For a resource module, you can instead replace that entry with both resourceProviderNamespace and resourceType; pattern and utility modules require an explicit canonicalType. Supply the assigned telemetry prefix if the proposal has one; otherwise omit telemetryIdPrefix and let creation mint it for resource and pattern modules. Utility modules do not use telemetry. Do not derive telemetry identifiers from repository names or replace existing identifiers.
if (!(Test-Path -Path ".\scripts\New-Repository.ps1")) {
Write-Error "This script must be run from the repository-creation directory." exit 1}
$parameters = @{
moduleName = "<approved module name>" moduleDisplayName = "<approved display name>" moduleDescription = "<approved description>" canonicalType = "<approved ARM resource type or taxonomy>" ownerGitHubHandles = @("<approved individual handle>")
}
.\scripts\New-Repository.ps1 @parameters -planOnly
Add optional entries from the table when needed, including telemetryIdPrefix when the proposal already assigns one. Keep ownerGitHubHandles as an array, such as @("first-owner", "@Azure/approved-team"), and moduleAlternativeNames as a comma-separated string.
-planOnly and -WhatIf validate the inputs and show the plan without making GitHub or filesystem changes. Review the plan, including any minted telemetry identifier, and obtain the required approval before running the same command without either switch.
Creation publishes validated root metadata in the first commit to main. If creation fails, stop and follow the recovery guidance in the tooling README before retrying.
Complete Open Source Portal Setup
The script will pause and prompt you to configure the Open Source Portal. Follow the link in the script output.
β If you see the Complete Setup link
Click Complete Setup and use the following settings:
Question
Answer
Classify the repository
Production
Assign a Service tree or Opt-out
Azure Verified Modules / AVM
Direct owners
Add yourself, jaredholgate, and jatracey. Add azure-verified-modules-module-owners as fallback security group. You add yourself temporarily so you can configure JIT in step 4; you will remove yourself afterwards.
Public open source licensed project?
Yes
What type of open source?
Sample code
License
MIT
All code created by your team?
Yes
Telemetry?
Yes, telemetry
Cryptography?
No
Project name
Azure Verified Module (Terraform) for ‘module name’
Project version
1
Project description
Azure Verified Module (Terraform) for ‘module name’. Part of AVM project - https://aka.ms/avm
Business goals
Create IaC module accelerating Azure deployment using Microsoft best practice.
Used in a Microsoft product?
Open source, can be leveraged in Microsoft services.
Security best practice?
Yes, use just-in-time elevation
Maintainer / Write permissions
Leave empty
Repository template / .gitignore
Uncheck both
Click Finish setup + start business review, then View repository, then Elevate your access.
β If you do NOT see the Complete Setup link
Go to the Compliance tab and fill out:
Direct owners: Add yourself, jaredholgate, and jatracey. Add azure-verified-modules-module-owners as fallback. You add yourself temporarily so you can configure JIT in step 4; you will remove yourself afterwards.
Classify the repository: Production
Service tree: Azure Verified Modules / AVM
Go back to Overview and click Elevate your access if available.
Return to the terminal and type yes to complete repository configuration.
The script creates the Azure Verified Modules GitHub App installation request.
Note
Maintain the module’s details and full owners array through metadata code-owner review. Complete the Open Source Portal, access-package, and JIT requirements separately.
4. Upgrade just-in-time access to JITv2
New repositories default to JIT v1. AVM repositories must be upgraded to JIT v2 and tied to the shared service-AVM-azure-verified-modules-module-owners rule, so that just-in-time elevation is governed centrally by the AVM team rather than by a repository-specific rule.
This is a one-off manual action in the Open Source Portal. You need Direct Owner access to the repository (configured in the previous step) to complete it.
Migrate the repository to JIT v2
Open the repository overview on the Open Source Portal: https://repos.opensource.microsoft.com/orgs/Azure/repos/<module name>.
In the right-hand sidebar, find the Improved Just-in-time (New) panel and click Next.
Review the concepts (Rule Version, Rule, Tie) and click Next.
Leave Require approval for elevation selected and click Upgrade <module name> now.
This migrates the repository to JIT v2 and creates a temporary repository-scoped starter rule. Reload the page and confirm the Just-in-time elevation section now shows JIT version: JIT v2.
Tie the repository to the shared AVM rule
On the repository overview, click Advanced JIT options, then select Propose a new tie.
Under Propose tying a new rule to this repository, enter the Rule ID service-AVM-azure-verified-modules-module-owners and click Review.
Confirm the details and click Create tie.
The tie is created in a pending approval state, so the temporary repository-scoped rule stays active until the tie is approved.
Info
The pending tie must be approved by an owner of the service-AVM-azure-verified-modules-module-owners rule (an AVM core team member). Ask the AVM core team to approve it. Once approved, just-in-time elevation for the repository is governed by the shared AVM rule and the temporary starter rule can be ignored.
Remove yourself as a Direct Owner
You were added as a Direct Owner so you could perform the JIT configuration above. Once you have finished both the JIT v2 upgrade and the shared-rule tie, remove your own account so that only jaredholgate and jatracey remain as Direct Owners.
On the Open Source Portal, open the repository’s Compliance tab.
Under Direct owners, remove your own account, leaving only jaredholgate and jatracey.
Info
Module owners retain day-to-day access through the azure-verified-modules-module-owners security group and just-in-time elevation, so you do not need to remain a Direct Owner.
5. Wait for the GitHub App and repository sync
After the app is installed, repository sync applies the shared repository configuration and managed files to complete the setup.
Sync reads the root metadata.json from the module repository’s default branch for the display name and full owner list.
AVM TFLint Rules
This reference covers the custom AVM TFLint ruleset rules. It does not repeat rules provided by the standard Terraform TFLint plugin. AVM rules are enabled by default. An override is an exception to an AVM requirement and should be narrow, temporary where possible, and explained in the override file.
Rule applicability and overrides
Rules run in the scope that contains the applicable Terraform configuration:
All module scopes - the root module, each submodule, and each example independently.
Module scopes - the root module and each submodule independently; examples are excluded.
Root module - the published module root only.
To disable a rule, use the exact HCL shown in the Disable column. The configuration files and precedence rules are documented in TFLint configuration overrides.
Applicable AzAPI resources expose and apply timeouts.
All module scopes
rule "avm_interface_timeouts" { enabled = false }
Per-rule severity
Version 1.0.0 of the AVM plugin supports an optional severity input on every AVM rule block. The exact supported values are error, warning, and notice. When severity is omitted, the rule keeps its default severity.
This setting is specific to rules provided by the AVM plugin and changes the severity emitted by that rule. It is separate from TFLint’s global --minimum-failure-severity option, which sets the failure threshold for the TFLint process rather than configuring an individual rule’s severity.
Breaking change in v1.0.0: rule names
AVM TFLint ruleset v1.0.0, released through ruleset PR #159, renamed all rules to canonical avm_* names without compatibility aliases. Update the label of every affected TFLint rule block in .tflint.hcl and AVM override files:
These renames apply only to TFLint rule identifiers. Terraform input variable names such as ignore_body_changes, resource_types, retry, and timeouts are unchanged.
Rule guidance
avm_azapi_data_response_export_values_required
Applies TFFR4 to AzAPI data sources: declare response_export_values, including [] when no response fields are needed.
avm_azapi_replace_triggers_refs_valid
Applies TFFR5. Omit replace_triggers_refs when no body paths require replacement. When present, it must be a non-empty static list of valid JMESPath expressions that identify body paths requiring replacement. Entries cannot be blank or duplicated, and cannot include name or location, because AzAPI already replaces the resource when either changes. When the body is statically evaluable, the rule verifies that each declared path resolves against it.
Authors remain responsible for identifying the properties that actually require replacement. Current Bicep-generated schemas do not reliably preserve create-only versus updateable mutability, so this rule validates declared paths but cannot prove that the list is semantically complete.
avm_azapi_resource_tags_required
Applies TFFR9: types with writable tags in the embedded AVM-generated capability snapshot must set tags from a consumer-settable expression. A direct tags = var.tags assignment remains valid, and modules can use the typed resource_tags replacement interface documented by the standard tags interface. Types with read-only or unsupported tags must omit the argument. The rule does not require one exact tags expression and skips dynamic or otherwise unevaluable type expressions.
The ruleset embeds its AVM-generated capability snapshot and works standalone. It does not consume, import, or query AzAPI, and does not accept an external snapshot path.
A weekly ruleset workflow compares the embedded snapshot with upstream data and opens a ruleset pull request when that data changes. Updated capability data ships with the next ruleset release. All users receive snapshot updates by upgrading the ruleset release.
avm_azapi_response_export_values_required
Applies TFFR4: every applicable managed AzAPI resource declares response_export_values, including [] when no fields are exported.
Validates the optional resource_tags variable when it is declared. The variable must default to null and permit null values. Its type must use one or both non-empty, optional resources and modules namespaces without inline defaults. Resource labels must be optional map(string) leaves, module labels must be optional objects that recursively use the same shape, and the complete type must contain at least one resource leaf. The separate namespaces identify Terraform resource and module block labels without collisions.
Validates the tags interface. The backward-compatible tags fallback remains a nullable map(string). When a module exposes resource_tags, its deterministic typed resources and modules namespaces provide complete per-resource replacements without merging.
avm_terraform_literal_heredoc_disallowed
Applies TFNFR40: represent JSON or YAML structured values with jsonencode or yamlencode.
avm_terraform_provider_block_disallowed
Applies TFNFR27: a published module contains no provider blocks; aliases are declared only through configuration_aliases and configured by its consumer.
The standard Terraform TFLint plugin validates required_version and provider requirement declarations. TFNFR25 and TFNFR26 explain the complementary AVM file-layout and ordering requirements.
TFLint configuration overrides
Avm.Authoring loads the following repository-root override files:
File
Default scope
avm.tflint.override.hcl
All root-module checks
avm.tflint_module.override.hcl
All submodule checks
avm.tflint_example.override.hcl
All example checks
modules/<name>/avm.tflint.override.hcl
One direct submodule
examples/<name>/avm.tflint.override.hcl
One direct example
Each file contains normal TFLint rule configuration. For example:
Avm.Authoring merges overrides in this order: the immutable AVM base configuration, the matching repository-root all-scope override, then the target-directory override. A submodule or example override is loaded only for its target directory and takes precedence over the matching all-submodule or all-example file. Use it when an exception is specific to one direct child module or example; do not weaken the corresponding repository-wide default.
AVM permits only one directory layer for Terraform submodule and example roots: modules/* and examples/*. Nested Terraform module or example roots are prohibited, so target overrides apply only to those direct scopes. Avm.Authoring convention validation enforces this structure.
Website Contribution Guide
Looking to contribute to the AVM Website, well you have made it to the right place/page. π
Follow the below instructions, especially the pre-requisites, to get started contributing to the library.
Context/Background
Before jumping into the pre-requisites and specific section contribution guidance, please familiarize yourself with this context/background on how this library is built to help you contribute going forward.
This site is built using Hugo, a static site generator, that’s source code is stored in the AVM GitHub repo (link in header of this site too) and is hosted on GitHub Pages, via the repo.
The reason for the combination of Hugo & GitHub pages is to allow us to present an easy to navigate and consume library, rather than using a native GitHub repo, which is not easy to consume when there are lots of pages and folders. Also, Hugo generates the site in such a way that it is also friendly for mobile consumers.
But I don’t have any skills in Hugo?
That’s okay and you really don’t need them. Hugo just needs you to be able to author markdown (.md) files and it does the rest when it generates the site π
Pre-Requisites
Read and follow the below sections to leave you in a “ready state” to contribute to AVM.
A “ready state” means you have a forked copy of the Azure/Azure-Verified-Modules repo cloned to your local machine and open in VS Code.
Run and Access a Local Copy of AVM Website During Development
When in VS Code you should be able to open a terminal and run the below commands to access a copy of the AVM website from a local web server, provided by Hugo, using the following address http://localhost:1313/Azure-Verified-Modules/:
cd docs
hugo server -D // you can add "--poll 700ms", if file changes are not detected
Software/Applications
To contribute to this website, you will need the following installed:
Tip
You can use winget to install all the pre-requisites easily for you. See the below section
Steps to do before contributing anything (after pre-requisites)
Run the following commands in your terminal of choice from the directory where you fork of the repo is located:
git checkout main
git pull
git fetch -p
git fetch -p upstream
git pull upstream main
git push
Doing this will ensure you have the latest changes from the upstream repo, and you are ready to now create a new branch from main by running the below commands:
git checkout main
git checkout -b <YOUR-DESIRED-BRANCH-NAME-HERE>
Top Tips
Sometimes the local version of the website may show some inconsistencies that don’t reflect the content you have created
If this happens, simply kill the Hugo local web server by pressing CTRL + C and then restart the Hugo web server by running hugo server -D from the docs/ directory.
Experimental
Experimental Content - No Long-Term Support Guarantee
The content in this section represents experimental exploration of emerging technologies and innovative approaches. The AVM team makes no guarantees regarding:
Long-term support or maintenance of solutions described here
Future direction or adoption of these approaches into core AVM guidance
Stability or compatibility of experimental features over time
This section may evolve rapidly or be deprecated as technology and best practices advance.
About This Section
This section showcases the AVM team’s exploration of cutting-edge technologies and methodologies that have the potential to enhance Azure infrastructure development. The content here represents forward-thinking experiments and proof-of-concepts that we believe are valuable to share with the broader community.
What to Expect
Experimental by Nature: The solutions and approaches documented in this section are under active exploration. They may change significantly, be superseded by better alternatives, or be discontinued as we learn more about their practical applications and limitations.
Community Innovation: Some of the tooling, integrations, and methodologies featured here may be developed by community members, partners, or external teams rather than the AVM core team or AVM module owners. While we strive to ensure quality, these solutions may have different support models and maturity levels than core AVM content or AVM modules.
Shared Learning: By documenting and sharing these experimental approaches, we aim to foster innovation, gather feedback, and accelerate the discovery of what works well in real-world scenarios. Your experience and feedback with these experimental features are invaluable.
Your feedback is welcome!
We encourage you to try these experimental features and share your experiences. Your feedback helps us understand what resonates with the community and what might be worth developing further or integrating into core AVM guidance.
Given the experimental nature of this content, we recommend:
Testing thoroughly in non-production environments before considering production use
Understanding the limitations and potential for breaking changes
Having contingency plans if an experimental feature is deprecated or significantly changed
Staying informed about updates and changes to experimental features you’re using
Explore the experimental features below to see what’s on the horizon for Azure IaC development with AVM!
Subsections of Experimental
AI-Assisted IaC Solution Development
Experimental Content
The content in this section represents experimental exploration of emerging technologies and innovative approaches. To learn more about our experimental content and its implications, please refer to the Experimental Section Overview.
For End Users
This section covers solution development scenarios and is primarily relevant for end users aiming to develop complex solutions based on AVM modules using AI. If you are a module owner looking for content on maintaining and developing AVM modules with AI assistance, see AI-Assisted Module Development.
This section explains concepts of developing IaC solution templates using Azure Verified Modules (AVM) with the assistance of AI tools such as GitHub Copilot and covers how AI-assisted development can accelerate the process of building and deploying Azure solutions using AVM modules.
This approach is referred to as AI-assisted IaC solution development rather than AI-driven or AI-led because humans remain fully in control of architectural decisions and solution design - AI simply handles the tedious, error-prone tasks of code generation and standards compliance, amplifying human ingenuity rather than replacing it.
AVM and GitHub Copilot
In the rapidly evolving landscape of AI, the convergence of Azure Verified Modules (AVM) and GitHub Copilot represents a transformative approach to building Azure solutions, addressing the fundamental challenges developers face: maintaining quality, consistency, and speed while navigating the complexity of modern cloud architectures.
How They Work Together
AVM provides the foundational “knowledge base”: Comprehensive, standardized, continuously updated, pre-validated modules that embody Azure best practices, security standards, and architectural patterns. Each module undergoes rigorous testing and validation, ensuring reliability and compliance with Microsoft’s standards.
GitHub Copilot brings AI-powered intelligence to the development workflow: AI-assisted code generation, module discovery, and real-time guidance based on AVM specifications with understanding both natural language intent and code context. Equipped with knowledge of AVM specifications and practices, Copilot serves as an expert guide that can:
Intelligently discover and recommend the appropriate AVM modules for your specific requirements
Generate compliant infrastructure code that adheres to AVM standards and Azure best practices
Accelerate development cycles by automating repetitive tasks and reducing manual lookups
Maintain consistency across your infrastructure codebase
Reduce errors by leveraging validated patterns and catching compliance issues early
Developers focus on solution architecture: This approach enables teams to dedicate more time to designing solutions that meet business requirements, rather than working on repetitive tasks.
This synergy means developers can express their infrastructure needs in natural language, and Copilot translates these into production-ready IaC code using validated AVM modules, complete with appropriate configurations, security settings, and dependencies.
The Result
What once required hours of documentation review, module discovery, and manual code writing can now be accomplished in minutes. Infrastructure teams can iterate faster, maintain higher quality standards, and deliver Azure solutions with confidence, knowing they’re built on a foundation of verified, best-practice modules guided by AI technology.
The combination of human expertise, Azure Verified Modules, and AI assistance creates a new opportunity to transform how we build and deploy cloud solutions at scale.
Subsections of AI-Assisted IaC Solution Development
Spec Kit
Experimental Content
The content in this section represents experimental exploration of emerging technologies and innovative approaches. To learn more about our experimental content and its implications, please refer to the Experimental Section Overview.
Overview
Spec Kit is a reference implementation of Specification-Driven Development (SDD) principles, developed by members of the open-source community, including engineers from Microsoft and Anthropic. It provides a structured, AI-native workflow for translating project requirements into specifications, plans, executable tasks and implemented code - demonstrating how SDD concepts can be operationalized.
For detailed information (installation instructions, usage guidelines, etc.) visit the official repository: https://github.com/github/spec-kit
Example Scenario
In this chapter we’ll explore each step of the Spec Kit workflow in detail. We’ll use the following example to illustrate the process: using AVM modules, we need to develop a solution that will host a simple legacy application on a Windows virtual machine (VM). The solution must be secure and auditable. The VM must not be accessible from the internet and its logs should be easily accessible.
The Spec Kit Workflow
Spec Kit guides development teams through a systematic process that ensures specifications remain the single source of truth throughout the development lifecycle:
flowchart TB
subgraph CAS["Constitution and Specification"]
direction LR
A["**Step 1**<br><code>/speckit.constitution</code><br>Establish project principles"] --> B["**Step 2**<br><code>/speckit.specify</code><br>Create baseline specification"]
B --> C["**Step 3** <br><code>/speckit.clarify</code><br>(optional)<br>Ask structured questions"]
end
subgraph PAT["Implementation Plan and Tasks"]
direction LR
D["**Step 4** <br><code>/speckit.plan</code><br>Create implementation plan"] --> E["**Step 5** <br><code>/speckit.checklist</code><br>(optional)<br>Generate quality checklists"]
E --> F["**Step 6** <br><code>/speckit.tasks</code><br>Generate actionable tasks"]
F --> G["**Step 7** <br><code>/speckit.analyze</code><br>(optional)<br>Consistency & alignment report"]
end
subgraph IMP["Implementation"]
H["**Step 8** <br><code>/speckit.implement</code><br>Execute<br>implementation"]
end
CAS --> PAT
PAT --> IMP
click A "#1-constitution"
click B "#2-specify"
click C "#3-clarify-optional"
click D "#4-plan"
click E "#5-checklist-optional"
click F "#6-tasks"
click G "#7-analyze-optional"
click H "#8-implement"
style C fill:#e1f5ff
style E fill:#e1f5ff
style G fill:#e1f5ff
style CAS fill:#f5f5f5,stroke:#999999
style PAT fill:#f5f5f5,stroke:#999999
style IMP fill:#f5f5f5,stroke:#999999
Each command in the workflow works with a number of AI agents, including GitHub Copilot, enabling AI-assisted processing through the specification-to-implementation pipeline while maintaining human control over architectural decisions and project direction.
1. Constitution
The constitution document (constitution.md) establishes the governing principles, development guidelines and project-wide constraints that every later step (spec, plan, tasks, implementation) must follow. It acts as the “North Star” for the AI agent. It ensures that fundamental requirements are always met by encoding architectural, compliance, security, coding, and operational rules.
Spec Kit uses /speckit.constitution to generate the constitution.md file. The constitution can be evolved through iterating over the constitution.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.constitution.
The constitution typically includes:
Required engineering standards
Guardrails and constraints
Required / discouraged patterns
Organizational coding standards
Testing expectations
Cloud/platform governance
Naming conventions, tagging rules
Compliance/security requirements
Following our scenario, here are some examples for what the prompt used to generate the constitution should include:
Architecture & Cloud Rules
Infrastructure must be declarative and written in Bicep only.
Must use Azure Verified Modules (AVM) for all supported resource types.
Deployment must follow a modular architecture using AVM best practices/standards.
Security & Compliance
Enforce NSG rules, disable all incoming traffic from the internet, require JIT.
OS hardening baseline must be applied via VM extension or custom script.
All storage must have private endpoints and be encrypted using CMK if required.
Ops & Reliability
Centralized logging via Azure Monitor / Log Analytics workspace.
Diagnostics extensions required for Windows Server.
Naming & Tagging
All resources follow Microsoft Cloud Adoption Framework naming conventions.
Deployment must succeed in at least one Azure region with a Windows Server SKU supported by AVM (e.g., 2022 Datacenter).
2. Specify
The specification document (spec.md) is used to define the baseline specification for the product, focusing on “the what and the why” rather than the low-level technical requirements. It’s detached from the implementation, meaning, the same spec can be used even if the underlying technology changes.
The specification describes WHAT you want to build and WHY - not how. It is focused on user needs, functional requirements, constraints, and success criteria.
Spec Kit uses /speckit.specify to generate the spec.md file. Specifications can be evolved through iterating over the spec.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.specify and leveraging /speckit.clarify to review and challenge the specification.
The specification typically includes:
Feature description
User/problem statements
Functional and non-functional requirements
Scenarios & their constraints
Input/output expectations
Success criteria
Following our scenario, here are some examples for what the prompt used to generate the specification should include:
What we are building
“A deployable IaC template, based on Azure Verified Modules, that provisions a secure single-VM environment suitable for hosting a legacy Windows Server-based line-of-business application.”
Functional Requirements
Deploy all Azure resources through referencing the corresponding AVM module (if available).
Expose the application through an internal load balancer (if needed).
Non-Functional Requirements
Must support repeatable deployments across environments (dev/test/prod).
Must comply with corporate security baselines.
Constraints
Legacy application cannot be containerized.
Only one VM instance supported.
No direct internet access allowed.
User Inputs
VM size, OS license type, admin credentials (via Key Vault), virtual network ranges.
Success Criteria
VM deploys successfully and application runs.
Diagnostics logs are set to be collected.
Deployment is fully reproducible and parameterized.
3. Clarify (Optional)
The clarify step is used to identify missing information, ambiguity, contradictions, or incompleteness in the specification. It runs a structured Q&A loop where the AI agent asks questions derived from the spec and your constitution, ensuring high-quality requirements before planning. This step is crucial when the initial specification is incomplete or ambiguous - which is common for infra projects.
Spec Kit uses /speckit.clarify to generate adjust information captured in spec.md. The prompt doesn’t require any specific inputs as it analyzes the existing specification for gaps.
4. Plan
This step is where the technical requirements for the project are defined. Spec Kit consults the constitution to ensure that the non-negotiable principles are respected. The plan turns the specification into a technical architecture and concrete design. It defines how the system will be built - including technical stack and architecture choices. It also outlines the execution flow, primary dependencies, testing approaches, target platforms, and architecture principles.
Spec Kit uses /speckit.plan to generate the plan.md file. The plan can be evolved through iterating over the plan.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.plan, or leveraging /speckit.checklist to review/validate and challenge the plan.
The plan typically includes:
Selected technical stack & components
Architecture diagram or description
Component-level (resource-level) breakdown
API/data contracts (if any)
Integration points
Deployment structure
Region & SKU validation
Required research (limitations, assumptions)
Following our scenario, here are some examples for what the prompt used to generate the plan should include:
Chosen Technologies
AVM Bicep or Terraform modules
Architecture
Hub/spoke or simple VNet depending on environment.
Subnet for VM with NSG enforcing inbound/outbound rules.
Azure Bastion for private admin access.
VM uses Managed Identity for Key Vault + Storage access.
Research (automatically generated)
Supported Windows Server SKUs in chosen region.
VM extension support for custom script on Windows.
How to implement/deploy: Steps to deploy via Azure CLI, Bicep CLI, PowerShell or GitHub Actions.
5. Checklist (Optional)
The checklist step ensures that all required criteria from the Constitution, Spec, and Plan are met or properly addressed before generating tasks or implementing.
Spec Kit uses /speckit.checklist to generate adjustments to the plan.md file. The prompt doesn’t require any specific inputs as it analyzes the existing plan for gaps.
6. Tasks
This step breaks the project work down into manageable and actionable chunks that the agent can tackle one by one. Tasks are the blueprint for coding/automation. For example, a plan can be broken down to individual phases and tasks, such as bootstrapping, test first (tests must fail before core implementation), core implementation, integration refinement, and polish/iterate.
Spec Kit uses /speckit.tasks to generate the tasks.md file. The prompt doesn’t require any specific inputs as it analyzes the existing plan to break it down into actionable tasks.
Tasks typically include:
Ordered, granular, developer-ready instructions, mapping to a single logical unit
Acceptance criteria per task
Notes for dependencies between tasks
Following our scenario, here are some examples for what the prompt used to generate the tasks should include:
Solution Template Creation Tasks
Create base Bicep structure for the template.
Reference the AVM VNet module with parameterized address space.
Reference the AVM Subnet module and associate NSG.
Reference the AVM NSG module with rules (deny all inbound except required).
Reference the AVM VM module with parameters for:
VM size
OS SKU
Managed Identity
Boot diagnostics settings
Add VM Extension for custom script to install legacy application.
Security Tasks
Integrate Key Vault references for secrets.
Apply security baseline hardening script.
Observability Tasks
Add Log Analytics workspace and diagnostic settings.
Documentation Tasks
Generate README with deployment instructions.
Generate sample parameter files for dev/test/prod.
Testing Tasks
Write validation tests using What-If and PSRule for Azure.
Deploy to sandbox environment for verification.
7. Analyze (Optional)
The analyze step runs a final check for consistency, completeness, contradictions, and coverage across all generated artifacts - specification, plan, tasks - before implementation.
Spec Kit uses /speckit.analyze to generate an analysis report. The prompt doesn’t require any specific inputs as it analyzes the existing spec, plan and tasks to produce the report.
8. Implement
The implementation step is the final stage where Spec Kit executes all tasks, building the actual software solution by generating real code, scripts, documentation, tests, and supporting assets. The implementation strictly adheres to the guidelines and requirements set forth in the earlier stages (constitution, specification, plan, and tasks) to ensure consistency, quality, and alignment with the project’s goals.
Spec Kit uses /speckit.implement to implement all defined tasks by generating all code. The prompt doesn’t require any specific inputs as Spec Kit analyzes the existing plan and tasks to perform this step.
Following our scenario, here are some examples for what the output of the implementation step should include. Note that GitHub Copilot can actually deploy the generated main.bicep file to Azure, and validate whether the deployment was successful.
Generated Code and Files
Bicep template (e.g., main.bicep)
Parameter file(s) (e.g., main.bicepparam)
Deployment scripts (if required)
Any additionally required configuration files
Test Artifacts
Unit tests, integration tests, IaC linting results
What-If validation JSON
PSRule for Azure test configs
Regression tests (if in constitution)
Documentation
README files
Architecture diagrams
Quick-start and deployment instructions
Known limitations and future improvements
Tooling Outputs
Auto-created scaffolding (directories and files)
Code generation aligned to constraints
Summary
Spec Kit transforms the traditionally ambiguous process of translating requirements into code by establishing a structured, AI-assisted workflow. By following the steps - from Constitution through Implementation - you create a clear chain of traceability where every line of code can be linked back to a specific requirement.
Key takeaways:
Start with principles: The constitution ensures that non-negotiable constraints (security, compliance, architecture patterns) are embedded from the beginning.
Iterate on specifications: Use the clarify step to challenge assumptions and refine requirements before committing to implementation.
Plan before coding: A well-defined plan prevents costly rework and ensures alignment with AVM best practices.
Break down complexity: Tasks make large projects manageable and provide clear acceptance criteria for each unit of work.
Validate continuously: Use analyze and checklist steps to catch inconsistencies early in the process.
When combined with Azure Verified Modules, Spec Kit helps ensure that your infrastructure-as-code solutions are not only functional but also secure, maintainable, and aligned with Azure best practices.
For hands-on examples of using Spec Kit with AVM, see the Bicep Example guide.
Subsections of Spec Kit
AVM Example for Spec Kit
Experimental Content
The content in this section represents experimental exploration of emerging technologies and innovative approaches. To learn more about our experimental content and its implications, please refer to the Experimental Section Overview.
Prerequisites
You will need the following tools and components to complete this guide:
Terraform MCP Server to boost the use of Azure Verified Modules (AVM) in Terraform.
Before you begin, make sure you have these tools installed in your development environment!
Solution Architecture
Before we begin coding, it is important to have details about what the infrastructure architecture will include. For our example, using AVM modules, we will be building a solution that will host a legacy business application running as a single Windows Server 2016 virtual machine (VM) with at least 2 CPU cores, 8GB RAM, Standard HDD OS disk, and a 500GB data disk.
The VM is accessible via Azure Bastion using secure RDP access (no public IP exposure). The solution needs an Azure Storage Account with an HDD-backed file share connected via private endpoint, and an Azure Key Vault to securely store the VM administrator password generated at deployment time. The VM must not be accessible from the internet, and all diagnostic logs will be captured in a Log Analytics workspace with critical alerts configured for VM availability, disk utilization, and Key Vault access failures.
Bootstrapping
Tip
On a Windows PC, to get the uv package manager CLI tool required for locally installing the Specify CLI, run the following command:
winget install astral-sh.uv
To install Spec Kit locally, run the following command in an elevated terminal:
Create a new directory for your Spec Kit project and navigate into it - this folder ideally already exists as a git repository:
mkdir avm-workload
cd avm-workload
Set your default branch to main (initializing Spec Kit will configure this working folder as a git repository if it isn’t one already):
git config --global init.defaultBranch main
Initialize a new Spec Kit project:
specify init .
If the folder has already been set up as a repository, the specify tool will warn you that the folder is not empty. Just confirm that you want to proceed.
As we haven’t defined the AI assistant in our init command, specify will prompt us to choose one. Select copilot (GitHub Copilot) from the list. Similarly, as we haven’t defined the script type, specify will prompt us to choose one. Select ps (PowerShell) from the list.
Alternatively, you can provide these parameters directly in the init command, like so:
specify init . --ai copilot --script ps
β Expand to see the results
Note: As Spec Kit evolves, the output may change over time. This example is meant to give you an idea of what the user interface looks like.
Click through the tabs to see the details!
You should see something like this:
In your project folder, you should now see the following files and folders created by the specify tool:
Spec Kit automatically commits this step to the git repository with following comment: Initial commit from Specify template.
The rest of the steps will be performed using GitHub Copilot Chat in VS Code: Start your VS Code environment, open or add the newly created folder to your workspace, and navigate to GitHub Copilot Chat using the dialog icon on the top of the window or by hitting CTRL+ALT+I.
Making it real
Spec Kit follows a structured workflow that guides you through each phase of solution development, from establishing foundational principles to implementing the final code. To learn more about Spec Kit, see the Spec Kit overview section.
flowchart LR
A[1\. Constitution] --> B[2\. Specify]
B --> C["3\. Clarify<br>(Optional)"]
C --> D[4\. Plan]
D --> E["5\. Checklist<br>(Optional)"]
E --> F[6\. Tasks]
F --> G["7\. Analyze<br>(Optional)"]
G --> H[8\. Implement]
click A "#1-constitution"
click B "#2-specify"
click C "#3-clarify-optional"
click D "#4-plan"
click E "#5checklist-optional"
click F "#6-tasks"
click G "#7-analyze-optional"
click H "#8-implement"
style C fill:#e1f5ff
style E fill:#e1f5ff
style G fill:#e1f5ff
To implement our example solution using AVM modules, we will walk through each of these steps in detail.
Each of the below steps will typically take 3-8 minutes to complete, depending on the complexity of your specification, the performance of the AI model you are using, and your reaction time to answer any outstanding questions and review and approve the generated content.
Choose your LLM
Changing the LLM does make a difference. We highly encourage you test different models to see which one works best for your needs.
Note: At the time of writing this article, we tested our prompts with Claude Sonnet 4.5 for Bicep and Claude Sonnet 4.6 for Terraform. In our experience, using Claude Opus 4.6 for Terraform typically leads to better, more accurate results, but also costs more tokens.
Know before you go
As Spec Kit uses a set of built-in and system tools and scripts, you will need to approve the execution of each of these steps. Make sure you understand the impact of these commands before approving and proceeding! Here’s an example:
In some cases, your account might exceed GitHub’s API rate limits when using GitHub Copilot with Spec Kit. If that happens, please wait for a while (usually an hour or so) and try again.
1. Constitution
Spec Kit uses /speckit.constitution to generate the constitution.md file. The constitution can be evolved through iterating over the constitution.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.constitution.
Info
To learn more about what the constitution should include, see the Constitution chapter in the Spec Kit article.
β Before running /speckit.constitution (Expand)
Notice what the constitution.md file looks like before running the related prompt. It is just a template with placeholders, defining the structure:
Note: As Spec Kit evolves, the content of this template may change over time. This example is meant to give you an idea of what the starting point looks like.
<!-- markdownlint-disable --># [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args β stdout, errors β stderr; Support JSON + human-readable formats -->### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written β User approved β Tests fail β Then implement; Red-Green-Refactor cycle strictly enforced -->### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
Run the following prompt to generate the constitution for our example:
/speckit.constitution Fill the constitution with the typical requirements of a legacy Azure workload (needed to be retained for compliance reasons; no high-availability requirements; no disaster recovery requirements; no scalability requirements), defined as infrastructure-as-code, in Bicep language, built only with Azure Verified Modules (AVM). Always try to implement every feature with Bicep first (using Infra-as-code), and only use custom scripts when it's not possible otherwise. Follow IaC best practices: define everything in a single template, and let ARM manage dependencies and the order of deployment for each Azure resource.
Security and reliability best practices must be followed under all circumstances.
The naming convention is to use just enough random characters to make the name unique and have the Azure resource type reflected in the name. Resource type specific character and length limitations must be respected.
Before running a deployment, always run a validation.
Deploy everything to the US West 3 datacenter region.
β Expand to see the results
The most important artifact created in this phase is the constitution.md file. Based on your inputs, additional files may also be created or updated, such as spec-template.md , plan-template.md, and tasks-template.md. These would further improve the quality of the generated artifacts in later phases.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
Once Copilot finished running the prompt, you should see something like this in the Copilot chat area:
In the constitution.md file, notice, how changes implemented by Copilot are not final yet, until you review, and approve them by clicking on the “Keep” button. You can either do this on a paragraph-by-paragraph basis, or for the entire document at once by clicking on the “Keep” button in the main Copilot chat window.:
<!-- markdownlint-disable --><!--
SYNC IMPACT REPORT
==================
Version Change: N/A β 1.0.0 (Initial constitution ratification)
Modified Principles:
-N/A (Initial version)
Added Sections:
-Core Principles (6 principles defined)
-Infrastructure Standards
-Security & Compliance Requirements
-Development Workflow
-Governance
Removed Sections:
-N/A (Initial version)
Templates Requiring Updates:
-β plan-template.md: Constitution Check section aligns with principles
-β spec-template.md: Requirements structure aligns with security principles
-β tasks-template.md: Task categorization aligns with validation-first workflow
Follow-up TODOs:
-None (all placeholders filled)
Change Rationale:
-MAJOR version (1.0.0) because this is the initial constitution establishing governance framework
-Principles focused on legacy workload characteristics: compliance retention, IaC-first with Bicep, AVM-only modules, validation-before-deployment
--># Legacy Azure Workload Constitution
## Core Principles
### I. Infrastructure-as-Code First (NON-NEGOTIABLE)
All Azure resources MUST be defined in Bicep templates. Manual Azure Portal configurations are STRICTLY PROHIBITED.
**Rationale**: Ensures compliance auditability, repeatability, and version control for regulatory requirements. Manual changes create configuration drift that violates compliance mandates.
**Rules**:
- Every feature starts with Bicep code defining the infrastructure
- Custom scripts are permitted ONLY when Bicep/ARM capabilities are insufficient
- All infrastructure changes MUST go through version control
- Single-template approach: define everything in one main.bicep, let ARM handle dependencies
### II. AVM-Only Modules
All Bicep infrastructure MUST use Azure Verified Modules (AVM). Direct resource declarations are permitted only when no AVM module exists.
**Rationale**: AVM modules are officially maintained, follow security best practices, and are compliance-tested by Microsoft.
**Rules**:
- Search for AVM module first (using `#list_avm_metadata` tool)
- Use latest stable version of AVM modules
- Document justification when direct resource declaration is necessary
- Follow AVM module documentation for parameter configuration
### III. Validation Before Deployment (NON-NEGOTIABLE)
Every deployment MUST be preceded by ARM validation. Deployments without prior validation are STRICTLY PROHIBITED.
**Rationale**: Prevents configuration errors that could impact compliance-required systems. Validation catches issues before they affect production.
**Rules**:
- Run `az deployment group validate` before every deployment
- Run `az deployment group what-if` to preview changes
- Document validation results in deployment logs
- Address all validation errors before proceeding
### IV. Security & Reliability First
Security and reliability best practices MUST be followed under all circumstances, even for legacy workloads.
**Rationale**: Compliance requirements mandate security controls regardless of workload age. Legacy status does not exempt from security obligations.
**Rules**:
- Enable Azure Monitor and diagnostic logs for all resources
- Apply network security groups and private endpoints where applicable
- Use managed identities instead of connection strings/keys
- Follow principle of least privilege for all access
- Enable Azure Security Center recommendations
### V. Minimal Naming with Type Identification
Resource names MUST be concise: minimal random characters for uniqueness + resource type identifier.
**Rationale**: Improves resource identification while respecting Azure naming limitations. Avoids verbose names that exceed character limits.
**Rules**:
- Format: `{resourceType}-{purpose}-{randomSuffix}`- Example: `st-legacyvm-k7m3p` for storage account
- Respect Azure resource-specific length limits (e.g., storage: 24 chars, lowercase/numbers only)
- Random suffix: 4-6 alphanumeric characters
- Document naming pattern in infrastructure documentation
### VI. Region Standardization
All resources MUST deploy to US West 3 (westus3) region unless technically impossible.
**Rationale**: Centralizes resources for simplified management and cost tracking. Reduces complexity for legacy workloads with no multi-region requirements.
**Rules**:
- Default region parameter: `westus3`- Document exceptions with technical justification
- Global resources (e.g., Azure Front Door) exempted by nature
## Infrastructure Standards
### Bicep Template Requirements
- Single main.bicep file as deployment entry point
- Use main.bicepparam for environment-specific parameters
- Leverage ARM dependency management (avoid explicit dependsOn unless necessary)
- Include detailed parameter descriptions and constraints
- Use Bicep decorators for validation (`@minLength`, `@maxLength`, `@allowed`)
### Module Management
- Reference AVM modules via Bicep Registry (br/public:avm/...)
- Pin to specific module versions (never use 'latest')
- Document module selection rationale in comments
- Review AVM module documentation for breaking changes during updates
### Documentation Requirements
- Maintain README.md with deployment instructions
- Document all parameters in main.bicepparam
- Include architecture diagram showing resource relationships
- Record compliance justifications for resource configurations
## Security & Compliance Requirements
### Mandatory Controls
- **Logging**: Enable diagnostic settings for all resources supporting it
- **Access Control**: Use Azure RBAC, no shared keys in parameters
- **Network Security**: Apply NSGs to subnet/NIC resources
- **Encryption**: Use Azure-managed encryption (minimum); customer-managed keys where compliance requires
- **Secrets Management**: Store sensitive values in Azure Key Vault, reference via Bicep getSecret()
### Compliance Documentation
- Tag all resources with compliance identifiers (e.g., `compliance: "legacy-retention"`)
- Document retention policies for data resources
- Record security exceptions with business justification
- Maintain audit trail of all infrastructure changes
### Prohibited Practices
- Hardcoded secrets or connection strings in Bicep files
- Public IP addresses without business justification
- Unrestricted network access (0.0.0.0/0 rules)
- Disabled diagnostic logging
## Development Workflow
### Pre-Deployment Phase
1. Research and select appropriate AVM modules
2. Draft Bicep templates with parameter documentation
3. Run local Bicep linting (`bicep build`)
4. Commit code to version control
### Validation Phase (MANDATORY GATE)
1. Run `az deployment group validate` and resolve all errors
2. Run `az deployment group what-if` and review changes
3. Document validation results
4. Obtain approval for resource changes (if required by organization)
### Deployment Phase
1. Deploy using validated parameters
2. Monitor deployment progress
3. Verify resource creation via Azure Portal/CLI
4. Test resource functionality
5. Document deployment outcomes
### Post-Deployment Phase
1. Verify diagnostic settings are active
2. Confirm tags applied correctly
3. Review security recommendations in Azure Security Center
4. Update documentation with deployed resource details
## Governance
This constitution supersedes all other development practices and guidelines. All infrastructure changes MUST comply with these principles.
### Amendment Process
1. Propose amendment with business/technical justification
2. Document impact on existing infrastructure
3. Update constitution with version increment following semantic versioning
4. Update all dependent templates and documentation
5. Communicate changes to all stakeholders
### Versioning Policy
- **MAJOR**: Breaking changes to core principles (e.g., removing AVM-only requirement)
- **MINOR**: New principle added or existing principle materially expanded
- **PATCH**: Clarifications, wording improvements, non-semantic fixes
### Compliance Review
All pull requests MUST verify compliance with this constitution. Constitution violations require explicit justification and approval exception.
Complexity that deviates from simplicity principles MUST be documented and justified with business or technical rationale.
**Version**: 1.0.0 | **Ratified**: 2026-01-27 | **Last Amended**: 2026-01-27
/speckit.constitution Fill the constitution with the typical requirements of a legacy Azure workload (needed to be retained for compliance reasons; no high-availability requirements; no disaster recovery requirements; no scalability requirements), defined as infrastructure-as-code, in Terraform language, built only with Azure Verified Modules (AVM). Always use Terraform, and never use custom scripts. Security and reliability best practices must be followed under all circumstances. Before running a deployment, always run a validation. Deploy everything to the US West 3 datacenter region.
β Expand to see the results
The most important artifact created in this phase is the constitution.md file. Based on your inputs, additional files may also be created or updated, such as spec-template.md , plan-template.md, and tasks-template.md. These would further improve the quality of the generated artifacts in later phases.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
Once Copilot finished running the prompt, you should see something like this in the Copilot chat area:
In the constitution.md file, notice, how changes implemented by Copilot are not final yet, until you review, and approve them by clicking on the “Keep” button. You can either do this on a paragraph-by-paragraph basis, or for the entire document at once by clicking on the “Keep” button in the main Copilot chat window.:
<!-- markdownlint-disable --><!--
Sync Impact Report - Version 1.0.0 (Initial Release)
Version: N/A β 1.0.0 (MAJOR - Initial constitution establishment)
Change Type: Initial Release
Principles Defined:
β I. Terraform-First Infrastructure
β II. AVM-Only Modules (Terraform Registry)
β III. Security & Reliability (NON-NEGOTIABLE)
β IV. Single-Template Pattern (Terraform root module)
β V. Validation-First Deployment (terraform validate + plan)
Sections Added:
β Deployment Standards
β Project Constraints
β Naming Convention
Templates Status:
β plan-template.md - Update Constitution Check for Terraform workflow (init β validate β plan β apply)
β spec-template.md - Update infrastructure requirements for .tf file patterns and state management
β tasks-template.md - Update task patterns for Terraform validation, AVM module sourcing, and security scanning
Follow-up Actions:
-Update plan-template.md Technical Context to include Terraform version and required providers
-Ensure spec-template.md reflects Terraform state management and backend configuration requirements
-Update tasks-template.md to include terraform init, validate, fmt, plan task patterns
-Add Terraform-specific linting (tflint, tfsec, checkov) to setup phase tasks
-Document Terraform backend configuration (Azure Storage for remote state) in project README
-Add .terraform, .tfstate, .tfvars patterns to .gitignore
--># Azure Verified Modules Legacy Workload Constitution
## Core Principles
### I. Terraform-First Infrastructure
Every Azure resource MUST be defined as Infrastructure-as-Code in Terraform configuration files before any alternative approach is considered. Custom scripts (PowerShell, Azure CLI, Bash) are permitted ONLY when Terraform providers cannot accomplish the requirement.
**Rationale**: Declarative infrastructure ensures repeatability, version control, audit trails, and compliance documentation. Terraform's state management provides idempotent operations and built-in dependency resolution through resource graph analysis.
**Requirements**:
- All Azure resources declared in Terraform `.tf` files in project root or modules
- Single root module paradigm - let Terraform manage orchestration and dependencies via implicit resource references
- Custom scripts require explicit justification documenting why neither an AVM module nor AzAPI can solve the need; AzureRM is not a fallback
- All infrastructure changes tracked in version control
- Terraform state stored remotely in Azure Storage Account with state locking enabled (blob container + lease)
- Use Terraform workspaces or separate state files for environment separation (dev, prod)
-`.terraform/`, `*.tfstate`, `*.tfstate.backup`, `*.tfvars` (except example files) excluded from version control
### II. AVM-Only Modules
All Terraform modules MUST be sourced exclusively from Azure Verified Modules (AVM) for Terraform. No custom or third-party Terraform modules are permitted unless an AVM module does not exist for the required resource type.
**Rationale**: AVM Terraform modules are Microsoft-maintained, tested against Azure best practices, include security hardening, follow consistent interfaces, and receive ongoing updates for provider changes and new Azure features.
**Requirements**:
- Use AVM resource modules (`Azure/avm-res-*`) from Terraform Registry for all supported Azure resources
- Use AVM pattern modules (`Azure/avm-ptn-*`) from Terraform Registry for multi-resource patterns
- Reference modules from official Terraform Registry source: `registry.terraform.io/Azure/avm-*`- Pin module versions explicitly using pessimistic constraint (e.g., `version = "~> 0.1.0"`) - no floating latest versions
- If AVM module unavailable, document gap in ADR (Architecture Decision Record) and follow AVM authoring standards for local module
- Review and update AVM module versions quarterly minimum - document breaking changes in release notes review
**Example AVM Module Reference**:
```hcl
module"storage_account" {
source ="Azure/avm-res-storage-storageaccount/azurerm" version ="~> 0.1.0" # Module inputs per AVM interface
}
```### III. Security & Reliability (NON-NEGOTIABLE)
Security and reliability best practices MUST be followed under all circumstances. This principle supersedes convenience, development velocity, and cost optimization.
**Rationale**: Legacy workloads retained for compliance reasons carry regulatory and legal obligations. Security breaches or reliability failures create compliance violations with potential legal ramifications.
**Requirements**:
- Managed identities required - no service principal credentials in Terraform code or variable files
- All secrets stored in Azure Key Vault - no plaintext secrets in `.tf`, `.tfvars`, or state files
- Use `sensitive = true` attribute for all secret outputs and variables
- Network security groups (NSGs) with explicit deny-by-default rules
- Azure Policy compliance validated before deployment (`terraform plan` must show policy compliance)
- Diagnostic settings and logging enabled on all supported resources (Activity Logs, Resource Logs)
- Resource locks (`CanNotDelete`) applied to prevent accidental deletion of compliance-critical resources
- Encryption at rest enabled (Microsoft-managed or customer-managed keys as appropriate)
- TLS 1.2+ required for all network communication (enforce via Azure Policy or resource properties)
- Principle of least privilege for all RBAC assignments (use built-in roles, no custom roles without justification)
- Static security analysis with `tfsec` or `checkov` in CI/CD pipeline - HIGH/CRITICAL findings block merge
- No hardcoded resource IDs or subscription IDs - use `data` sources or variables
### IV. Single-Template Pattern
All infrastructure for the workload MUST be defined in a single Terraform root module with Terraform managing dependencies and deployment order. Multi-stage deployments are permitted only when Terraform constraints (circular dependencies, provider limitations) make single-root infeasible.
**Rationale**: Single root module ensures atomic deployment, eliminates manual orchestration errors, simplifies rollback, and provides complete infrastructure visibility in one artifact. Terraform's dependency graph automatically determines execution order.
**Requirements**:
- One root module with `main.tf`, `variables.tf`, `outputs.tf`, and `versions.tf` (or combined files by preference)
- Use `depends_on` sparingly - rely on Terraform implicit dependency resolution via resource attribute references
- Child module composition for organizational clarity - all child modules instantiated in root module
- Separate `.tfvars` files for environment-specific values (e.g., `dev.tfvars`, `prod.tfvars`)
- If multi-stage required, document Terraform limitation necessitating split (rare - most circular dependencies solvable with proper design)
- No imperative orchestration scripts chaining multiple `terraform apply` commands
**Example Root Module Structure**:
```
terraform/
βββ main.tf # Primary resource declarations and module calls
βββ variables.tf # Input variable definitions
βββ outputs.tf # Output value definitions
βββ versions.tf # Terraform and provider version constraints
βββ backend.tf # Remote state backend configuration
βββ dev.tfvars # Development environment values
βββ prod.tfvars # Production environment values
βββ modules/ # Local child modules (only if AVM unavailable)
βββ custom/
```### V. Validation-First Deployment
Every deployment MUST execute Terraform validation (`terraform validate`) and plan review (`terraform plan`) before actual apply. Deployments without successful validation and plan approval are prohibited.
**Rationale**: Validation catches syntax errors, type mismatches, and configuration issues. Plan preview catches logical errors, permission issues, policy violations, and unintended changes, preventing destructive actions and partial deployments.
**Requirements**:
-`terraform init` executed to initialize providers and backend
-`terraform fmt -check` executed to enforce code formatting (must pass before deployment)
-`terraform validate` executed and must return success before plan
-`terraform plan -out=plan.tfplan` executed for every deployment - output must be reviewed and approved
- Plan shows no unexpected resource deletions or replacements (unless explicitly intended and documented)
- Validation failures or unexpected plan changes block deployment pipeline - no manual override without incident review
- Plan file (`plan.tfplan`) stored as artifact in CI/CD for audit trail (encrypted if sensitive data present)
- Apply MUST use plan file: `terraform apply plan.tfplan` (no ad-hoc apply without plan)
- Plan diff documented in deployment logs for compliance audit trail
**Deployment Workflow**:
1.`terraform init -backend-config=backend-prod.hcl`2.`terraform fmt -check -recursive`3.`terraform validate`4.`terraform plan -var-file=prod.tfvars -out=plan.tfplan`5.**GATE**: Human review and approval of plan output
6.`terraform apply plan.tfplan`## Deployment Standards
### Region & Availability
- **Target Region**: US West 3 (`westus3`) for all resources
- **High Availability**: Not required (legacy workload, compliance retention only)
- **Disaster Recovery**: Not required
- **Scalability**: Not required (fixed capacity sufficient)
**Rationale**: This is a legacy workload retained for compliance and legal record-keeping. Active user workloads have migrated to modern platforms. Fixed-region, single-instance deployments are appropriate and cost-effective.
**Terraform Implementation**:
- Use `location = "westus3"` for all resources (or variable `var.location` with default `"westus3"`)
- No zone redundancy, geo-replication, or auto-scaling configurations
- Accept default SKUs optimized for cost over high availability (e.g., Standard vs Premium)
### Naming Convention
Resource names MUST follow this pattern: `<resourceTypeAbbreviation>-<workloadName>-<randomSuffix>`**Requirements**:
- Resource type abbreviation per [Azure naming best practices](https://learn.microsoft.com/azure/cloud-adoption-framework/ready/azure-best-practices/resource-abbreviations) (e.g., `st` for Storage Account, `kv` for Key Vault, `vm` for Virtual Machine)
- Workload name: `avmlegacy` (or feature-specific descriptor)
- Random suffix: minimum characters needed for global uniqueness (e.g., 6-character alphanumeric generated via `random_string` resource)
- Respect Azure resource type character limits and restrictions:
- Storage Account: 24 chars max, lowercase alphanumeric only, globally unique
- Key Vault: 3-24 chars, alphanumeric and hyphens, globally unique
- Resource Group: 1-90 chars, alphanumeric, underscores, hyphens, periods
- Use Terraform `random_string` or `random_id` resource to generate suffix consistently across deployments
- Document abbreviations in README or add comments in code
**Terraform Implementation Example**:
```hcl
resource"random_string" "unique_suffix" {
length =6 special =false upper =false}
locals {
workload_name ="avmlegacy" location_abbr ="wus3" # westus3 abbreviation
# Resource names following convention
storage_account_name ="st${local.workload_name}${random_string.unique_suffix.result}" # max 24 chars
key_vault_name ="kv-${local.workload_name}-${random_string.unique_suffix.result}" resource_group_name ="rg-${local.workload_name}-${local.location_abbr}"}
module"resource_group" {
source ="Azure/avm-res-resources-resourcegroup/azurerm" version ="~> 0.2" name =local.resource_group_name location ="westus3"}
```**Examples**:
-`stavmlegacy8k3m9x` (Storage Account - 18 chars)
-`kv-avmlegacy-8k3m9x` (Key Vault - 20 chars)
-`rg-avmlegacy-wus3` (Resource Group)
-`vm-avmlegacy-001` (Virtual Machine - numeric suffix for multiple instances)
## Project Constraints
### Legacy Workload Context
This infrastructure supports a **legacy Azure workload** retained exclusively for compliance, regulatory, and legal record-keeping purposes. Active business operations have migrated off this system.
**Implications**:
- Cost optimization prioritized (single instances, no redundancy beyond Azure platform defaults)
- Change frequency low (quarterly patches and security updates only)
- User activity minimal (compliance audits, occasional data retrieval by legal/audit teams)
- Retention period defined by legal/compliance requirements (document separately in project README or ADR)
- Decommissioning planned when retention period expires (add sunset date if known)
**Terraform Impact**:
- Use smaller SKUs and tiers (Standard vs Premium) where compliance allows
- No auto-scaling configurations needed
- Simplified networking (single VNet, minimal subnets)
- Backup retention aligned with compliance requirements (not business continuity requirements)
### Non-Functional Requirements
- **Performance**: Adequate for infrequent access (no SLA requirements, no performance testing needed)
- **Availability**: Standard Azure platform availability (no custom HA configurations, 99.9% acceptable)
- **Capacity**: Fixed sizing (no auto-scaling, no capacity planning for growth)
- **Compliance**: MUST maintain audit logs (Azure Monitor Logs minimum 90 days), access controls (RBAC), data integrity (checksums, immutability where required)
- **Cost**: Target <$X/month (specify budget if known) - optimize for minimal operational cost
- **Maintenance Window**: Changes allowed during business hours (no 24/7 operations requirement)
## Governance
This constitution is the ultimate authority for all infrastructure decisions, architecture choices, and development practices for this workload. All team members, code reviews, and deployment pipelines MUST verify compliance.
### Amendment Process
1. Proposed changes documented with rationale and impact analysis (create ADR in `docs/decisions/` if significant)
2. Review by infrastructure lead and compliance officer
3. Approval required before amendment merge
4. Version incremented per semantic versioning:
- **MAJOR**: Principle removal, redefinition, or backward-incompatible governance changes (e.g., switching IaC tools)
- **MINOR**: New principle added or materially expanded guidance (e.g., adding new security requirement)
- **PATCH**: Clarifications, corrections, non-semantic improvements (e.g., fixing typos, adding examples)
5. Migration plan required for MAJOR/MINOR changes affecting existing infrastructure (document in amendment PR)
6. All dependent templates and documentation updated atomically with constitution
### Compliance Review
- All pull requests MUST include constitution compliance checklist (see `.github/PULL_REQUEST_TEMPLATE.md`)
- Deployment pipelines MUST validate against principles where automatable:
- Terraform fmt check (Principle I)
- AVM module source validation (Principle II)
- tfsec/checkov security scan (Principle III)
- Plan approval gate (Principle V)
- Quarterly compliance audit against all principles with findings documented in team wiki/issue tracker
- Violations require remediation plan within 30 days or justified exception with expiration date (document in issue)
### Compliance Checklist (for PRs):
- [ ] All resources defined in Terraform (Principle I)
- [ ] All modules sourced from AVM Terraform Registry (Principle II)
- [ ] Security requirements met: managed identities, Key Vault, NSGs, logging (Principle III)
- [ ] Single root module pattern followed (Principle IV)
- [ ] Deployment includes terraform validate and plan review (Principle V)
- [ ] Naming convention followed (Deployment Standards)
- [ ] Resources deployed to westus3 region (Deployment Standards)
- [ ] No high-availability or disaster recovery features added unnecessarily (Project Constraints)
### Runtime Guidance
For day-to-day development guidance, coding standards, and tooling setup, refer to:
-`.specify/templates/` for specification and planning workflows
- Project `README.md` for Terraform setup, backend configuration, and deployment instructions
-`docs/` directory for additional Terraform patterns, troubleshooting, and Azure-specific guidance
**Version**: 1.0.0 | **Ratified**: 2026-02-18 | **Last Amended**: 2026-02-18
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture the new constitution of your project, with a comment of something like Constitution added.
2. Specify
Spec Kit uses /speckit.specify to generate the spec.md file. Specifications can be evolved through iterating over the spec.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.specify and leveraging /speckit.clarify to review and challenge the specification.
Info
To learn more about what the specification should include, see the Specification chapter in the Spec Kit article.
Run the following prompt to generate the specification for our example:
/speckit.specify Create specification, called "01-my-legacy-workload" for a legacy business application, running as a single virtual machine connected to a virtual network. The VM must run Windows Server 2016, needs to have at least 2 CPU cores, 8 GB of RAM, a standard HDD, and a 500 GB HDD-based data disk attached. It must be remotely accessible via a bastion host and needs to have access to an HDD-backed file share in a storage account connected via a private endpoint. The VM must access the internet via a NAT gateway. Network Security Groups (NSGs) must be created for each subnet, configured and assigned as applicable, restricting traffic to only what's necessary. VM subnet NSG must allow inbound RDP (port 3389) from Bastion subnet to enable bastion connectivity.
The VM's administrator password (created at the time of deployment) must be stored in a Key Vault, also deployed as part of this solution. The VM's administrator account must be called "vmadmin". The VM's computer name (netbios name) must be 15 or fewer characters long.
Always rely on parameters from the main.bicepparam file only. Have the name of the secret used for the admin password captured as a parameter. Include rich comments in both the main.bicep and main.bicepparam files to explain the purpose of each resource and parameter.
When a decision needs to be made on availability zones, always choose a number between 1 and 3 (never choose -1, that explicitly disables this feature).
Create everything in a single resource group, standing for a production environment. Do not create any additional environments (such as dev, test, staging, etc.).
Read the documentation (readme.md file) of each module you need to use to find out what parameters and complex parameter objects you can use. Don't guess the allowed parameters.
The VM must not be accessible from the internet and its logs should be captured in Log Analytics, included with the solution. Configure diagnostic logging plus critical-only alerts (VM stopped, disk full, Key Vault access failures).
β Expand to see the results
Notice that the execution of the /speckit.specify created a new file called requirements.md and a file called spec.md in the specs/001-legacy-vm-workload/ folder.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
Once Copilot finished running the prompt, you should see something like this in the Copilot chat area:
<!-- markdownlint-disable --># Specification Quality Checklist: Legacy VM Workload Infrastructure
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-01-27
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Validation Results
**Status**: β PASSED - All checklist items completed successfully
**Validation Date**: 2026-01-27
**Details**:
- Specification includes 5 user stories, properly prioritized (P1-P3)
- 16 functional requirements defined with concrete Azure resources
- 8 security & compliance requirements aligned with constitution
- 6 infrastructure constraints following project standards
- 5 monitoring & alerting requirements for operational visibility
- 11 success criteria, all measurable and deployment-focused
- Edge cases identified (6 scenarios)
- Assumptions documented (13 items)
- Out of scope clearly defined (13 items)
- No [NEEDS CLARIFICATION] markers - all requirements are concrete and actionable
**Readiness**: β Specification is ready for `/speckit.plan` phase
<!-- markdownlint-disable --># Feature Specification: Legacy VM Workload Infrastructure
**Feature Branch**: `001-legacy-vm-workload`**Created**: 2026-01-27
**Status**: Draft
**Input**: User description: "legacy business application, running as a single virtual machine connected to a virtual network with Windows Server 2016, 2 CPU cores, 8 GB RAM, standard HDD, 500 GB data disk, bastion access, file share via private endpoint, NAT gateway internet access, NSGs, Key Vault for VM password, Log Analytics with diagnostic logging and critical alerts"
## User Scenarios & Testing *(mandatory)*
<!--
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
you should still have a viable MVP (Minimum Viable Product) that delivers value.
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
Think of each story as a standalone slice of functionality that can be:
-Developed independently
-Tested independently
-Deployed independently
-Demonstrated to users independently
-->### User Story 1 - Core VM Infrastructure Deployment (Priority: P1)
Deploy the fundamental infrastructure including virtual network, VM with required specifications, and basic connectivity. This establishes the baseline workload environment.
**Why this priority**: Without the VM and network infrastructure, no other components can function. This is the foundation for the entire workload.
**Independent Test**: Can be fully tested by deploying the infrastructure and verifying VM is created with correct specifications (Windows Server 2016, 2 cores, 8GB RAM, standard HDD) and can communicate within the VNet.
**Acceptance Scenarios**:
1.**Given** no existing infrastructure, **When** deployment is executed, **Then** VM is created with Windows Server 2016, 2 CPU cores, 8GB RAM
2.**Given** deployment is complete, **When** checking VM configuration, **Then** VM has standard HDD OS disk and is placed in correct VNet
3.**Given** VM is deployed, **When** checking computer name, **Then** NetBIOS name is 15 characters or fewer
---
### User Story 2 - Secure Storage and Data Disk (Priority: P2)
Provision the 500GB data disk for the VM and configure the storage account with file share accessible via private endpoint. This provides the data storage layer for the application.
**Why this priority**: Data storage is critical for application functionality but depends on the VM infrastructure being in place first.
**Independent Test**: Can be tested by verifying the 500GB HDD data disk is attached to the VM and the file share is accessible from the VM through the private endpoint.
**Acceptance Scenarios**:
1.**Given** VM infrastructure exists, **When** data disk deployment executes, **Then** 500GB HDD-based managed disk is attached to the VM
2.**Given** storage account is deployed, **When** checking storage configuration, **Then** HDD-backed file share is created
3.**Given** private endpoint is deployed, **When** VM attempts to access file share, **Then** connection succeeds through private network without traversing internet
---
### User Story 3 - Secure Access and Secrets Management (Priority: P2)
Implement bastion host for secure remote access and Key Vault for storing the VM administrator password. This ensures secure access patterns for operations teams.
**Why this priority**: Secure access is essential for ongoing operations but the infrastructure must exist before access can be configured.
**Independent Test**: Can be tested by connecting to the VM through bastion host using credentials retrieved from Key Vault.
**Acceptance Scenarios**:
1.**Given** bastion and Key Vault are deployed, **When** VM administrator password is generated at deployment, **Then** password is stored in Key Vault secret
2.**Given** bastion host is deployed, **When** operator attempts to connect to VM, **Then** connection succeeds through bastion without public IP on VM
3.**Given** Key Vault access is configured, **When** retrieving VM password, **Then** secret can be accessed only by authorized identities
4.**Given** VM subnet NSG is configured, **When** bastion attempts RDP connection to VM, **Then** traffic is allowed through NSG rule (port 3389 from Bastion subnet)
---
### User Story 4 - Internet Connectivity and Network Security (Priority: P3)
Configure NAT gateway for outbound internet access and implement Network Security Groups for all subnets with least-privilege rules.
**Why this priority**: Network security controls are important but the workload can function for testing without full NSG configuration initially.
**Independent Test**: Can be tested by verifying VM can reach internet through NAT gateway and that NSG rules block unauthorized traffic.
**Acceptance Scenarios**:
1.**Given** NAT gateway is deployed, **When** VM initiates outbound internet connection, **Then** traffic routes through NAT gateway
2.**Given** NSGs are configured, **When** unauthorized traffic attempts to reach VM, **Then** traffic is blocked by NSG rules
3.**Given** NSGs are deployed, **When** checking subnet associations, **Then** each subnet has appropriate NSG assigned
---
### User Story 5 - Monitoring and Alerting (Priority: P3)
Deploy Log Analytics workspace, configure diagnostic settings for all resources, and set up critical alerts (VM stopped, disk full, Key Vault access failures).
**Why this priority**: Monitoring is important for operations but the workload can function without it. It provides operational visibility rather than core functionality.
**Independent Test**: Can be tested by verifying diagnostic logs are flowing to Log Analytics and triggering test scenarios that generate alerts.
**Acceptance Scenarios**:
1.**Given** Log Analytics workspace is deployed, **When** resources are created, **Then** diagnostic settings send logs to workspace
2.**Given** alerting is configured, **When** VM is stopped, **Then** critical alert is triggered
3.**Given** alerting is configured, **When** Key Vault access fails, **Then** critical alert is triggered
4.**Given** diagnostic logging is active, **When** querying Log Analytics, **Then** logs are available within 5 minutes
---
## Clarifications
### Session 2026-01-27
- Q: VNet address space and subnet sizing for VM, bastion, and private endpoint subnets? β A: VNet: 10.0.0.0/24, VM subnet: 10.0.0.0/27, Bastion subnet: 10.0.0.64/26, Private endpoint subnet: 10.0.0.128/27
- Q: Storage file share quota size? β A: 1024 GiB (1 TiB)
- Q: Disk space alert threshold percentage? β A: 85% full
- Q: Alert notification method for critical alerts? β A: Azure Portal notifications only
- Q: VM size SKU for 2 cores and 8GB RAM requirement? β A: Standard_D2s_v3
### Edge Cases
- What happens when VM computer name parameter would exceed 15 characters? (NetBIOS limit must be enforced)
- How does deployment handle when Key Vault secret name parameter is not provided or is invalid?
- What happens when storage account name would exceed 24 characters or contains invalid characters?
- How does system handle when no availability zone is specified for resources requiring zone selection?
- What happens when private endpoint deployment fails but storage account succeeds?
- How does deployment handle if bastion subnet already exists in the VNet from a previous deployment?
## Requirements *(mandatory)*
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right functional requirements.
-->### Functional Requirements
<!-- NOTE: "Standard HDD" refers to Azure Standard_LRS disk SKU (magnetic disk storage) -->- **FR-001**: Infrastructure MUST provision a Windows Server 2016 Virtual Machine with size Standard_D2s_v3 (2 vCPUs, 8 GiB RAM) using Standard HDD for OS disk
- **FR-002**: Infrastructure MUST attach a 500GB HDD-based managed disk to the VM as a data disk
- **FR-003**: Infrastructure MUST create Virtual Network with address space 10.0.0.0/24 containing three subnets: VM subnet (10.0.0.0/27), Bastion subnet (10.0.0.64/26), and private endpoint subnet (10.0.0.128/27)
- **FR-004**: Infrastructure MUST deploy Azure Bastion for secure remote access to the VM without public IP
- **FR-005**: Infrastructure MUST provision Storage Account with HDD-backed file share (1024 GiB quota) accessible via private endpoint
- **FR-006**: Infrastructure MUST deploy NAT Gateway for VM outbound internet connectivity
- **FR-007**: Infrastructure MUST create Network Security Groups for each subnet with least-privilege rules
- **FR-008**: Infrastructure MUST deploy Azure Key Vault to store VM administrator password
- **FR-009**: Infrastructure MUST set VM administrator account name to "vmadmin"
- **FR-010**: Infrastructure MUST ensure VM computer name (NetBIOS name) is 15 characters or fewer
- **FR-011**: Infrastructure MUST generate and store VM administrator password in Key Vault at deployment time
- **FR-012**: Infrastructure MUST accept Key Vault secret name as a parameter from main.bicepparam
- **FR-013**: Infrastructure MUST deploy all resources to a single resource group representing production environment
- **FR-014**: Infrastructure MUST select availability zone between 1-3 for zone-capable resources (never use -1)
- **FR-015**: Infrastructure MUST include rich comments in both main.bicep and main.bicepparam explaining resource purpose and parameters
- **FR-016**: Infrastructure MUST rely exclusively on parameters defined in main.bicepparam file
### Security & Compliance Requirements (Mandatory for all features)
- **SEC-001**: All resources MUST enable diagnostic settings and send logs to Log Analytics Workspace
- **SEC-002**: VM MUST use managed identity for Azure resource authentication (no connection strings/keys in configuration)
- **SEC-003**: Network Security Groups MUST restrict traffic to only necessary ports and protocols per subnet
- **SEC-003a**: VM subnet NSG MUST allow inbound RDP (port 3389) from Bastion subnet (10.0.0.64/26) to enable bastion connectivity
- **SEC-004**: All resources MUST be tagged with compliance identifier "legacy-retention"
- **SEC-005**: VM administrator password MUST be stored in Azure Key Vault, never in code or parameters
- **SEC-006**: VM MUST NOT have public IP address assigned (access only through bastion)
- **SEC-007**: Storage account file share MUST be accessible only through private endpoint, not public endpoint
- **SEC-008**: Key Vault MUST restrict access to only authorized identities using RBAC
### Infrastructure Constraints
- **IC-001**: MUST deploy to westus3 region (US West 3)
- **IC-002**: MUST use Azure Verified Modules (AVM) exclusively (read module readme.md for parameter documentation)
- **IC-003**: MUST validate deployment with `az deployment group validate` before applying
- **IC-004**: MUST run `az deployment group what-if` to preview changes
- **IC-005**: Resource names MUST follow pattern: {resourceType}-{purpose}-{random4-6chars}
- **IC-006**: MUST NOT create additional environments (dev, test, staging) - production only
### Monitoring & Alerting Requirements
- **MON-001**: Infrastructure MUST deploy Log Analytics workspace for centralized logging
- **MON-002**: Infrastructure MUST configure diagnostic logging for VM, Key Vault, Storage Account, and network resources
- **MON-003**: Infrastructure MUST create critical alert for VM stopped/deallocated condition (Portal notifications)
- **MON-004**: Infrastructure MUST create critical alert for disk space exceeding 85% threshold (Portal notifications)
- **MON-005**: Infrastructure MUST create critical alert for Key Vault access failures (Portal notifications)
### Key Azure Resources
- **Virtual Machine**: Windows Server 2016 VM with size Standard_D2s_v3 (2 vCPUs, 8 GiB RAM), Standard HDD OS disk, managed identity enabled
- **Managed Disk**: 500GB HDD-based data disk attached to VM
- **Virtual Network**: VNet with subnets for VM, bastion, and private endpoints
- **Azure Bastion**: Secure RDP access to VM without public IP
- **Storage Account**: Standard HDD storage with file share
- **Private Endpoint**: Secure connectivity between VM and storage account file share
- **NAT Gateway**: Outbound internet connectivity for VM subnet
- **Network Security Groups**: One per subnet with least-privilege rules
- **Key Vault**: Stores VM administrator password as secret
- **Log Analytics Workspace**: Centralized logging for all resources
- **Azure Monitor Alerts**: Critical alerts for VM stopped, disk full, Key Vault access failures
## Success Criteria *(mandatory)*
<!--
ACTION REQUIRED: Define measurable success criteria.
These must be technology-agnostic and measurable.
-->### Measurable Outcomes
- **SC-001**: Infrastructure deploys successfully within 20 minutes including all resources
- **SC-002**: ARM validation (`az deployment group validate`) passes without errors
- **SC-003**: ARM what-if analysis shows all expected resources will be created
- **SC-004**: VM is accessible via bastion host within 5 minutes of deployment completion
- **SC-005**: VM can access file share through private endpoint connection
- **SC-006**: VM can reach internet through NAT gateway for outbound connections
- **SC-007**: Diagnostic logs from all resources appear in Log Analytics within 5 minutes
- **SC-008**: All resources pass Azure Security Center baseline compliance checks
- **SC-009**: NSG rules successfully block unauthorized traffic in test scenarios
- **SC-010**: VM administrator password can be retrieved from Key Vault by authorized identities
- **SC-011**: Critical alerts can be triggered and verified (VM stop, simulated disk full warning, Key Vault access attempt)
## Assumptions
- Azure subscription has sufficient quota for Standard_D2s_v3 VM size
- Azure Bastion service is available in westus3 region
- Windows Server 2016 image is available in Azure Marketplace for westus3 region
- Log Analytics workspace can be deployed in westus3 region
- Private endpoint feature is available for storage accounts in westus3 region
- NAT Gateway is available in westus3 region
- Deployment is executed by identity with sufficient permissions to create all resource types
- Resource group name will be provided as parameter in main.bicepparam
- Random suffix for resource names will be generated or provided as parameter
- Default log retention period of 30 days is acceptable for Log Analytics (compliance requirement may differ)
- Standard_LRS storage redundancy is acceptable for this legacy workload
- VM will be deployed without availability sets or scale sets (single instance acceptable)
- Availability zone selection (1, 2, or 3) will be provided as parameter
## Out of Scope
- Multi-region deployment or disaster recovery configuration
- High availability (availability sets, load balancers, multiple VMs)
- Auto-scaling capabilities
- Backup and restore automation (Azure Backup configuration)
- Additional environments (development, test, staging)
- Application installation or configuration on the VM
- Custom monitoring dashboards or complex alerting logic beyond critical alerts
- Network connectivity to on-premises networks (VPN or ExpressRoute)
- Azure Active Directory domain join
- Additional data disks beyond the single 500GB disk specified
- Storage account configuration beyond file share (no blob containers, tables, or queues)
- Advanced network features (Azure Firewall, Application Gateway, Traffic Manager)
- Cost optimization recommendations or reserved instance planning
/speckit.specify Create specification, called "01-my-legacy-workload" for a legacy business application, running as a single virtual machine connected to a virtual network. The VM must run Windows Server 2016, needs to have at least 2 CPU cores, 8 GB of RAM, a standard HDD, and a 500 GB HDD-based data disk attached. It must be remotely accessible via a bastion host and needs to have access to an HDD-backed file share in a storage account connected via a private endpoint. The VM must access the internet via a NAT gateway. Network Security Groups (NSGs) must be created for each subnet, configured and assigned as applicable, restricting traffic to only what's necessary. VM subnet NSG must allow inbound RDP (port 3389) from Bastion subnet to enable bastion connectivity.
The VM's administrator password (created at the time of deployment) must be stored in a Key Vault, also deployed as part of this solution. The VM's administrator account must be called "vmadmin". The VM's computer name (netbios name) must be 15 or fewer characters long.
Always rely on values from the `terraform.tfvars` file only. Have the name of the secret used for the admin password captured as a variable. Include rich comments in both the `main.tf` and `terraform.tfvars` files to explain the purpose of each resource and variable.
When a decision needs to be made on availability zones, always choose a number between 1 and 3 (never choose -1, that explicitly disables this feature).
Create everything in a single resource group, standing for a production environment. Do not create any additional environments (such as dev, test, staging, etc.).
Read the documentation (readme.md file) of each module you need to use to find out what variables and complex variable objects you can use. Don't guess the allowed variables.
The VM must not be accessible from the internet and its logs should be captured in Log Analytics, included with the solution. Configure diagnostic logging plus critical-only alerts (VM stopped, disk full, Key Vault access failures).
The Azure resource naming convention should follow Azure Cloud Adoption Framework guidance. Resource type specific character and length limitations must be respected. Random character should only be added to resources that must be globally unique like storage accounts. All resource names should be kebab case unless the hyphen is not supported for that resource.
β Expand to see the results
Notice that the execution of the /speckit.specify created a new file called requirements.md and a file called spec.md in the specs/001-legacy-vm-workload/ folder.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
Once Copilot finished running the prompt, you should see something like this in the Copilot chat area:
# Specification Quality Checklist: Legacy Business Application Infrastructure
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-02-18
**Feature**: [001-my-legacy-workload/spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Validation Notes
### Content Quality Assessment
- **β Pass**: Specification focuses on infrastructure requirements (WHAT) without specifying HOW to implement (e.g., specific Terraform syntax, module parameters beyond identifying which AVM modules to use)
- **β Pass**: Written for infrastructure stakeholders and operations teams - describes Azure resources, security controls, and operational requirements
- **β Pass**: All mandatory sections present: User Scenarios & Testing, Requirements, Success Criteria, Assumptions, Dependencies, Out of Scope
### Requirement Completeness Assessment
- **β Pass**: Zero [NEEDS CLARIFICATION] markers - all requirements fully specified based on user input
- **β Pass**: Requirements are testable - each FR and SEC item can be verified (e.g., "VM MUST have 2+ CPU cores" - check VM properties; "NSG MUST allow RDP from Bastion only" - check NSG rules)
- **β Pass**: Success criteria are measurable with specific metrics (e.g., "deployment completes within 30 minutes", "RDP connection established within 2 minutes", "cost under $200/month")
- **β Pass**: Success criteria avoid implementation details - focus on outcomes (e.g., "VM can mount file share" not "private endpoint DNS configuration works")
- **β Pass**: Acceptance scenarios defined for all 4 user stories with Given/When/Then format
- **β Pass**: Edge cases identified (8 scenarios covering naming limits, zone availability, DNS resolution, secret conflicts, NSG rules, storage naming, subnet sizing, disk attachment)
- **β Pass**: Scope clearly bounded with detailed "Out of Scope" section (15 items explicitly excluded like HA config, DR, multiple environments, domain join, etc.)
- **β Pass**: Dependencies section lists all prerequisites (Terraform version, Azure CLI, AVM modules, Azure subscription,state backend, etc.)
- **β Pass**: Assumptions section documents all implicit decisions (15 assumptions covering quotas, state backend existence, permissions, naming conflicts, zone support, application compatibility, etc.)
### Feature Readiness Assessment
- **β Pass**: All 25 functional requirements map to user stories and have testable acceptance criteria
- **β Pass**: 4 user stories cover complete infrastructure lifecycle: P1 (core compute/network), P2 (secure access), P3 (storage), P4 (internet/monitoring)
- **β Pass**: Each user story independently testable and deliverable
- **β Pass**: Success criteria define 13 measurable outcomes aligned with requirements
- **β Pass**: No Terraform syntax or module-specific parameters in spec (appropriate - those belong in plan/implementation phase)
### Specification Completeness: READY FOR PLANNING β
**Summary**: Specification passes all quality gates. No clarifications needed. Ready to proceed with `/speckit.plan` to generate implementation plan.
**Recommended Next Steps**:
1. Run `/speckit.plan` to generate implementation plan with Terraform architecture
2. During planning phase, research AVM module documentation for each identified resource
3. Define Technical Context (Terraform version, provider versions, AVM module versions)
4. Create Project Structure (terraform/ directory layout)
5. Generate tasks.md with phased implementation (Setup β Foundational β US1-US4 β Polish)
# Feature Specification: Legacy Business Application Infrastructure
**Feature Branch**: `001-my-legacy-workload`**Created**: 2026-02-18
**Status**: Draft
**Input**: User description: "Legacy business application running as a single virtual machine with Windows Server 2016, networking (VNet, Bastion, NAT Gateway, NSGs), storage (file share via private endpoint), Key Vault for secrets, and Log Analytics for monitoring"
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Core Compute and Network Infrastructure (Priority: P1)
Deploy a Windows Server 2016 virtual machine within an isolated virtual network with proper subnet segmentation and network security controls. This provides the foundational compute and network infrastructure required for the legacy application.
**Why this priority**: Without the VM and basic networking, the application cannot run. This is the minimum viable infrastructure that delivers compute capability in an isolated, secure network environment.
**Independent Test**: Deploy Terraform configuration, verify VM is created and running in the specified VNet with proper subnets. Confirm NSGs are attached to subnets and default deny rules are in place. VM should be isolated with no internet or external access at this stage.
**Acceptance Scenarios**:
1.**Given** Terraform configuration with VM and VNet resources, **When**`terraform apply` is executed, **Then** a Windows Server 2016 VM is created with 2+ CPU cores, 8GB RAM, standard HDD OS disk, and 500GB HDD data disk
2.**Given** the VM is deployed, **When** checking the virtual network, **Then** VNet contains at least 3 subnets (VM subnet, Bastion subnet, Private Endpoint subnet) with appropriate CIDR ranges
3.**Given** subnets are created, **When** checking NSG assignments, **Then** each subnet has an NSG attached with deny-by-default rules configured
4.**Given** VM is running, **When** checking VM properties, **Then** computer name is 15 characters or fewer, administrator account is "vmadmin", and password is stored in Key Vault (secret name configurable)
5.**Given** VM subnet NSG rules, **When** checking inbound rules, **Then** NSG allows RDP (port 3389) from Bastion subnet only
---
### User Story 2 - Secure Remote Access (Priority: P2)
Enable secure remote access to the virtual machine through Azure Bastion and store the VM administrator password securely in Azure Key Vault. This allows administrators to manage the VM without exposing it to the internet.
**Why this priority**: Secure access is critical for managing the VM and performing administrative tasks. Without Bastion, the VM would need a public IP (violating security requirements) or would be completely inaccessible.
**Independent Test**: After deploying US1, deploy Bastion and Key Vault infrastructure. Verify administrators can connect to the VM via Azure Bastion using credentials retrieved from Key Vault. Confirm VM has no public IP address.
**Acceptance Scenarios**:
1.**Given** Bastion host and Key Vault are deployed, **When** administrator navigates to VM in Azure Portal, **Then** "Connect via Bastion" option is available
2.**Given** Bastion connection initiated, **When** using "vmadmin" username and password from Key Vault, **Then** RDP session to VM is successfully established
3.**Given** Key Vault is deployed, **When** checking secrets, **Then** VM administrator password is stored as a secret with configurable name (defined in terraform.tfvars)
4.**Given** VM networking configuration, **When** checking VM properties, **Then** VM has no public IP address and is not directly accessible from internet
5.**Given** Key Vault access policies, **When** Terraform deploys the infrastructure, **Then** Key Vault uses managed identity for authentication (no service principal credentials in code)
---
### User Story 3 - Application Storage Integration (Priority: P3)
Provide secure access to an Azure Files share for application data storage, connected via private endpoint to ensure data does not traverse the public internet.
**Why this priority**: The legacy application requires access to a file share for data persistence. This enables the application's core functionality while maintaining security through private connectivity.
**Independent Test**: After deploying US1 and US2, deploy storage account with file share and private endpoint. From the VM, mount the Azure Files share using private endpoint IP. Verify data can be written to and read from the share without public internet connectivity.
**Acceptance Scenarios**:
1.**Given** storage account is deployed, **When** checking storage configuration, **Then** storage account has HDD-backed file share created (Standard tier, not Premium)
2.**Given** private endpoint is deployed, **When** checking network connectivity, **Then** private endpoint is connected to the Private Endpoint subnet in the VNet
3.**Given** private endpoint exists, **When** checking DNS resolution from VM, **Then** storage account FQDN resolves to private endpoint IP address (not public IP)
4.**Given** VM is running, **When** attempting to mount file share, **Then** file share is accessible from VM using private IP and SMB protocol
5.**Given** storage NSG rules, **When** checking Private Endpoint subnet NSG, **Then** NSG allows SMB traffic (port 445) from VM subnet only
---
### User Story 4 - Internet Access and Observability (Priority: P4)
Enable outbound internet access via NAT Gateway for Windows Updates and patches, and implement comprehensive monitoring through Log Analytics with diagnostic logging and critical alerts.
**Why this priority**: While not required for basic application functionality, internet access enables the VM to download security updates. Monitoring and alerting provide operational visibility and compliance evidence.
**Independent Test**: After deploying US1-US3, deploy NAT Gateway and Log Analytics. From VM, verify outbound internet connectivity (e.g., download Windows Update). Confirm diagnostic logs are flowing to Log Analytics and test alerts trigger correctly.
**Acceptance Scenarios**:
1.**Given** NAT Gateway is deployed and associated with VM subnet, **When** VM attempts outbound HTTP/HTTPS connection, **Then** connection succeeds with traffic routed through NAT Gateway
2.**Given** VM attempts inbound connection from internet, **When** traffic reaches VM subnet, **Then** connection is blocked (VM remains inaccessible from internet)
3.**Given** Log Analytics workspace is deployed, **When** checking diagnostic settings, **Then** VM, Key Vault, and Storage Account have diagnostic logging enabled sending logs to Log Analytics
4.**Given** alerts are configured, **When** VM is stopped, **Then** critical alert notification is triggered
5.**Given** alerts are configured, **When** VM disk reaches 90% capacity, **Then** critical alert notification is triggered
6.**Given** alerts are configured, **When** Key Vault access failure occurs (e.g., permission denied), **Then** critical alert notification is triggered
---
### Edge Cases
- **VM naming constraints**: What happens when generated VM computer name exceeds 15 characters (NetBIOS limit)? Truncate or error during validation.
- **Availability zone selection**: If availability zones 1-3 are unavailable in westus3 region, how does deployment handle this? Fail with clear error or fall back to no-zone deployment?
- **Private endpoint DNS**: What happens when private DNS zone for storage account doesn't exist or isn't linked to VNet? File share mount will fail without proper DNS resolution.
- **Key Vault secret naming**: What happens when the secret name specified in terraform.tfvars already exists in Key Vault? Overwrite or error?
- **NSG rule conflicts**: What happens when custom NSG rules conflict with required rules (e.g., accidentally blocking RDP from Bastion)? Terraform should fail validation.
- **Storage account naming**: What happens when randomly generated storage account name conflicts with existing global namespace? Terraform apply will fail - require retry with new random suffix.
- **Bastion subnet size**: What happens when VNet address space is too small for required subnets including /26 for Bastion? Deployment fails with clear CIDR allocation error.
- **Managed disk attachment**: What happens when 500GB data disk fails to attach to VM? Deployment should fail atomically (VM should not be left in inconsistent state).
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: Infrastructure MUST deploy a Windows Server 2016 virtual machine with minimum 2 CPU cores and 8GB RAM
- **FR-002**: VM MUST use standard HDD for OS disk (not SSD) for cost optimization
- **FR-003**: VM MUST have a 500GB HDD-based managed disk attached as data disk
- **FR-004**: VM computer name (NetBIOS name) MUST be 15 characters or fewer to comply with Windows naming limits
- **FR-005**: VM administrator account MUST be named "vmadmin"
- **FR-006**: VM administrator password MUST be generated at deployment time and stored in Key Vault
- **FR-007**: Infrastructure MUST deploy a virtual network with at least 3 subnets (VM subnet, Bastion subnet, Private Endpoint subnet)
- **FR-008**: Infrastructure MUST deploy Network Security Groups for each subnet with deny-by-default posture
- **FR-009**: VM subnet NSG MUST allow inbound RDP (port 3389) from Bastion subnet ONLY
- **FR-010**: Infrastructure MUST deploy Azure Bastion for secure RDP access to VM (no public IP on VM)
- **FR-011**: VM MUST NOT be accessible directly from the internet (no public IP address on VM)
- **FR-012**: Infrastructure MUST deploy NAT Gateway associated with VM subnet for outbound internet access
- **FR-013**: Infrastructure MUST deploy storage account with HDD-backed (Standard tier) Azure Files share
- **FR-014**: Storage account file share MUST be accessible from VM via private endpoint (no public access)
- **FR-015**: Infrastructure MUST deploy Key Vault for storing VM administrator password securely
- **FR-016**: Key Vault secret name for VM password MUST be configurable via terraform.tfvars variable
- **FR-017**: Infrastructure MUST use managed identities for authentication (no service principal credentials in Terraform code)
- **FR-018**: Infrastructure MUST deploy Log Analytics workspace for centralized logging
- **FR-019**: VM, Key Vault, and Storage Account MUST have diagnostic settings enabled sending logs to Log Analytics
- **FR-020**: Infrastructure MUST configure critical alerts: VM stopped, VM disk usage >90%, Key Vault access failures
- **FR-021**: All configurable values (VM size, disk sizes, subnet CIDRs, secret names, etc.) MUST be defined in terraform.tfvars (not hardcoded in main.tf)
- **FR-022**: All Terraform files (main.tf, terraform.tfvars) MUST include rich comments explaining purpose of each resource, variable, and configuration block
- **FR-023**: When selecting availability zones, MUST choose zone 1, 2, or 3 (NEVER use -1 or no-zone unless region doesn't support zones)
- **FR-024**: All resources MUST be deployed in a single resource group representing production environment
- **FR-025**: Infrastructure MUST reference AVM module documentation (readme.md) to determine correct variable names and object structures (no guessing)
### Infrastructure Requirements *(for Terraform IaC projects)*
**Azure Resources Required**:
- **Resource 1**: Resource Group for all resources - AVM Module: `Azure/avm-res-resources-resourcegroup/azurerm`- **Resource 2**: Virtual Network with 3+ subnets - AVM Module: `Azure/avm-res-network-virtualnetwork/azurerm`- **Resource 3**: Network Security Groups (3 minimum) - AVM Module: `Azure/avm-res-network-networksecuritygroup/azurerm`- **Resource 4**: Windows Server 2016 Virtual Machine - AVM Module: `Azure/avm-res-compute-virtualmachine/azurerm`- **Resource 5**: Azure Bastion Host - AVM Module: `Azure/avm-res-network-bastionhost/azurerm`- **Resource 6**: Key Vault for password storage - AVM Module: `Azure/avm-res-keyvault-vault/azurerm`- **Resource 7**: Storage Account with file share - AVM Module: `Azure/avm-res-storage-storageaccount/azurerm`- **Resource 8**: Private Endpoint for storage - AVM Module: `Azure/avm-res-network-privateendpoint/azurerm` (or part of storage module)
- **Resource 9**: NAT Gateway - AVM Module: `Azure/avm-res-network-natgateway/azurerm`- **Resource 10**: Log Analytics Workspace - AVM Module: `Azure/avm-res-operationalinsights-workspace/azurerm`- **Resource 11**: Alerts/Action Groups - use AzAPI `Microsoft.Insights/actionGroups` and `Microsoft.Insights/metricAlerts` resources
- **Resource 12**: Random string for naming suffix - Built-in: `random_string` from random provider
**Infrastructure Constraints**:
- **IC-001**: All resources MUST be deployed to `westus3` region (per constitution)
- **IC-002**: Terraform state MUST be stored in Azure Storage backend with state locking enabled
- **IC-003**: Resource naming MUST follow `<type>-<workload>-<suffix>` pattern (per constitution, e.g., `vm-avmlegacy-8k3m9x`)
- **IC-004**: No high-availability or geo-redundancy configurations (legacy workload constraint, single VM acceptable)
- **IC-005**: All resources MUST be deployed in single Resource Group (named per convention: `rg-my-legacy-workload-prod-wus3`)
- **IC-006**: Availability zone MUST be selected (zone 1, 2, or 3) - NEVER use -1 or disable zones explicitly
- **IC-007**: Use HDD/Standard tier storage for cost optimization (OS disk, data disk, storage account)
- **IC-008**: VNet MUST have sufficient address space for minimum 3 subnets (recommend /23 or larger for VNet, /26 for Bastion per Azure requirements)
- **IC-009**: Private Endpoint subnet MUST have `privateEndpointNetworkPolicies` disabled per Azure requirements
- **IC-010**: Computer name generation MUST enforce 15-character limit (Windows NetBIOS constraint)
**Security & Compliance**:
- **SEC-001**: VM MUST use managed identity (system-assigned) for Azure service authentication
- **SEC-002**: VM administrator password MUST be stored in Key Vault with secret name defined in terraform.tfvars
- **SEC-003**: NO service principal credentials or secrets in Terraform files (.tf or .tfvars)
- **SEC-004**: Network Security Groups MUST implement deny-by-default posture with explicit allow rules only
- **SEC-005**: VM subnet NSG MUST allow RDP (3389) ONLY from Bastion subnet CIDR (source IP restricted)
- **SEC-006**: Bastion subnet NSG MUST allow inbound 443 from internet (Azure Bastion requirement) and outbound RDP to VM subnet
- **SEC-007**: Private Endpoint subnet NSG MUST allow SMB (445) from VM subnet for file share access
- **SEC-008**: VM MUST NOT have public IP address (internet inaccessible)
- **SEC-009**: Storage account MUST have public network access disabled (private endpoint only)
- **SEC-010**: Diagnostic logging MUST be enabled on VM, Key Vault, and Storage Account sending logs to Log Analytics
- **SEC-011**: Resource locks (CanNotDelete) MUST be applied to Resource Group, VM, Key Vault, and Storage Account (compliance-critical resources)
- **SEC-012**: Key Vault MUST have soft-delete and purge protection enabled
- **SEC-013**: Storage account MUST use encryption at rest with Microsoft-managed keys (minimum)
- **SEC-014**: All network traffic between VM and storage MUST traverse private endpoint (verified via NSG flow logs or connection test)
**State Management**:
- **State Backend**: Azure Storage Account in separate resource group (pre-existing, not created by this Terraform)
- **State File**: `my-legacy-workload-prod.tfstate`- **State Locking**: Enabled via blob lease mechanism
- **Workspaces/Key Prefix**: Single production environment only - use `prod.tfvars` for variable values
### Key Entities *(include if feature involves data)*
- **Virtual Machine**: Windows Server 2016 compute instance running legacy business application. Attributes: computer name (β€15 chars), size (Standard_D2s_v3 or similar with 2+ cores, 8GB RAM), OS disk (Standard HDD), data disk (500GB Standard HDD), administrator credentials (username: vmadmin, password in Key Vault).
- **Virtual Network**: Isolated network containing all infrastructure. Attributes: address space (e.g., 10.0.0.0/23), subnets (VM subnet, Bastion subnet /26, Private Endpoint subnet).
- **Network Security Group**: Firewall rules for subnet-level traffic control. Attributes: associated subnet, inbound rules (RDP from Bastion, SMB to private endpoint), outbound rules (allow NAT Gateway for internet, deny all else).
- **Azure Bastion**: Managed PaaS service providing secure RDP/SSH access. Attributes: Bastion subnet (/26 minimum), public IP (managed by Bastion), SKU (Basic or Standard).
- **Key Vault**: Secure secrets store for VM password. Attributes: soft-delete enabled, purge protection enabled, access policies (Terraform managed identity for deployment, VM managed identity for runtime access if needed).
- **Storage Account**: Azure Files storage for application data. Attributes: Standard performance tier (HDD), LRS replication, file share (e.g., 100GB quota), private endpoint connection.
- **Private Endpoint**: Network interface in VNet providing private IP for storage account. Attributes: subnet (Private Endpoint subnet), private DNS integration (optional but recommended).
- **NAT Gateway**: Managed outbound internet gateway. Attributes: public IP address, associated with VM subnet for outbound traffic.
- **Log Analytics Workspace**: Centralized log repository. Attributes: retention period (e.g., 30-90 days per compliance requirements), diagnostic settings (VM, Key Vault, Storage Account).
- **Alerts**: Monitoring rules triggering on critical conditions. Attributes: VM stopped alert, disk space alert (>90%), Key Vault access failure alert, action group for notifications.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: Infrastructure deployment completes successfully via `terraform apply` within 30 minutes with all resources in "healthy" state
- **SC-002**: Administrator can establish RDP connection to VM via Azure Bastion within 2 minutes of infrastructure deployment completion
- **SC-003**: VM administrator password retrieved from Key Vault successfully authenticates RDP session via Bastion (100% success rate)
- **SC-004**: VM can mount Azure Files share via private endpoint and read/write files without errors (verified via test file operations)
- **SC-005**: VM can download content from internet via NAT Gateway (e.g., successful Windows Update check or HTTP GET to microsoft.com)
- **SC-006**: VM is NOT reachable via direct internet connection (verified via external port scan showing no open ports)
- **SC-007**: Diagnostic logs from VM, Key Vault, and Storage Account appear in Log Analytics within 15 minutes of deployment
- **SC-008**: Critical alerts (VM stopped, disk >90%, Key Vault access failure) trigger notifications within 5 minutes of condition occurring (tested via controlled failure scenarios)
- **SC-009**: All Terraform validation steps pass (`terraform fmt -check`, `terraform validate`, `tfsec` with no HIGH/CRITICAL findings)
- **SC-010**: Infrastructure deployment uses ONLY values from terraform.tfvars (no hardcoded values in main.tf) - verified via code review
- **SC-011**: All AVM module variables are correctly structured per module documentation (verified by successful deployment without Terraform errors)
- **SC-012**: Computer name is 15 characters or fewer (verified via VM properties after deployment)
- **SC-013**: Total monthly cost of deployed infrastructure is under $200/month (estimated based on Azure pricing calculator)
## Assumptions
- **A-001**: Azure subscription has sufficient quota for VM size, NAT Gateway, and Bastion in westus3 region
- **A-002**: Terraform state backend (Azure Storage Account) already exists and is configured prior to deployment (not managed by this Terraform code)
- **A-003**: Deployment identity (user, service principal, or managed identity running Terraform) has Contributor access to target subscription or resource group scope
- **A-004**: No existing resources with conflicting names in the subscription (e.g., duplicate storage account name, Key Vault name)
- **A-005**: Azure region westus3 supports availability zones (deployment assumes zone selection 1-3 is valid)
- **A-006**: Legacy application compatibility with Windows Server 2016 has been validated (not part of infrastructure scope)
- **A-007**: Legacy application does not require specific VM size beyond minimum 2 cores, 8GB RAM (actual VM SKU chosen for cost-performance balance)
- **A-008**: 500GB data disk is sufficient for application data storage requirements (not dynamically scaled)
- **A-009**: Standard HDD performance is adequate for legacy application workload (no IOPS/throughput requirements specified)
- **A-010**: File share quota (e.g., 100GB) is sufficient for application needs - configurable in terraform.tfvars if different
- **A-011**: Alert notifications can use email or webhook action group (specific notification target configured separately or in variables)
- **A-012**: VNet address space 10.0.0.0/23 (512 IPs) is sufficient and does not conflict with on-premises networks or VPN peering requirements
- **A-013**: No ExpressRoute or VPN gateway integration required (VM internet access is outbound only via NAT Gateway)
- **A-014**: VM does not require domain join (workgroup/standalone configuration acceptable)
- **A-015**: No existing Azure Policy assignments block required configuration (e.g., policy preventing public IP on Bastion, policy requiring specific encryption)
## Dependencies
- **D-001**: Terraform >= 1.5.0 installed on deployment machine
- **D-002**: Azure CLI authenticated with sufficient permissions (`az login` completed)
- **D-003**: AVM modules available from Terraform Registry (internet connectivity required during `terraform init`)
- **D-004**: Azure subscription with active valid payment method and sufficient credits
- **D-005**: Pre-existing Azure Storage Account and container for Terraform state backend
- **D-006**: Pre-existing Resource Group for Terraform state backend (separate from workload resource group)
- **D-007**: Azure region westus3 supports all required resource types (VM, Bastion, NAT Gateway, availability zones)
- **D-008**: AVM module documentation (readme.md) accessible for each module used (refer to Terraform Registry or GitHub)
- **D-009**: Terraform providers: AzAPI (~> 2.12) for direct resources, AzureRM (~> 4.0) as required by published AVM dependencies, and random (~> 3.5)
- **D-010**: Security scanning tools (tfsec or checkov) installed if enforcing constitution security requirements
- **D-011**: Windows Server 2016 image available in Azure Marketplace (standard Microsoft image)
- **D-012**: Understanding of Terraform module composition (reading AVM module documentation to determine input variables and complex objects)
## Out of Scope
- **OS-001**: Installation or configuration of legacy business application on the VM (infrastructure only, app deployment separate)
- **OS-002**: Domain join or Active Directory integration (standalone/workgroup VM)
- **OS-003**: VPN gateway or ExpressRoute connectivity to on-premises networks
- **OS-004**: Multiple environments (dev, test, staging) - ONLY production environment deployed
- **OS-005**: High availability configuration (multiple VMs, load balancer, availability set) - single VM by design per legacy constraint
- **OS-006**: Disaster recovery or geo-replication configuration (no backup policies, no secondary region)
- **OS-007**: Auto-scaling or dynamic resource sizing (fixed VM size, fixed disk sizes)
- **OS-008**: Custom VM extensions or DSC configuration (beyond basic deployment)
- **OS-009**: Application-level monitoring or APM (only infrastructure-level diagnostics in Log Analytics)
- **OS-010**: Database deployment (if legacy app uses database, assumed to be on separate server or managed service)
- **OS-011**: DNS records in public or private DNS zones (beyond private endpoint DNS if AVM module handles it)
- **OS-012**: Certificate management or SSL/TLS termination (application responsibility if needed)
- **OS-013**: Cost management tags beyond basic workload identification (detailed cost center, project, owner tags)
- **OS-014**: Compliance frameworks implementation (HIPAA, PCI-DSS, SOC2) - basic security controls only per constitution
- **OS-015**: Terraform module development (using existing AVM modules only, no custom module authoring)
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture the clarified specification of your project, with a comment of something like Specification created.
3. Clarify (Optional)
Spec Kit uses /speckit.clarify to generate adjust information captured in spec.md. The prompt doesn’t require any specific inputs as it analyzes the existing specification for gaps.
Info
To learn more about the clarify step, see the Clarify chapter in the Spec Kit article.
Run the following prompt to generate clarification questions for our example:
/speckit.clarify
β Expand to see example questions
The clarify phase iterates on the spec.md file by asking questions, making suggestions and capturing the user’s feedback.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
When running the clarify prompt, Copilot may ask you a number of depth questions to clarify certain aspects of the plan. Here’s an example of what that looks like. You can answer in the following format, e.g.: Q1: E, Q2:A, Q3:A
In the Copilot chat window, you will likely see some questions raised, similar to these. You can answer these just like in a normal chat conversation - e.g., by typing the letter standing for the option provided for each question, or by elaborating further if needed.
See a few examples of clarifying questions Copilot may ask. Copilot typically suggests a few options, but you can always deviate from them as needed, just use the chat to provide your answers.
## Clarifications
- Q: How should the Azure file share be mounted on the Windows VM? β A: Post-deployment manual mount by administrator following documented procedure (no automation, aligns with IaC-first principle)
- Q: What level of monitoring and alerting should be configured for this legacy workload? β A: Diagnostic logging plus critical-only alerts (VM stopped, disk full, Key Vault access failures)
- Q: If the initial deployment partially fails (e.g., VM creates but Bastion fails), what should the recovery procedure be? β A: Keep existing resources, fix errors in template/parameters, redeploy entire template (ARM incremental mode handles already-deployed resources)
- Q: File share initial quota and growth strategy? β A: 1TB initial quota with documented growth monitoring procedure
- Q: VM administrator username? β A: vmadmin
- Q: VNet address space and subnet sizing for VM, bastion, and private endpoint subnets? β A: VNet: 10.0.0.0/24, VM subnet: 10.0.0.0/27, Bastion subnet: 10.0.0.64/26, Private endpoint subnet: 10.0.0.128/27
- Q: Storage file share quota size? β A: 1024 GiB (1 TiB)
- Q: Disk space alert threshold percentage? β A: 85% full
- Q: Alert notification method for critical alerts? β A: Azure Portal notifications only
- Q: VM size SKU for 2 cores and 8GB RAM requirement? β A: Standard_D2s_v3
/speckit.clarify
β Expand to see example questions
The clarify phase iterates on the spec.md file by asking questions, making suggestions and capturing the user’s feedback.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
When running the clarify prompt, Copilot may ask you a number of depth questions to clarify certain aspects of the plan. Here’s an example of what that looks like. You can answer in the following format, e.g.: Q1: E, Q2:A, Q3:A
In the Copilot chat window, you will likely see some questions raised, similar to these. You can answer these just like in a normal chat conversation - e.g., by typing the letter standing for the option provided for each question, or by elaborating further if needed.
See a few examples of clarifying questions Copilot may ask. Copilot typically suggests a few options, but you can always deviate from them as needed, just use the chat to provide your answers.
## Clarifications
- Q: Backup & Recovery Strategy - Does the legacy workload require Azure Backup for VM and data disk? β A: No backups needed - VM and data disk are disposable, can be recreated from Terraform
- Q: VNet Address Space and Subnet Sizing - What specific CIDR allocations should be used for the 3 required subnets? β A: Minimal: 10.0.0.0/24 (VM: /27, Bastion: /26, PrivateEndpoint: /28) - tight fit, no growth
- Q: VM Size SKU Selection - Which specific Azure VM SKU should be used for the 2-core/8GB requirement? β A: Standard_D2s_v3 (General Purpose) - balanced, widely used, predictable performance
- Q: Azure Files Share Quota and Performance Tier - What provisioned capacity should the file share have? β A: 1TB Standard tier (LRS) - large capacity for growth
- Q: Log Analytics Workspace Retention Period - How long should diagnostic logs be retained? β A: 180 days retention - extended compliance coverage, moderate cost increase
- Q: How should the Azure file share be mounted on the Windows VM? β A: Post-deployment manual mount by administrator following documented procedure (no automation, aligns with IaC-first principle)
- Q: What level of monitoring and alerting should be configured for this legacy workload? β A: Diagnostic logging plus critical-only alerts (VM stopped, disk full, Key Vault access failures)
- Q: If the initial deployment partially fails (e.g., VM creates but Bastion fails), what should the recovery procedure be? β A: Keep existing resources, fix errors in template/parameters, redeploy entire template (ARM incremental mode handles already-deployed resources)
- Q: VM administrator username? β A: vmadmin
- Q: VNet address space and subnet sizing for VM, bastion, and private endpoint subnets? β A: VNet: 10.0.0.0/24, VM subnet: 10.0.0.0/27, Bastion subnet: 10.0.0.64/26, Private endpoint subnet: 10.0.0.128/27
- Q: Disk space alert threshold percentage? β A: 85% full
- Q: Alert notification method for critical alerts? β A: Azure Portal notifications only
Review and approve the changes suggested by Copilot by clicking on the “Keep” button!
It is recommended to make a commit now to capture the updated specification of your project, with a comment of something like Specification clarified.
4. Plan
Spec Kit uses /speckit.plan to generate the plan.md file. The plan can be evolved through iterating over the plan.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.plan, or leveraging /speckit.checklist to review/validate and challenge the plan.
Info
To learn more about what the plan should include, see the Plan chapter in the Spec Kit article.
Click through the tabs to see the details!
Run the following prompt to generate the plan for our example:
/speckit.planΒ Create a detailed plan for the spec. Build with the latest version of Bicep and the latest available version of each AVM module. Use the "Bicep/list_avm_metadata" MCP tool to find out what's the latest version of each module. Only include direct resource references in the Bicep template if no related AVM resource modules are available. Similarly, for diagnostic settings, role assignments, resource locks, tags, managed identities, private endpoints, customer manged keys, etc., always use the related "interface" built-in to each resource module when available. Do not create and reference local modules, or any other bicep files.Β If a subset of the deployments fail, don't delete anything, just attempt redeploying the whole solution after fixing any bugs. Create a single main.bicep file, with direct references to AVM modules and leverage a single *.bicepparam file for all input parameters.
When generating the admin password for the VM, use the secret feature built into the AVM Key Vault module. Leverage the uniqueString function to generate a new random password and do not use any external helper script (including deployment scripts) for generating the password. Provide this password to the VM module by referencing the Key vault secret that stores it. The template must first generate this password including a random, complex string, using the uniqueString Bicep function, store it in Key Vault and then reference it for the VM to use it as admin password at deployment time.
Don't connect the file share to the VM just yet - i.e., no need to extract storage keys or shared access signatures - we will do this later.
If implementing resource level locks, always use the built-in AVM "interface" for resource locks, instead of directly deploying the "Microsoft.Authorization/locks" resource.
Bicep template must compile without warnings or errors using the latest stable Bicep CLI version. Create a bicepconfig.json file to generate a warning when not the latest version of an AVM module is used. You can configure this by making sure in the bicepconfig.json file, there is a node under analyzers/core/rules/use-recent-module-versions/level" with the value of "warning". Before validating the template or attempting the first deployment, always fix all warnings or errors related to the AVM module versioning by updating to the latest available version of each module.
β Expand to see the results
Notice how the plan step creates the plan.md file and a number of additional helper files. These may very depending on your prompts, the solution you are building, the version of Spec Kit and the LLM used. These typically include: data-model.md, research.md, quickstart.md and optional files in the contracts folder, such as outputs.md and parameters.md.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
In the Copilot chat window, you should see results, similar to this:
<!-- markdownlint-disable --># Implementation Plan: Legacy VM Workload
**Branch**: `001-legacy-vm-workload` | **Date**: 2026-01-27 | **Spec**: [spec.md](./spec.md)
**Input**: Feature specification from `/specs/001-legacy-vm-workload/spec.md`**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
## Summary
Deploy a legacy Windows Server 2016 virtual machine workload to Azure using Infrastructure-as-Code (Bicep) with the following capabilities:
- **Core Infrastructure**: Windows Server 2016 VM (Standard_D2s_v3) in availability zone 1, with system-assigned managed identity, 500GB HDD data disk, no public IP, deployed in dedicated VNet (10.0.0.0/24)
- **Secure Access**: Azure Bastion for RDP access, password stored in Key Vault, no direct internet exposure
- **Storage**: 1TB Azure Files share accessible via private endpoint from VM subnet
- **Network Security**: NAT Gateway for outbound internet, NSGs on all subnets with least-privilege rules, private endpoint for storage account
- **Monitoring**: Log Analytics workspace with diagnostic settings on all resources, three critical alerts (VM stopped, disk space >85%, Key Vault access failures), portal-only notifications
- **Naming**: Minimal naming convention with resource type prefix and 4-6 character random suffix
- **Region**: All resources in westus3 (US West 3)
**Technical Approach**: Single-template Bicep deployment using 12 Azure Verified Modules (latest stable versions), ARM-managed dependencies, parameter-driven configuration with uniqueString() for password generation.
## Technical Context
**IaC Language**: Bicep v0.33.0 or later (latest stable)
**Module Framework**: Azure Verified Modules (AVM) - 12 modules identified
**Target Region**: westus3 (US West 3)
**Deployment Tool**: Azure CLI v2.65.0+ (`az deployment group create`)
**Validation Required**: `bicep build` + `az deployment group validate` + `what-if` analysis
**Workload Type**: Legacy compliance-retained workload (Windows Server 2016)
**High Availability**: Single-zone deployment (availability zone parameter: 1, 2, or 3)
**Disaster Recovery**: Not required
**Scalability Requirements**: Static single VM, no auto-scaling
**Security Baseline**: Diagnostic logging to Log Analytics, managed identities, NSGs, private endpoints, Key Vault for secrets
**Naming Convention**: `{resourceType}-{purpose}-{random4-6chars}` (e.g., `vm-legacyvm-k7m3p`)
**Compliance Tags**: `workload: legacy-vm`, `environment: production`, `compliance: legacy-retention`### AVM Modules Selected (Latest Versions)
| Module | Version | Purpose |
|--------|---------|---------|
| avm/res/network/virtual-network | 0.7.2 | VNet with 3 subnets (VM, Bastion, PE) |
| avm/res/compute/virtual-machine | 0.21.0 | Windows Server 2016 VM with data disk |
| avm/res/network/bastion-host | 0.8.2 | Secure RDP access |
| avm/res/storage/storage-account | 0.31.0 | File share with private endpoint |
| avm/res/network/nat-gateway | 2.0.1 | Outbound internet connectivity |
| avm/res/network/network-security-group | 0.5.2 | Subnet-level network security (3 NSGs) |
| avm/res/key-vault/vault | 0.13.3 | Store VM admin password |
| avm/res/operational-insights/workspace | 0.15.0 | Centralized logging |
| avm/res/network/private-endpoint | 0.11.1 | Private storage access |
| avm/res/insights/metric-alert | 0.4.1 | Monitoring alerts (3 alerts) |
| avm/res/network/private-dns-zone | 0.8.0 | DNS for private endpoints |
**Module Documentation**: See [research.md](./research.md) for detailed module analysis and alternatives considered.
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*- [x]**I. Infrastructure-as-Code First**: β All resources defined in single `main.bicep` template, no manual Portal configurations, deployment via Azure CLI only
- [x]**II. AVM-Only Modules**: β Using 12 AVM modules with latest stable versions (0.7.2 to 2.0.1), no direct resource declarations except where AVM unavailable (none identified)
- [x]**III. Validation Before Deployment**: β Quickstart guide includes `bicep build`, `az deployment group validate`, and `what-if` analysis steps before deployment
- [x]**IV. Security & Reliability First**: β Diagnostic logs to Log Analytics for all resources, managed identities (VM system-assigned), NSGs on all subnets, private endpoint for storage, Key Vault for password, least-privilege RBAC
- [x]**V. Minimal Naming with Type ID**: β Naming pattern: `{type}-{purpose}-{random}` (e.g., `vm-legacyvm-k7m3p`, `kv-legacyvm-k7m3p`), random suffix via `uniqueString(resourceGroup().id)` - 6 chars
- [x]**VI. Region Standardization**: β All resources deploy to westus3, parameter default set to `'westus3'`, no exceptions needed
**Constitution Compliance Status**: **PASSED** β
All 6 constitution principles satisfied. No violations requiring justification.
## Project Structure
### Documentation (this feature)
## Project Structure
### Documentation (this feature)
```text
specs/001-legacy-vm-workload/
βββ spec.md # Feature specification (completed)
βββ plan.md # This file - implementation plan (in progress)
βββ research.md # AVM module research (Phase 0 - completed)
βββ data-model.md # Network topology & resource model (Phase 1 - completed)
βββ quickstart.md # Deployment guide (Phase 1 - completed)
βββ checklists/
β βββ requirements.md # Quality validation checklist (passed)
βββ tasks.md # Task decomposition (Phase 2 - not yet created)
```### Infrastructure Code Structure
```text
avm-workload/
βββ infra/
β βββ main.bicep # Main deployment template (to be created)
β βββ main.bicepparam # Deployment parameters (to be created)
β βββ bicepconfig.json # Bicep analyzer configuration (to be created)
βββ specs/
β βββ 001-legacy-vm-workload/ # This feature documentation
βββ .specify/
β βββ memory/
β β βββ constitution.md # Governance framework
β βββ templates/ # SpecKit templates
β βββ scripts/ # SpecKit automation scripts
βββ README.md # Project overview (to be created)
```**Structure Decision**: Single-template Infrastructure-as-Code approach using Bicep with Azure Verified Modules. All 20+ resources (VM, VNet, Bastion, Storage, Key Vault, NSGs, NAT Gateway, Log Analytics, Alerts, Private Endpoint, DNS Zone, diagnostic settings, RBAC assignments) defined in one `main.bicep` file with ARM handling dependency ordering automatically. No custom modules needed - all functionality provided by AVM modules.
## Complexity Tracking
**No Constitution Violations** - This section is intentionally empty.
All 6 constitution principles are satisfied with no exceptions required. See Constitution Check section above for detailed compliance status.
---
## Implementation Phases
### Phase 0: Research & Architecture β COMPLETED
**Objective**: Identify required AVM modules, resolve technical unknowns, document architectural decisions.
**Artifacts Created**:
- β [research.md](./research.md) - AVM module inventory with latest versions, alternatives considered, implementation patterns
- β [data-model.md](./data-model.md) - Network topology, resource dependencies, configuration model, security model
- β [quickstart.md](./quickstart.md) - Step-by-step deployment guide with validation commands
**Key Decisions**:
1.**VM Password Generation**: Use Bicep `uniqueString()` function with multiple seeds (resourceGroup().id, deployment().name) - no external scripts needed
2.**Network Addressing**: VNet 10.0.0.0/24 with VM subnet /27, Bastion subnet /26, PE subnet /27
3.**Storage Access**: Private endpoint with private DNS zone integration (privatelink.file.core.windows.net)
4.**Naming Pattern**: `{type}-{purpose}-{uniqueString(6)}` for all resources
5.**Dependency Management**: Single-template approach, let ARM handle resource ordering automatically
6.**Diagnostic Settings**: All resources send logs/metrics to centralized Log Analytics workspace
**Unknowns Resolved**:
- β VNet sizing: 10.0.0.0/24 confirmed sufficient (256 IPs)
- β File share quota: 1TB (1024 GiB)
- β Disk alert threshold: 85%
- β Notification method: Azure Portal only (no Action Groups)
- β VM size: Standard_D2s_v3
- β AVM modules exist for all 11 required Azure resource types
### Phase 1: Infrastructure Code Implementation π IN PROGRESS
**Objective**: Create Bicep templates with AVM module references, parameter file, and configuration.
#### Task 1.1: Create bicepconfig.json β³ PENDING
**File**: `infra/bicepconfig.json`**Purpose**: Configure Bicep analyzer to enforce AVM best practices and warn on outdated module versions.
**Configuration**:
```json
{
"analyzers": {
"core": {
"enabled": true,
"rules": {
"use-recent-module-versions": {
"level": "warning" }
}
}
},
"moduleAliases": {
"br": {
"public": {
"registry": "mcr.microsoft.com",
"modulePath": "bicep" }
}
}
}
```**Validation**: Run `bicep build main.bicep` and verify no analyzer warnings.
#### Task 1.2: Create main.bicep β³ PENDING
**File**: `infra/main.bicep`**Purpose**: Single deployment template referencing 12 AVM modules with proper parameters.
**Structure** (700-900 lines estimated):
1.**Header** (lines 1-30):
- Metadata: name, description, owner
- Target scope: `targetScope = 'resourceGroup'`- Parameters: vmSize, vmAdminUsername, availabilityZone, fileShareQuotaGiB, logAnalyticsRetentionDays
2.**Variables** (lines 31-80):
- Random suffix: `var suffix = uniqueString(resourceGroup().id)`- Resource names: all following `{type}-{purpose}-${suffix}` pattern
- VM password: `var vmPassword = 'P@ssw0rd!${uniqueString(resourceGroup().id, deployment().name)}'`- Network configuration: subnet CIDR blocks, NSG rules
- Tags: workload, environment, compliance, managedBy, deploymentDate
3.**Log Analytics Workspace** (lines 81-110):
```bicep
module logAnalytics 'br/public:avm/res/operational-insights/workspace:0.15.0' = {
name: 'deploy-log-analytics'
params: {
name: 'law-legacyvm-${suffix}'
location: location
retentionInDays: logAnalyticsRetentionDays
tags: tags
}
}
```
4.**Virtual Network** (lines 111-200):
- Module: `avm/res/network/virtual-network:0.7.2`- 3 subnets: VM (10.0.0.0/27), Bastion (10.0.0.64/26), PE (10.0.0.128/27)
- Diagnostic settings to Log Analytics
5.**Network Security Groups** (lines 201-350):
- Module: `avm/res/network/network-security-group:0.5.2` (3 instances)
- NSG 1: VM subnet (deny all inbound, allow internet + VNet outbound)
- NSG 2: Bastion subnet (standard Azure Bastion rules)
- NSG 3: PE subnet (allow VM subnet inbound on 445, allow all outbound)
- Associate each NSG with its subnet
- Diagnostic settings to Log Analytics
6.**NAT Gateway** (lines 351-380):
- Module: `avm/res/network/nat-gateway:2.0.1`- Public IP auto-created
- Associate with VM subnet
- Diagnostic settings to Log Analytics
7.**Azure Bastion** (lines 381-410):
- Module: `avm/res/network/bastion-host:0.8.2`- Depends on VNet and Bastion NSG
- Public IP auto-created
- Diagnostic settings to Log Analytics
8.**Key Vault** (lines 411-470):
- Module: `avm/res/key-vault/vault:0.13.3`- SKU: Standard
- Access model: RBAC
- Secret: VM admin password (generated variable)
- RBAC assignment: VM managed identity β Key Vault Secrets User role
- Diagnostic settings to Log Analytics
9.**Private DNS Zone** (lines 471-500):
- Module: `avm/res/network/private-dns-zone:0.8.0`- Zone name: `privatelink.file.core.windows.net`- VNet link to main VNet
- Depends on VNet
10.**Storage Account** (lines 501-580):
- Module: `avm/res/storage/storage-account:0.31.0`- Kind: StorageV2, SKU: Standard_LRS
- Public network access: Disabled
- File share: 1024 GiB quota
- Diagnostic settings to Log Analytics
11.**Private Endpoint** (lines 581-620):
- Module: `avm/res/network/private-endpoint:0.11.1`- Service: file
- Subnet: Private Endpoint subnet
- DNS integration: Private DNS zone
- Depends on Storage Account, VNet, Private DNS Zone
12.**Virtual Machine** (lines 621-730):
- Module: `avm/res/compute/virtual-machine:0.21.0`- OS: Windows Server 2016
- Size: Standard_D2s_v3
- Admin username: parameter
- Admin password: Key Vault secret reference
- System-assigned managed identity
- OS disk: Standard HDD
- Data disk: 500GB Standard HDD, LUN 0
- NIC: VM subnet, dynamic private IP, no public IP
- Availability zone: parameter (1, 2, or 3)
- Diagnostic settings to Log Analytics
- Depends on VNet, Key Vault
13.**Metric Alerts** (lines 731-850):
- Module: `avm/res/insights/metric-alert:0.4.1` (3 instances)
- Alert 1: VM stopped (CPU < 1%for15min,Sev0)-Alert2:Diskspace >85% (OS disk used %, Sev 0)
- Alert 3: Key Vault access failures (SecretGet failures, Sev 0)
- No action groups (portal-only notifications)
- Depends on VM and Key Vault
14.**Outputs** (lines 851-900):
- VM name and resource ID
- Key Vault name and resource ID
- Storage account name and file share name
- Bastion name
- Log Analytics workspace ID
- VNet name and resource ID
**Key Implementation Notes**:
- Use AVM module built-in interfaces for diagnostic settings (NOT direct `Microsoft.Insights/diagnosticSettings` resources)
- Use AVM module built-in interfaces for RBAC role assignments (NOT direct `Microsoft.Authorization/roleAssignments` resources)
- Use AVM module built-in interfaces for locks if needed (NOT direct `Microsoft.Authorization/locks` resources)
- Reference Key Vault secret for VM password using AVM module's secret reference parameter
- ARM will automatically determine deployment order based on dependencies
- All resource names use `uniqueString(resourceGroup().id)` for suffix (6 chars, consistent across all resources)
- Storage account name: no hyphens (Azure requirement), format: `st${replace(suffix, '-', '')}` (max 24 chars)
- VM computer name: max 15 chars, format: `vm-${substring(suffix, 0, 10)}`#### Task 1.3: Create main.bicepparam β³ PENDING
**File**: `infra/main.bicepparam`**Purpose**: Parameter file for deployment with sensible defaults.
**Content**:
```bicep
using'./main.bicep'// VM Configurationparam vmSize = 'Standard_D2s_v3'param vmAdminUsername = 'vmadmin'param availabilityZone = 1
// Storage Configurationparam fileShareQuotaGiB = 1024
// Monitoring Configurationparam logAnalyticsRetentionDays = 30
// Optional overrides (uncomment to customize)// param vmName = 'vm-custom-name'// param keyVaultName = 'kv-custom-name'```**Validation**: Ensure all parameters match those defined in `main.bicep`.
#### Task 1.4: Create project README.md β³ PENDING
**File**: `README.md` (root of repository)
**Purpose**: Project overview with quickstart and links to detailed documentation.
**Sections**:
1. Project Overview
2. Architecture Summary (link to data-model.md)
3. Prerequisites (link to quickstart.md)
4. Quick Deployment (3-step process)
5. Documentation Links (spec.md, plan.md, research.md, quickstart.md)
6. Governance (link to constitution.md)
7. Support and Contributing
### Phase 2: Validation & Testing π NEXT PHASE
**Objective**: Validate Bicep templates and perform what-if analysis before deployment.
#### Task 2.1: Bicep Build Validation
```powershell
cd infra
bicep build main.bicep
# Expected: main.json created, zero warnings```**Success Criteria**:
- No compilation errors
- No analyzer warnings
- Output ARM JSON file created successfully
#### Task 2.2: ARM Template Validation
```powershell
az group create --name rg-legacyvm-test --location westus3
az deployment group validate `
--resource-group rg-legacyvm-test `
--template-file main.bicep `
--parameters main.bicepparam `
--verbose
```**Success Criteria**:
- Validation passes with `provisioningState: Succeeded`- No errors related to missing resource providers
- No errors related to invalid parameters
#### Task 2.3: What-If Analysis
```powershell
az deployment group what-if `
--resource-group rg-legacyvm-test `
--template-file main.bicep `
--parameters main.bicepparam `
--verbose
```**Success Criteria**:
- All expected resources show as "Create" (green +)
- No unexpected deletions or modifications
- Resource count: 20-25 resources total
- No warnings about deprecated API versions
#### Task 2.4: Code Review Checklist
Manual review of `main.bicep`:
- [ ] All 12 AVM modules referenced with exact versions (no floating versions)
- [ ] All module versions match research.md documentation
- [ ] uniqueString() used consistently for resource name suffixes
- [ ] Storage account name respects 24-char limit and no-hyphen requirement
- [ ] VM computer name respects 15-char limit
- [ ] All subnets have NSG associations
- [ ] NAT Gateway associated with VM subnet only
- [ ] Bastion deployed to AzureBastionSubnet (exact name required)
- [ ]**VM subnet NSG allows inbound RDP (port 3389) from Bastion subnet (10.0.0.64/26) - CRITICAL for bastion connectivity**- [ ] Private endpoint connects to correct storage service (file)
- [ ] Private DNS zone has VNet link
- [ ] Key Vault secret created with generated password
- [ ] VM references Key Vault secret for password (not plaintext)
- [ ] VM has system-assigned managed identity
- [ ] RBAC assignment: VM identity β Key Vault (Key Vault Secrets User role)
- [ ] All resources have diagnostic settings to Log Analytics
- [ ] All resources have tags applied
- [ ] All resources deploy to westus3 region
- [ ] VM data disk configured: 500GB, Standard HDD, LUN 0
- [ ] File share quota: 1024 GiB
- [ ] 3 metric alerts configured with correct thresholds
- [ ] No action groups on alerts (portal-only requirement)
- [ ] Comments explain each major section
### Phase 3: Deployment π FUTURE PHASE
**Objective**: Deploy infrastructure to Azure and verify all resources operational.
#### Task 3.1: Initial Deployment
**Pre-deployment**:
- Create resource group: `rg-legacyvm-prod`- Ensure subscription quotas sufficient (VMs, Public IPs, etc.)
- Authenticate to Azure CLI with sufficient permissions
**Deployment Command**:
```powershell
az deployment group create `
--name "legacyvm-$(Get-Date -Format 'yyyyMMdd-HHmmss')" `
--resource-group rg-legacyvm-prod `
--template-file infra/main.bicep `
--parameters infra/main.bicepparam `
--verbose
```**Expected Duration**: 15-20 minutes
**Monitoring**: Track deployment progress in Azure Portal β Resource Groups β rg-legacyvm-prod β Deployments
#### Task 3.2: Post-Deployment Verification
Follow checklist in [quickstart.md](./quickstart.md):
1.**Resource Count Verification**:
```powershell
az resource list --resource-group rg-legacyvm-prod --output table
# Expected: 20-25 resources
```
2.**Bastion Connectivity Test**:
- Retrieve VM password from Key Vault
- Connect to VM via Azure Portal Bastion
- Verify Windows Server 2016 desktop loads
3.**Log Analytics Verification**:
- Run sample Kusto queries
- Verify logs appearing for all resources
- Check for any error logs
4.**Network Connectivity Tests** (from VM):
- Test internet access via NAT Gateway
- Verify private endpoint DNS resolution
- Ping storage account private IP
5.**Alert Verification**:
- Trigger test alert (Key Vault access failure)
- Verify alert visible in Azure Portal within 5-10 minutes
- Confirm alert severity (Sev 0)
#### Task 3.3: Documentation Updates
- Update README.md with actual deployed resource names
- Record deployment timestamp and duration
- Document any deployment issues encountered and resolutions
- Create CHANGELOG.md entry for initial deployment
### Phase 4: Operational Handoff π FUTURE PHASE
**Objective**: Provide operational documentation and ensure supportability.
#### Task 4.1: Operational Runbooks
Create runbooks for common operations:
- VM start/stop procedures
- File share quota increase
- Bastion troubleshooting
- Alert acknowledgment workflow
- Disaster recovery procedure (VM rebuild)
#### Task 4.2: Cost Monitoring Setup
Document estimated monthly costs:
- VM (Standard_D2s_v3): ~$70/month
- Storage (1TB + disks): ~$50/month
- Bastion: ~$140/month
- Other services: ~$10/month
- **Total**: ~$270/month (westus3 region)
Set up Azure Cost Management alerts:
- Budget: $300/month
- Alert threshold: 80% ($240)
#### Task 4.3: Security Review
Complete post-deployment security checklist:
- [ ] All resources have diagnostic logging enabled
- [ ] VM has no public IP address
- [ ] Storage account public access disabled
- [ ] Key Vault access restricted to VM managed identity
- [ ] NSG rules follow least-privilege principle
- [ ] Azure Security Center recommendations reviewed
- [ ] No high-severity vulnerabilities identified
#### Task 4.4: Compliance Documentation
Document compliance controls met:
- Infrastructure-as-Code: All resources in version control
- Audit logging: All activity logged to Log Analytics
- Secret management: Passwords in Key Vault, not plaintext
- Network isolation: Private endpoints, no public exposure
- Change management: Deployments require validation gate
### Phase 5: Future Enhancements π OUT OF SCOPE (DOCUMENTED FOR REFERENCE)
Items explicitly out of scope for initial deployment but may be added later:
1.**File Share VM Integration**:
- Map file share as network drive in VM
- Configure persistent drive mapping via Group Policy or startup script
- Document in operational runbooks
2.**Advanced Monitoring**:
- Custom Log Analytics queries and workbooks
- Action Groups for email/SMS notifications
- Integration with external monitoring systems
3.**Backup Configuration**:
- Azure Backup for VM
- Azure Files snapshot/backup policies
- Backup retention policy aligned with compliance requirements
4.**High Availability** (if requirements change):
- Availability Set or multiple VMs across zones
- Load Balancer for multi-VM scenarios
- Azure Site Recovery for disaster recovery
5.**Security Enhancements**:
- Just-In-Time VM Access
- Azure Policy assignments
- Microsoft Defender for Cloud integration
- Network Watcher flow logs
---
## Risk Assessment & Mitigation
### Technical Risks
| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| AVM module breaking changes | Low | Medium | Pin exact module versions, monitor AVM changelogs |
| Bastion deployment timeout | Medium | Low | Allow 20-30 min deployment window, retry if needed |
| Key Vault access issues | Low | High | Thorough RBAC testing, fallback manual password retrieval |
| Private endpoint DNS resolution failures | Low | Medium | Verify Private DNS Zone VNet link, wait for propagation |
| VM extension failures (Windows diagnostics) | Medium | Low | Monitor deployment, acceptable to complete manually |
| Storage account naming conflicts | Low | Low | uniqueString() ensures uniqueness per resource group |
### Operational Risks
| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| Lost VM password | Low | High | Key Vault provides secure retrieval, document procedure |
| Excessive costs (Bastion always-on) | Medium | Medium | Document monthly costs, set budget alerts at 80% |
| Alert fatigue (too many alerts) | Low | Medium | Start with 3 critical alerts, expand based on operations feedback |
| Insufficient disk space (500GB data disk) | Medium | Low | Alert at 85%, expansion procedure documented |
| Network connectivity issues | Low | High | NAT Gateway provides reliable outbound, private endpoint for inbound |
| Manual Portal changes breaking IaC | Medium | High | Enforce constitution principle I, document prohibition clearly |
### Compliance Risks
| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| Configuration drift from manual changes | Medium | High | Constitution principle I (IaC-First) prohibits manual changes |
| Audit log gaps | Low | High | All resources send logs to Log Analytics, monitor for gaps |
| Secret exposure (VM password) | Low | Critical | Password generated in Bicep variable, stored only in Key Vault |
| Unauthorized access attempts | Low | High | No public IPs, Bastion-only access, NSG least-privilege rules |
| Non-compliance with retention policies | Low | Medium | Log Analytics retention set to 30+ days, configurable parameter |
---
## Success Criteria
### Deployment Success
- [x] All Bicep templates compile without warnings
- [ ] ARM validation passes successfully
- [ ] What-if analysis shows expected resource creation only
- [ ] Deployment completes in <30minutes- [ ]All20-25resourcescreatedsuccessfully- [ ]Nofailedresourcesorpartialdeployments### Functional Success
- [ ]VMaccessibleviaAzureBastionRDP- [ ]VMadminpasswordretrievablefromKeyVault- [ ]VMhasinternetconnectivityviaNATGateway- [ ]FileshareaccessiblefromVMviaprivateendpoint- [ ]StorageaccountprivateendpointresolvestointernalIP(10.0.0.128/27range)- [ ]AllresourcesloggingtoLogAnalytics- [ ]3metricalertsvisibleinAzurePortal- [ ]Testalertfiressuccessfullywithin10minutes### Compliance Success
- [x]All6constitutionprinciplessatisfied(seeConstitutionCheck)- [ ]Allresourcesdeployedtowestus3region- [ ]Allresourcesfollownamingconvention:{type}-{purpose}-{random}- [ ]NomanualPortalconfigurationsrequiredpost-deployment- [ ]Deploymentprocessdocumentedinquickstart.md- [ ]AllsecretsstoredinKeyVault,noneinversioncontrol### Operational Success
- [ ]Quickstartguideexecutedsuccessfullybyindependenttester- [ ]VMoperationalfor24hourswithnoerrors- [ ]Monitoringdashboardsshowhealthyresourcestate- [ ]Nohigh-severitySecurityCenteralerts- [ ]Totalmonthlycostprojection:$250-$300USD- [ ]Documentationsufficientforoperationalhandoff---## Appendices
### A. Resource Naming Reference
|ResourceType|NamePattern|Example||---------------|-------------|---------||VirtualMachine|`vm-legacyvm-{random}`|`vm-legacyvm-k7m3p`||VirtualNetwork|`vnet-legacyvm-{random}`|`vnet-legacyvm-k7m3p`||Subnets|`snet-{purpose}-legacyvm-{random}`|`snet-vm-legacyvm-k7m3p`||NetworkSecurityGroup|`nsg-{purpose}-legacyvm-{random}`|`nsg-vm-legacyvm-k7m3p`||NATGateway|`nat-legacyvm-{random}`|`nat-legacyvm-k7m3p`||AzureBastion|`bas-legacyvm-{random}`|`bas-legacyvm-k7m3p`||KeyVault|`kv-legacyvm-{random}`|`kv-legacyvm-k7m3p`||StorageAccount|`st{random-no-hyphens}`|`stk7m3p2a`||LogAnalyticsWorkspace|`law-legacyvm-{random}`|`law-legacyvm-k7m3p`||MetricAlert|`alert-{purpose}-legacyvm-{random}`|`alert-disk-space-legacyvm-k7m3p`||PrivateEndpoint|`pe-{service}-legacyvm-{random}`|`pe-file-legacyvm-k7m3p`||PrivateDNSZone|`privatelink.{service}.core.windows.net`|`privatelink.file.core.windows.net`|**Random Suffix**:Generatedusing`uniqueString(resourceGroup().id)`-produces13characters,takefirst6:`k7m3p2`### B. Network Address Allocation
|Component|CIDR|UsableIPs|Purpose||-----------|------|------------|---------||VNet|10.0.0.0/24|256|Overallnetwork||VMSubnet|10.0.0.0/27|27usable|VirtualmachineNICs||BastionSubnet|10.0.0.64/26|59usable|AzureBastion(requires/26)||PrivateEndpointSubnet|10.0.0.128/27|27usable|Storageprivateendpoint||Reserved|10.0.0.160/27|27usable|Futureexpansion||Reserved|10.0.0.192/26|59usable|Futureexpansion|### C. Required Azure Permissions
**Subscription-Level**:-`Contributor`roleORspecificresourceproviderpermissions-`User Access Administrator`role(forRBACassignmentstoKeyVault)**Resource Providers**(mustberegistered):-`Microsoft.Compute`-`Microsoft.Network`-`Microsoft.Storage`-`Microsoft.KeyVault`-`Microsoft.Insights`-`Microsoft.OperationalInsights`### D. Tool Version Requirements
|Tool|MinimumVersion|RecommendedVersion|CheckCommand||------|----------------|---------------------|---------------||AzureCLI|2.65.0|Latest|`az --version`||BicepCLI|0.33.0|Latest|`az bicep version`||PowerShell|7.4|Latest|`$PSVersionTable.PSVersion`|### E. Related Documentation
-**FeatureSpecification**: [spec.md](./spec.md) -Detailedrequirementsanduserstories-**ModuleResearch**: [research.md](./research.md) -AVMmoduleanalysisandalternatives-**DataModel**: [data-model.md](./data-model.md) -Networktopologyandresourcerelationships-**DeploymentGuide**: [quickstart.md](./quickstart.md) -Step-by-stepdeploymentinstructions-**QualityChecklist**: [checklists/requirements.md](./checklists/requirements.md) -Validationresults-**Governance**: [../../.specify/memory/constitution.md](../../.specify/memory/constitution.md) -Projectconstitution### F. Change Log
|Date|Version|Author|Changes||------|---------|--------|---------||2026-01-27|1.0.0|SpecKit|Initialimplementationplancreated|---**Plan Status**:Phase1(InfrastructureCodeImplementation)-Readyforbicepconfig.jsonandmain.bicepcreation**Next Command**:`/speckit.tasks`todecomposePhase1tasksintogranularimplementationsteps
<!-- markdownlint-disable --># Data Model: Legacy VM Workload Infrastructure
**Date**: 2026-01-27
**Feature**: [spec.md](../spec.md)
**Purpose**: Document network topology, resource relationships, and configuration data model
## Network Topology
### Virtual Network Structure
```
VNet: 10.0.0.0/24 (vnet-legacyvm-{random})
β
βββ VM Subnet: 10.0.0.0/27 (snet-vm-legacyvm-{random})
β βββ NAT Gateway attached
β βββ NSG attached (nsg-vm-legacyvm-{random})
β βββ VM Network Interface
β βββ Hosts: Virtual Machine
β
βββ Bastion Subnet: 10.0.0.64/26 (AzureBastionSubnet - required name)
β βββ NSG attached (nsg-bastion-legacyvm-{random})
β βββ Hosts: Azure Bastion
β
βββ Private Endpoint Subnet: 10.0.0.128/27 (snet-pe-legacyvm-{random})
βββ NSG attached (nsg-pe-legacyvm-{random})
βββ Hosts: Storage Account Private Endpoint
```### Address Space Allocation
| Resource | CIDR | Usable IPs | Purpose |
|----------|------|------------|---------|
| VNet | 10.0.0.0/24 | 256 | Overall network |
| VM Subnet | 10.0.0.0/27 | 32 (27 usable) | Virtual machine network interfaces |
| Bastion Subnet | 10.0.0.64/26 | 64 (59 usable) | Azure Bastion (requires /26 minimum) |
| Private Endpoint Subnet | 10.0.0.128/27 | 32 (27 usable) | Storage account private endpoints |
| Reserved | 10.0.0.160/27 | 32 | Future expansion |
| Reserved | 10.0.0.192/26 | 64 | Future expansion |
## Resource Dependency Graph
```
Resource Group
β
βββ Log Analytics Workspace
β βββ (Used by all diagnostic settings)
β
βββ Virtual Network
β βββ Depends on: None
β βββ Used by: Bastion, VM NIC, Private Endpoint
β
βββ Network Security Groups (3)
β βββ nsg-vm-legacyvm-{random}
β βββ nsg-bastion-legacyvm-{random}
β βββ nsg-pe-legacyvm-{random}
β βββ Depends on: VNet (for subnet association)
β βββ Diagnostic settings β Log Analytics
β
βββ NAT Gateway
β βββ Public IP (auto-created)
β βββ Depends on: None
β βββ Associated with: VM Subnet
β βββ Diagnostic settings β Log Analytics
β
βββ Azure Bastion
β βββ Public IP (auto-created)
β βββ Depends on: VNet (Bastion subnet)
β βββ Depends on: NSG (bastion subnet)
β βββ Diagnostic settings β Log Analytics
β
βββ Key Vault
β βββ Depends on: None (deployed early)
β βββ Secret: VM admin password (generated)
β βββ RBAC: VM managed identity (Key Vault Secrets User)
β βββ Diagnostic settings β Log Analytics
β
βββ Private DNS Zone
β βββ Name: privatelink.file.core.windows.net
β βββ VNet Link: Main VNet
β βββ Depends on: VNet
β
βββ Storage Account
β βββ File Share (1024 GiB)
β βββ Depends on: None
β βββ Public access: Disabled
β βββ Diagnostic settings β Log Analytics
β βββ Private Endpoint
β βββ Depends on: Storage Account, VNet, Private DNS Zone
β βββ Subnet: Private Endpoint Subnet
β βββ DNS integration: Private DNS Zone
β
βββ Virtual Machine
βββ Depends on: VNet, Key Vault (for password)
βββ Managed Identity: System-assigned
βββ OS Disk: Standard HDD
βββ Data Disk: 500GB Standard HDD
βββ Network Interface
β βββ Depends on: VM Subnet
β βββ No Public IP
βββ Password: Retrieved from Key Vault secret
βββ Diagnostic settings β Log Analytics
βββ Azure Monitor Alerts (3)
βββ VM Stopped Alert
β βββ Depends on: VM
βββ Disk Space Alert
β βββ Depends on: VM
βββ Key Vault Access Failures Alert
βββ Depends on: Key Vault
```## Resource Configuration Model
### Virtual Machine
```yaml
Name Pattern: vm-legacyvm-{random}Computer Name: vm-{random} (β€15 chars total)Configuration:
Size: Standard_D2s_v3OS: Windows Server 2016OS Disk:
Type: Standard_LRS (HDD performance tier)Size: Default (127 GB or OS default)Data Disks:
- Name: datadisk-01Size: 500GBType: Standard_LRS (HDD performance tier)LUN: 0Admin:
Username: vmadminPassword: {From Key Vault secret}Identity:
Type: SystemAssignedZone: {Parameter: 1, 2, or 3}Network:
NIC:
Subnet: VM SubnetPublic IP: NonePrivate IP: DynamicDiagnostics:
Boot Diagnostics: Enabled (Managed)Guest Diagnostics: Windows (via Log Analytics agent)```### Key Vault
```yaml
Name Pattern: kv-legacyvm-{random}Configuration:
SKU: StandardAccess Model: RBAC (Azure role-based access control)Public Network Access: Enabled (simplified for legacy workload)Soft Delete: Enabled (90 days)Purge Protection: Disabled (not required for legacy workload)Secrets:
- Name: {Parameter: vmAdminPasswordSecretName}Value: {Generated: uniqueString-based password}Content Type: text/plainRBAC Assignments:
- Principal: VM Managed IdentityRole: Key Vault Secrets UserScope: Key VaultDiagnostics:
Logs: All categoriesMetrics: All metricsDestination: Log Analytics```### Storage Account
```yaml
Name Pattern: st{random-no-hyphens} (β€24 chars)Configuration:
Kind: StorageV2SKU: Standard_LRS (HDD-based)Access Tier: HotPublic Network Access: DisabledMinimum TLS: 1.2File Services:
Shares:
- Name: fileshareQuota: 1024GiBAccess Tier: TransactionOptimizedPrivate Endpoints:
- Service: fileSubnet: Private Endpoint SubnetDNS Integration: privatelink.file.core.windows.netDiagnostics:
Logs: All categories (StorageRead, StorageWrite, StorageDelete)Metrics: All metricsDestination: Log Analytics```### Network Security Groups
#### VM Subnet NSG
```yaml
Name: nsg-vm-legacyvm-{random}Security Rules:
Inbound:
- Name: DenyAllInboundPriority: 4096Direction: InboundAccess: DenyProtocol: *
Source: *
Destination: *
SourcePort: *
DestinationPort: *
Outbound:
- Name: AllowInternetOutboundPriority: 100Direction: OutboundAccess: AllowProtocol: *
Source: *
Destination: InternetSourcePort: *
DestinationPort: *
- Name: AllowVnetOutboundPriority: 200Direction: OutboundAccess: AllowProtocol: *
Source: *
Destination: VirtualNetworkSourcePort: *
DestinationPort: *
- Name: DenyAllOutboundPriority: 4096Direction: OutboundAccess: DenyProtocol: *
Source: *
Destination: *
SourcePort: *
DestinationPort: *
```#### Bastion Subnet NSG
```yaml
Name: nsg-bastion-legacyvm-{random}Security Rules:
# Standard Azure Bastion required rulesInbound:
- Name: AllowHttpsInboundPriority: 100Direction: InboundAccess: AllowProtocol: TcpSource: InternetDestination: *
SourcePort: *
DestinationPort: 443 - Name: AllowGatewayManagerInboundPriority: 110Direction: InboundAccess: AllowProtocol: TcpSource: GatewayManagerDestination: *
SourcePort: *
DestinationPort: 443 - Name: AllowAzureLoadBalancerInboundPriority: 120Direction: InboundAccess: AllowProtocol: TcpSource: AzureLoadBalancerDestination: *
SourcePort: *
DestinationPort: 443 - Name: AllowBastionHostCommunicationPriority: 130Direction: InboundAccess: AllowProtocol: *
Source: VirtualNetworkDestination: VirtualNetworkSourcePort: *
DestinationPort: 8080,5701Outbound:
- Name: AllowSshRdpOutboundPriority: 100Direction: OutboundAccess: AllowProtocol: *
Source: *
Destination: VirtualNetworkSourcePort: *
DestinationPort: 22,3389 - Name: AllowAzureCloudOutboundPriority: 110Direction: OutboundAccess: AllowProtocol: TcpSource: *
Destination: AzureCloudSourcePort: *
DestinationPort: 443 - Name: AllowBastionCommunicationPriority: 120Direction: OutboundAccess: AllowProtocol: *
Source: VirtualNetworkDestination: VirtualNetworkSourcePort: *
DestinationPort: 8080,5701 - Name: AllowGetSessionInformationPriority: 130Direction: OutboundAccess: AllowProtocol: *
Source: *
Destination: InternetSourcePort: *
DestinationPort: 80```#### Private Endpoint Subnet NSG
```yaml
Name: nsg-pe-legacyvm-{random}Security Rules:
Inbound:
- Name: AllowVMSubnetInboundPriority: 100Direction: InboundAccess: AllowProtocol: TcpSource: 10.0.0.0/27Destination: *
SourcePort: *
DestinationPort: 445 - Name: DenyAllInboundPriority: 4096Direction: InboundAccess: DenyProtocol: *
Source: *
Destination: *
SourcePort: *
DestinationPort: *
Outbound:
- Name: AllowAllOutboundPriority: 100Direction: OutboundAccess: AllowProtocol: *
Source: *
Destination: *
SourcePort: *
DestinationPort: *
```### Azure Monitor Alerts
#### Alert 1: VM Stopped/Deallocated
```yaml
Name: alert-vm-stopped-legacyvm-{random}Configuration:
Type: MetricTarget: Virtual MachineMetric:
Namespace: Microsoft.Compute/virtualMachinesName: Percentage CPUCondition:
Operator: LessThanThreshold: 1Aggregation: AverageWindow: 15minutesSeverity: Critical (Sev 0)Auto-Mitigate: falseDescription: "Critical: VM appears to be stopped or deallocated"```#### Alert 2: Disk Space Exceeded
```yaml
Name: alert-disk-space-legacyvm-{random}Configuration:
Type: MetricTarget: Virtual MachineMetric:
Namespace: Microsoft.Compute/virtualMachinesName: OS Disk Used PercentageCondition:
Operator: GreaterThanThreshold: 85Aggregation: AverageWindow: 5minutesSeverity: Critical (Sev 0)Auto-Mitigate: falseDescription: "Critical: Disk space exceeded 85% threshold"```#### Alert 3: Key Vault Access Failures
```yaml
Name: alert-kv-access-fail-legacyvm-{random}Configuration:
Type: MetricTarget: Key VaultMetric:
Namespace: Microsoft.KeyVault/vaultsName: ServiceApiHitFilter:
Dimension: ActivityNameValues: SecretGetResult: FailedCondition:
Operator: GreaterThanThreshold: 0Aggregation: CountWindow: 5minutesSeverity: Critical (Sev 0)Auto-Mitigate: falseDescription: "Critical: Key Vault secret access failures detected"```## Deployment Sequence
Based on ARM dependency analysis, resources will deploy in this approximate order:
1.**Phase 1: Foundation** (Parallel)
- Log Analytics Workspace
- Virtual Network (with subnets)
- Network Security Groups
2.**Phase 2: Network & Security** (Depends on Phase 1)
- NAT Gateway (associates with VM subnet)
- Azure Bastion (requires subnet and NSG)
- Private DNS Zone (requires VNet)
- Key Vault (generates and stores password)
3.**Phase 3: Storage** (Depends on Phase 2)
- Storage Account (with file share)
- Private Endpoint (requires storage account, VNet, DNS zone)
4.**Phase 4: Compute** (Depends on Phases 1-3)
- Virtual Machine (requires VNet, Key Vault secret, zone assignment)
5.**Phase 5: Monitoring** (Depends on Phase 4)
- Azure Monitor Alerts (require VM and Key Vault to be deployed)
## Parameter Data Model
```yaml
# Required Parametersparameters:
resourceGroupName: stringdescription: Name of the resource group for deploymentexample: rg-legacyvm-prodlocation: stringdescription: Azure region for deploymentdefault: westus3validation: Must be valid Azure regionvmSize: stringdescription: Virtual machine sizedefault: Standard_D2s_v3validation: Must support Windows Server 2016vmAdminUsername: stringdescription: VM administrator usernamedefault: vmadminminLength: 1maxLength: 20vmAdminPasswordSecretName: stringdescription: Name of Key Vault secret for VM admin passworddefault: vm-admin-passwordminLength: 1maxLength: 127availabilityZone: intdescription: Availability zone for zone-capable resourcesallowed: [1, 2, 3]
default: 1fileShareQuotaGiB: intdescription: File share quota in GiBdefault: 1024minValue: 100maxValue: 102400logAnalyticsRetentionDays: intdescription: Log Analytics data retention in daysdefault: 30minValue: 30maxValue: 730# Generated Values (not parameters)variables:
randomSuffix: uniqueString(resourceGroup().id)vmPassword: P@ssw0rd!{uniqueString(resourceGroup().id, deployment().name)}# Resource NamesvnetName: vnet-legacyvm-{randomSuffix}vmName: vm-legacyvm-{randomSuffix}storageAccountName: st{replace(randomSuffix, '-', '')}keyVaultName: kv-legacyvm-{randomSuffix}logAnalyticsName: law-legacyvm-{randomSuffix}```## Tags Model
All resources will be tagged with:
```yaml
tags:
workload: legacy-vmenvironment: productioncompliance: legacy-retentionmanagedBy: bicep-avmdeploymentDate: {deployment().timestamp}```## Security Model
### RBAC Assignments
| Principal | Role | Scope | Purpose |
|-----------|------|-------|---------|
| VM Managed Identity | Key Vault Secrets User | Key Vault | Read VM admin password |
| VM Managed Identity | Storage Blob Data Contributor | Storage Account | Access file share (future) |
### Network Security
| Source | Destination | Protocol/Port | Action | Purpose |
|--------|-------------|---------------|--------|---------|
| Internet | Bastion (443) | TCP/443 | Allow | Admin RDP access |
| Bastion | VM (3389) | TCP/3389 | Allow | RDP to VM |
| VM | Internet | Any | Allow | Outbound via NAT Gateway |
| VM | Storage PE (445) | TCP/445 | Allow | File share access |
| Any | VM | Any | Deny | No direct access to VM |
## Monitoring Data Model
### Diagnostic Settings Targets
All resources with diagnostic settings send to:
- **Primary**: Log Analytics Workspace
- **Categories**: All available log categories
- **Metrics**: All available metrics
### Alert Notification Model
- **Channel**: Azure Portal only
- **No Action Groups**: Alerts visible in portal alerts blade
- **Severity**: All set to Critical (Sev 0)
- **Auto-Mitigation**: Disabled (require manual acknowledgment)
<!-- markdownlint-disable --># Research: Legacy VM Workload AVM Modules
**Date**: 2026-01-27
**Feature**: [spec.md](../spec.md)
**Purpose**: Research and document AVM module selections, versions, and configuration approaches
## AVM Module Inventory
### Primary Infrastructure Modules
#### 1. Virtual Network
- **Module**: `avm/res/network/virtual-network`- **Latest Version**: 0.7.2
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/network/virtual-network/0.7.2/avm/res/network/virtual-network/README.md
- **Decision**: Use this module for VNet and subnet deployment
- **Rationale**: Official AVM module with built-in support for subnets, NSG assignments, NAT gateway association, and diagnostic settings
- **Key Parameters Needed**:
- Address space: 10.0.0.0/24
- Subnets: VM (10.0.0.0/27), Bastion (10.0.0.64/26), Private endpoint (10.0.0.128/27)
- NSG associations per subnet
- NAT gateway assignment to VM subnet
#### 2. Virtual Machine
- **Module**: `avm/res/compute/virtual-machine`- **Latest Version**: 0.21.0
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/compute/virtual-machine/0.21.0/avm/res/compute/virtual-machine/README.md
- **Decision**: Use this module for VM deployment
- **Rationale**: Comprehensive AVM module with built-in support for managed disks, managed identity, diagnostic settings, and guest configuration
- **Key Parameters Needed**:
- VM size: Standard_D2s_v3
- OS: Windows Server 2016
- Computer name: β€15 characters
- Admin username: vmadmin
- Admin password: Reference to Key Vault secret
- Managed identity: System-assigned
- Data disks: 500GB HDD
- Availability zone: 1-3 (parameter-driven)
- No public IP
#### 3. Azure Bastion
- **Module**: `avm/res/network/bastion-host`- **Latest Version**: 0.8.2
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/network/bastion-host/0.8.2/avm/res/network/bastion-host/README.md
- **Decision**: Use this module for bastion deployment
- **Rationale**: AVM module with built-in diagnostic settings and public IP creation
- **Key Parameters Needed**:
- Subnet: Bastion subnet (10.0.0.64/26)
- SKU: Basic (cost-effective for legacy workload)
- Diagnostic settings to Log Analytics
#### 4. Storage Account
- **Module**: `avm/res/storage/storage-account`- **Latest Version**: 0.31.0
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/storage/storage-account/0.31.0/avm/res/storage/storage-account/README.md
- **Decision**: Use this module for storage account and file share
- **Rationale**: Comprehensive AVM module with built-in file share, private endpoint, diagnostic settings, and network rules support
- **Key Parameters Needed**:
- SKU: Standard_LRS (HDD-based)
- File share quota: 1024 GiB
- Private endpoint enabled
- Public network access disabled
- Diagnostic settings to Log Analytics
#### 5. NAT Gateway
- **Module**: `avm/res/network/nat-gateway`- **Latest Version**: 2.0.1
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/network/nat-gateway/2.0.1/avm/res/network/nat-gateway/README.md
- **Decision**: Use this module for NAT gateway
- **Rationale**: AVM module with public IP creation and zone support
- **Key Parameters Needed**:
- Zone: parameter-driven (1-3)
- Public IP: Auto-created by module
#### 6. Network Security Group
- **Module**: `avm/res/network/network-security-group`- **Latest Version**: 0.5.2
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/network/network-security-group/0.5.2/avm/res/network/network-security-group/README.md
- **Decision**: Use this module for all three NSGs (VM subnet, bastion subnet, private endpoint subnet)
- **Rationale**: AVM module with built-in diagnostic settings and security rule definitions
- **Key Parameters Needed**:
- VM subnet NSG: Allow outbound to internet via NAT gateway, deny other traffic
- Bastion subnet NSG: Standard bastion rules (inbound 443, outbound to VM subnet)
- Private endpoint subnet NSG: Allow traffic from VM subnet only
#### 7. Key Vault
- **Module**: `avm/res/key-vault/vault`- **Latest Version**: 0.13.3
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/key-vault/vault/0.13.3/avm/res/key-vault/vault/README.md
- **Decision**: Use this module for Key Vault and secret storage
- **Rationale**: AVM module with built-in secret creation using `secrets` parameter array, RBAC support, diagnostic settings, and network rules
- **Key Features**:
- Supports `secrets` parameter for creating secrets at deployment time
- Can generate password using `uniqueString()` and store in secret
- Built-in RBAC assignments
- Private endpoint support (optional for this scenario)
- Diagnostic settings interface
- **Password Generation Approach**:
- Use Bicep `uniqueString()` function to generate complex password
- Combine multiple seed values for randomness
- Store in Key Vault secret via module's `secrets` parameter
- Reference secret in VM module
#### 8. Log Analytics Workspace
- **Module**: `avm/res/operational-insights/workspace`- **Latest Version**: 0.15.0
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/operational-insights/workspace/0.15.0/avm/res/operational-insights/workspace/README.md
- **Decision**: Use this module for Log Analytics
- **Rationale**: AVM module with retention configuration and solution deployment support
- **Key Parameters Needed**:
- Retention days: 30 (default assumption)
- SKU: PerGB2018
#### 9. Private Endpoint
- **Module**: `avm/res/network/private-endpoint`- **Latest Version**: 0.11.1
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/network/private-endpoint/0.11.1/avm/res/network/private-endpoint/README.md
- **Decision**: Use this module for storage account file share private endpoint
- **Rationale**: AVM module with built-in private DNS zone group configuration
- **Key Parameters Needed**:
- Service connection: Storage account file service
- Subnet: Private endpoint subnet
- Private DNS zone: privatelink.file.core.windows.net (manual creation)
#### 10. Azure Monitor Alerts
- **Module**: `avm/res/insights/metric-alert`- **Latest Version**: 0.4.1
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/insights/metric-alert/0.4.1/avm/res/insights/metric-alert/README.md
- **Decision**: Use this module for all three critical alerts
- **Rationale**: AVM module supporting metric-based alerts for VM and Key Vault
- **Alerts to Create**:
1. VM stopped/deallocated
2. Disk space > 85%
3. Key Vault access failures
- **Note**: Portal-only notifications (no action groups needed for this scenario)
### Supporting Modules
#### 11. Managed Disk
- **Included in VM Module**: The Virtual Machine module handles data disk creation inline
- **No separate module needed**: Data disks are specified as parameters to the VM module
#### 12. Private DNS Zone
- **Module**: `avm/res/network/private-dns-zone`- **Latest Version**: 0.8.0
- **Documentation**: https://github.com/Azure/bicep-registry-modules/tree/avm/res/network/private-dns-zone/0.8.0/avm/res/network/private-dns-zone/README.md
- **Decision**: Use this module for private DNS zone for file share private endpoint
- **Rationale**: Required for DNS resolution of storage account file share through private endpoint
- **Key Parameters Needed**:
- Zone name: privatelink.file.core.windows.net
- VNet link to main VNet
## Alternative Approaches Considered
### Alternative 1: Direct Resource Declarations
- **Approach**: Use direct Bicep resource declarations instead of AVM modules
- **Rejected**: Violates constitution principle II (AVM-Only Modules)
- **Trade-offs**: Would provide more control but lose benefits of tested, maintained, secure-by-default configurations
### Alternative 2: Pattern Module for VM Workloads
- **Approach**: Search for existing AVM pattern module combining VM, networking, and storage
- **Evaluated**: No suitable pattern module exists for this specific legacy VM scenario
- **Decision**: Compose solution from resource modules per constitution
### Alternative 3: Deployment Scripts for Password Generation
- **Approach**: Use Azure Deployment Scripts to generate and store VM password
- **Rejected**: User requirement specifies using uniqueString() and avoiding external helper scripts
- **Decision**: Generate password inline using Bicep uniqueString() function and store via Key Vault module's secrets parameter
### Alternative 4: Azure Backup Integration
- **Approach**: Include Azure Backup configuration for VM
- **Rejected**: Explicitly out of scope per specification
- **Note**: Can be added later if requirements change
## Bicep Language Features Required
### Password Generation Pattern
```bicep
// Generate complex password using uniqueString with multiple seedsvar generatedPassword = 'P@ssw0rd!${uniqueString(resourceGroup().id, deployment().name, utcNow('u'))}'```### Resource Dependency Management
- Let ARM manage dependencies automatically
- Explicit `dependsOn` only when implicit dependency isn't detected
- Use resource symbolic names for references
### Parameter Validation
- Use decorators: `@minLength()`, `@maxLength()`, `@allowed()`- Validate VM computer name length (β€15 chars)
- Validate storage account name (β€24 chars, lowercase, alphanumeric)
## Key Configuration Decisions
### Resource Naming
- **Pattern**: {resourceType}-{purpose}-{randomSuffix}
- **Random Suffix**: Use uniqueString() with 6 characters
- **Examples**:
- VNet: `vnet-legacyvm-${uniqueString(resourceGroup().id)}`- VM: `vm-legacyvm-${uniqueString(resourceGroup().id)}`- Storage: `st${replace(uniqueString(resourceGroup().id), '-', '')}` (no hyphens, β€24 chars)
- Key Vault: `kv-legacyvm-${uniqueString(resourceGroup().id)}`### Network Security
- **VM Subnet NSG**: Allow outbound internet (via NAT), deny all inbound except from bastion
- **Bastion Subnet NSG**: Follow Azure Bastion NSG requirements
- **Private Endpoint Subnet NSG**: Allow inbound from VM subnet on port 445 (SMB)
### Diagnostic Settings
- **Target**: Log Analytics Workspace (centralized)
- **Resources to Monitor**: VM, Key Vault, Storage Account, NSGs, Bastion
- **Log Categories**: All available categories
- **Metrics**: All available metrics
### Availability Zones
- **VM**: Deploy to zone specified by parameter (1, 2, or 3)
- **NAT Gateway**: Deploy to same zone as VM
- **Managed Disks**: Automatically zone-aligned with VM
## Implementation Notes
### Single Template Approach
- All resources in main.bicep
- No nested modules or separate Bicep files
- ARM dependency management handles deployment order
### Parameter Management
- All configurable values in main.bicepparam
- Rich comments explaining each parameter
- Default values where appropriate
- No hardcoded values in template
### Bicep CLI Version
- **Minimum**: Latest stable version (0.33.0 or higher at time of writing)
- **Recommendation**: Always use latest for newest AVM module support
- **Verification**: Run `bicep --version` before deployment
### Module Version Pinning
- **Required**: Always pin to specific versions (never 'latest' tag)
- **Format**: `br/public:avm/res/network/virtual-network:0.7.2`- **Maintenance**: Update versions explicitly when needed
## Open Questions Resolved
1.**How to generate VM password without external scripts?**- **Resolution**: Use Bicep `uniqueString()` function with multiple seeds
- **Implementation**: Store generated password in Key Vault using module's `secrets` parameter
2.**How to connect file share to VM?**- **Resolution**: Out of scope for initial deployment per user guidance
- **Future**: Will require VM extension or post-deployment script
3.**Should we use private endpoint for Key Vault?**- **Resolution**: No, not required for this legacy workload
- **Justification**: Adds complexity without clear benefit for single VM scenario
4.**What alert notification channels?**- **Resolution**: Portal notifications only (clarified during specification)
- **Implementation**: Create metric alerts without action groups
5.**Module version for optimal features?**- **Resolution**: Always use latest stable version listed in AVM metadata
- **Verification**: Confirmed all required features available in latest versions
## Next Steps
1. Create data-model.md with network topology and resource relationships
2. Write deployment quickstart guide
3. Fill implementation plan template
4. Create bicepconfig.json with module version analyzer
<!-- markdownlint-disable --># Quickstart: Deploy Legacy VM Workload
**Date**: 2026-01-27
**Feature**: [spec.md](../spec.md)
**Purpose**: Step-by-step deployment guide with validation and troubleshooting
## Prerequisites
### Required Tools
1.**Azure CLI** (v2.65.0 or later)
```powershell
# Check version
az --version
# Install/upgrade if needed
# Windows: Download from https://aka.ms/installazurecliwindows
# Or use winget
winget install -e --id Microsoft.AzureCLI
```
2.**Bicep CLI** (v0.33.0 or later)
```powershell
# Check version
az bicep version
# Install/upgrade
az bicep install
az bicep upgrade
```
3.**PowerShell** (v7.4 or later recommended)
```powershell
# Check version
$PSVersionTable.PSVersion
# Install if needed
winget install --id Microsoft.Powershell --source winget
```
### Azure Permissions
You need the following permissions on the target subscription:
- **Owner** or **Contributor** role at subscription or resource group level
- **User Access Administrator** role (if deploying RBAC assignments)
- Permissions to create resources in **westus3** region
### Authentication
```powershell
# Login to Azureaz login
# Set the target subscriptionaz account set --subscription "<subscription-id-or-name>"# Verify current contextaz account show --output table
```## Repository Structure
```
avm-workload/
βββ infra/
β βββ main.bicep # Main infrastructure template
β βββ main.bicepparam # Deployment parameters
β βββ bicepconfig.json # Bicep configuration
βββ specs/
β βββ 001-legacy-vm-workload/
β βββ spec.md # Feature specification
β βββ plan.md # Implementation plan
β βββ data-model.md # Architecture documentation
β βββ quickstart.md # This file
βββ .specify/
βββ memory/
βββ constitution.md # Governance framework
```## Deployment Workflow
### Step 1: Review Parameters
Edit `infra/main.bicepparam` to customize deployment:
```bicep
using'./main.bicep'// Required parametersparam vmSize = 'Standard_D2s_v3'param vmAdminUsername = 'vmadmin'param availabilityZone = 1
param fileShareQuotaGiB = 1024
param logAnalyticsRetentionDays = 30
// Optional: Override resource names// param vmName = 'vm-custom-name'// param vnetName = 'vnet-custom-name'```**Key Parameters**:
-`vmSize`: Virtual machine SKU (must support Windows Server 2016)
-`vmAdminUsername`: Administrator username for the VM
-`availabilityZone`: Availability zone (1, 2, or 3)
-`fileShareQuotaGiB`: Storage file share quota (default 1024 GiB)
-`logAnalyticsRetentionDays`: Log retention period (30-730 days)
### Step 2: Pre-Deployment Validation
#### 2.1 Bicep Compilation
Verify the template compiles without errors:
```powershell
# Navigate to infrastructure directorycd C:\SOURCE\avm-workload\infra
# Build Bicep templatebicep build main.bicep
# Check for warnings# Fix any warnings reported by the analyzer```**Expected Output**: `main.json` file created with no errors or warnings.
#### 2.2 Template Validation
Validate deployment against Azure:
```powershell
# Create resource group (if it doesn't exist)az group create `
--name rg-legacyvm-prod `
--location westus3
# Validate deploymentaz deployment group validate `
--resource-group rg-legacyvm-prod `
--template-file main.bicep `
--parameters main.bicepparam `
--verbose
# Check validation resultif ($LASTEXITCODE -eq0) {
Write-Host "β Validation passed" -ForegroundColor Green
} else {
Write-Host "β Validation failed - review errors above" -ForegroundColor Red
exit 1}
```**Expected Output**: `provisioningState: Succeeded`#### 2.3 What-If Analysis
Preview what resources will be created:
```powershell
# Run what-if analysisaz deployment group what-if `
--resource-group rg-legacyvm-prod `
--template-file main.bicep `
--parameters main.bicepparam `
--verbose
# Review output:# - Green (+): Resources to be created# - Yellow (~): Resources to be modified# - Red (x): Resources to be deleted# - White (=): No change```**Review Checklist**:
- [ ] 1 Virtual Network with 3 subnets
- [ ] 3 Network Security Groups
- [ ] 1 NAT Gateway with Public IP
- [ ] 1 Azure Bastion with Public IP
- [ ] 1 Key Vault with 1 secret
- [ ] 1 Storage Account with 1 file share
- [ ] 1 Private Endpoint
- [ ] 1 Private DNS Zone with VNet link
- [ ] 1 Virtual Machine with NIC, OS disk, data disk
- [ ] 1 Log Analytics Workspace
- [ ] 3 Metric Alerts
- [ ] Multiple diagnostic settings
- [ ] RBAC role assignments
**STOP**: Do not proceed if what-if shows unexpected resource deletions or modifications.
### Step 3: Deploy Infrastructure
#### 3.1 Execute Deployment
```powershell
# Deploy infrastructureaz deployment group create `
--name "legacyvm-$(Get-Date -Format 'yyyyMMdd-HHmmss')" `
--resource-group rg-legacyvm-prod `
--template-file main.bicep `
--parameters main.bicepparam `
--verbose
# Deployment typically takes 15-20 minutes# Monitor progress in Azure Portal: Resource Groups > rg-legacyvm-prod > Deployments```**Expected Duration**: 15-20 minutes
**Deployment Phases**:
1.**0-2 min**: Log Analytics, VNet, NSGs
2.**2-8 min**: NAT Gateway, Bastion, Private DNS Zone, Key Vault
3.**8-12 min**: Storage Account, Private Endpoint
4.**12-18 min**: Virtual Machine (longest phase)
5.**18-20 min**: Monitor Alerts
#### 3.2 Monitor Deployment
**Option A: Azure CLI**```powershell
# Watch deployment statusaz deployment group show `
--name "legacyvm-<timestamp>" `
--resource-group rg-legacyvm-prod `
--query "{State:properties.provisioningState, Duration:properties.duration}" `
--output table
```**Option B: Azure Portal**1. Navigate to: [Azure Portal](https://portal.azure.com)
2. Go to: **Resource Groups** > **rg-legacyvm-prod** > **Deployments**3. Click on the active deployment to see detailed progress
4. Monitor each resource deployment status
### Step 4: Post-Deployment Verification
#### 4.1 Verify Resources
```powershell
# List all resources in the resource groupaz resource list `
--resource-group rg-legacyvm-prod `
--output table
# Expected count: 20-25 resources# Key resources to verify:# - Virtual Machine# - Virtual Network# - Storage Account# - Key Vault# - Azure Bastion# - Log Analytics Workspace```#### 4.2 Test Bastion Connectivity
**Via Azure Portal**:
1. Go to: **Virtual Machines** > **vm-legacyvm-{random}**2. Click: **Connect** > **Bastion**3. Enter credentials:
- **Username**: `vmadmin`- **Password**: Get from Key Vault (see below)
4. Click: **Connect****Retrieve VM Password**:
```powershell
# Get Key Vault name$kvName = az keyvault list `
--resource-group rg-legacyvm-prod `
--query "[0].name" `
--output tsv
# Get VM admin password from Key Vaultaz keyvault secret show `
--name vm-admin-password `
--vault-name $kvName `
--query "value" `
--output tsv
```**Expected Result**: Successful RDP connection to Windows Server 2016 VM.
#### 4.3 Verify Logs in Log Analytics
```powershell
# Get Log Analytics workspace ID$workspaceId = az monitor log-analytics workspace show `
--resource-group rg-legacyvm-prod `
--workspace-name law-legacyvm-{random} `
--query "customerId" `
--output tsv
Write-Host "Log Analytics Workspace ID: $workspaceId"Write-Host "Portal: https://portal.azure.com#blade/Microsoft_Azure_Monitoring_Logs/LogsBlade/resourceId/%2Fsubscriptions%2F{subscription-id}%2FresourceGroups%2Frg-legacyvm-prod%2Fproviders%2FMicrosoft.OperationalInsights%2Fworkspaces%2Flaw-legacyvm-{random}"```**Via Azure Portal**:
1. Go to: **Log Analytics Workspaces** > **law-legacyvm-{random}**2. Click: **Logs**3. Run query to verify diagnostic logs:
```kusto
// Query 1: Verify VM activity logs
AzureActivity
| where ResourceGroup == "rg-legacyvm-prod"
| where ResourceType == "Microsoft.Compute/virtualMachines"
| summarize count() by OperationName
| order by count_ desc
// Query 2: Verify Key Vault audit logs
AzureDiagnostics
| where ResourceType == "VAULTS"
| where ResourceGroup == "rg-legacyvm-prod"
| summarize count() by OperationName, ResultType
| order by count_ desc
// Query 3: Verify Storage Account logs
StorageFileLogs
| where AccountName startswith "st"
| summarize count() by OperationName
| order by count_ desc
// Query 4: Check for any errors
AzureDiagnostics
| where ResourceGroup == "rg-legacyvm-prod"
| where Level == "Error"
| project TimeGenerated, ResourceType, OperationName, ResultDescription
| order by TimeGenerated desc
```**Expected Results**: Logs appearing for all resources within 5-10 minutes of deployment.
#### 4.4 Test Alerts
**Test 1: Disk Space Alert** (Optional - requires VM modification)
```powershell
# WARNING: This will consume disk space on the VM# Only run if you want to test alert firing# Connect to VM via Bastion, then run in VM:# fsutil file createnew C:\testfile.tmp 100000000000 # 100GB file# Wait 5-10 minutes for alert to fire# Check: Azure Portal > Monitor > Alerts```**Test 2: Key Vault Access Failure** (Safe test)
```powershell
# Attempt to get a non-existent secret (should generate access failure log)az keyvault secret show `
--name "non-existent-secret" `
--vault-name $kvName 2>$null
# Wait 5 minutes, then check:# Azure Portal > Monitor > Alerts > alert-kv-access-fail-legacyvm-{random}```**Expected Behavior**: Alerts visible in Azure Portal within 5-10 minutes of trigger condition.
#### 4.5 Verify Network Connectivity
**From VM (via Bastion RDP session)**:
```powershell
# Test internet connectivity via NAT GatewayTest-NetConnection -ComputerName google.com -Port 443# Test Azure DNS resolutionnslookup st{random}.file.core.windows.net
# Verify private endpoint resolutionnslookup st{random}.privatelink.file.core.windows.net
# Expected: Private IP from 10.0.0.128/27 range# Test file share access (future - after mapping)# net use Z: \\st{random}.file.core.windows.net\fileshare```**Expected Results**:
- Internet access works (NAT Gateway)
- Private endpoint resolves to internal IP (10.0.0.128/27)
- File share accessible from VM
## Troubleshooting
### Issue: Bicep Build Fails
**Symptoms**: `bicep build` reports errors or warnings
**Solutions**:
1.**Check Bicep CLI version**:
```powershell
az bicep version
# Should be v0.33.0 or later
az bicep upgrade
```
2.**Review analyzer warnings**:
- Open `main.bicep` in VS Code with Bicep extension
- Fix any red/yellow squiggles
- Common issues: outdated module versions, missing required parameters
3.**Validate bicepconfig.json**:
```powershell
# Ensure file exists and is valid JSON
Get-Content infra/bicepconfig.json | ConvertFrom-Json
```
### Issue: Validation Fails
**Symptoms**: `az deployment group validate` returns errors
**Common Errors**:
1.**"Resource provider not registered"**
```powershell
# Register required providers
az provider register --namespace Microsoft.Compute
az provider register --namespace Microsoft.Network
az provider register --namespace Microsoft.Storage
az provider register --namespace Microsoft.KeyVault
az provider register --namespace Microsoft.Insights
# Wait for registration to complete (2-5 minutes)
az provider show --namespace Microsoft.Compute --query "registrationState"
```
2.**"Quota exceeded"**
- Check Azure subscription quotas
- Request quota increase if needed: Portal > Subscriptions > Usage + quotas
3.**"Invalid parameter value"**
- Review `main.bicepparam` for typos
- Ensure `vmSize` is valid for westus3 region
- Verify availability zone is 1, 2, or 3
### Issue: Deployment Hangs or Times Out
**Symptoms**: Deployment runs longer than 30 minutes
**Diagnosis**:
```powershell
# Check deployment statusaz deployment group show `
--name "legacyvm-<timestamp>" `
--resource-group rg-legacyvm-prod `
--query "properties.{State:provisioningState, SubState:provisioningDetails}" `
--output json
# View deployment operationsaz deployment operation group list `
--resource-group rg-legacyvm-prod `
--name "legacyvm-<timestamp>" `
--query "[?properties.provisioningState=='Failed' || properties.provisioningState=='Running']" `
--output table
```**Solutions**:
1.**VM creation timeout**: May indicate VM extension failures
- Check: Portal > VM > Extensions and applications
- Solution: Redeploy with `--no-wait` flag, monitor separately
2.**Bastion timeout**: Check Public IP allocation
- Verify Public IP quota not exceeded
- Check NSG rules on Bastion subnet
3.**Private Endpoint timeout**: DNS propagation delay
- Wait additional 5-10 minutes
- Verify Private DNS Zone linked to VNet
### Issue: VM Password Not Working
**Symptoms**: Cannot connect to VM via Bastion with retrieved password
**Solutions**:
1.**Re-retrieve password from Key Vault**:
```powershell
$kvName = az keyvault list --resource-group rg-legacyvm-prod --query "[0].name" -o tsv
$password = az keyvault secret show --name vm-admin-password --vault-name $kvName --query "value" -o tsv
Write-Host "Password: $password"
```
2.**Check Key Vault access**:
```powershell
# Ensure you have Key Vault Secrets User role
az role assignment list `
--scope /subscriptions/{subscription-id}/resourceGroups/rg-legacyvm-prod/providers/Microsoft.KeyVault/vaults/$kvName ` --query "[?principalName=='<your-user-email>']" `
--output table
```
3.**Reset VM password** (if secret retrieval works but password is wrong):
```powershell
# This should not be necessary if deployment succeeded
# Only use as last resort
az vm user update `
--resource-group rg-legacyvm-prod ` --name vm-legacyvm-{random} `
--username vmadmin ` --password "NewP@ssw0rd!123"
```
### Issue: Bastion Connection Fails
**Symptoms**: Cannot establish Bastion RDP session
**Diagnosis**:
```powershell
# Check Bastion healthaz network bastion show `
--resource-group rg-legacyvm-prod `
--name bas-legacyvm-{random} `
--query "{ProvisioningState:provisioningState, DNSName:dnsName}" `
--output table
# Check VM statusaz vm get-instance-view `
--resource-group rg-legacyvm-prod `
--name vm-legacyvm-{random} `
--query "instanceView.statuses[?starts_with(code, 'PowerState/')].displayStatus" `
--output tsv
```**Solutions**:
1.**VM is stopped**: Start the VM
```powershell
az vm start --resource-group rg-legacyvm-prod --name vm-legacyvm-{random}
```
2.**Bastion NSG rules incorrect**: Verify Bastion subnet NSG
- Required: Allow inbound 443 from Internet
- Required: Allow outbound 3389/22 to VirtualNetwork
- Check: Portal > NSG > nsg-bastion-legacyvm-{random} > Security rules
3.**Browser issues**: Try different browser or incognito mode
### Issue: No Logs in Log Analytics
**Symptoms**: Queries return no results 10+ minutes after deployment
**Diagnosis**:
```kusto
// Check if workspace is receiving any data
Heartbeat
| where TimeGenerated > ago(1h)
| summarize count()
// Check diagnostic settings configuration
AzureDiagnostics
| where TimeGenerated > ago(1h)
| summarize count() by ResourceType
```**Solutions**:
1.**Wait longer**: Initial log ingestion can take 10-15 minutes
2.**Verify diagnostic settings**:
```powershell
# Check VM diagnostic settings
az monitor diagnostic-settings list `
--resource /subscriptions/{subscription-id}/resourceGroups/rg-legacyvm-prod/providers/Microsoft.Compute/virtualMachines/vm-legacyvm-{random} ` --query "value[].{Name:name, LogAnalytics:workspaceId}" `
--output table
```
3.**Manual diagnostic setting creation** (if missing):
- Portal > VM > Diagnostic settings > Add diagnostic setting
- Select all log categories and metrics
- Send to Log Analytics workspace: law-legacyvm-{random}
### Issue: Alerts Not Firing
**Symptoms**: Test conditions met but no alerts visible in Portal
**Diagnosis**:
```powershell
# Check alert rulesaz monitor metrics alert list `
--resource-group rg-legacyvm-prod `
--query "[].{Name:name, Enabled:enabled, Severity:severity}" `
--output table
# Check alert condition evaluationaz monitor metrics alert show `
--resource-group rg-legacyvm-prod `
--name alert-disk-space-legacyvm-{random} `
--query "{Enabled:enabled, Condition:criteria, State:properties.state}" `
--output json
```**Solutions**:
1.**Wait for evaluation window**: Alerts evaluate every 1-5 minutes
2.**Verify alert is enabled**: Should show `"enabled": true`3.**Check metric availability**:
```powershell
# List available metrics for VM
az monitor metrics list-definitions `
--resource /subscriptions/{subscription-id}/resourceGroups/rg-legacyvm-prod/providers/Microsoft.Compute/virtualMachines/vm-legacyvm-{random} ` --query "[].{Name:name.value, Unit:unit}" `
--output table
```
4.**Review activity log for alert evaluation**:
- Portal > Monitor > Activity Log
- Filter: Resource Type = "microsoft.insights/metricalerts"
- Look for "Evaluate Action" events
## Clean Up Resources
**WARNING**: This will delete ALL resources and data. Ensure you have backups before proceeding.
```powershell
# Delete resource group and all resourcesaz group delete `
--name rg-legacyvm-prod `
--yes `
--no-wait
# Verify deletion status (takes 5-10 minutes)az group exists --name rg-legacyvm-prod
# Expected output: false```**Cost Estimate**: Keeping resources deployed costs approximately:
- VM (Standard_D2s_v3): ~$70/month
- Storage (1TB file share + disks): ~$50/month
- Bastion: ~$140/month
- Other services (negligible): ~$10/month
- **Total**: ~$270/month in westus3 region
## Next Steps
After successful deployment:
1.**Configure VM**:
- Install required applications on Windows Server 2016
- Map file share as network drive: `\\st{random}.file.core.windows.net\fileshare`- Configure Windows Firewall rules as needed
2.**Set Up Monitoring**:
- Configure Log Analytics queries and save as functions
- Create custom workbooks in Azure Monitor
- Set up action groups for email/SMS notifications (currently Portal-only)
3.**Implement Backup** (not in scope of this deployment):
- Azure Backup for VM
- Azure Files snapshot/backup for file share
4.**Security Hardening** (additional measures):
- Enable Azure Security Center recommendations
- Implement Just-In-Time VM access
- Review and tighten NSG rules based on actual traffic
5.**Operational Procedures**:
- Document VM maintenance schedules
- Create runbooks for common tasks
- Establish change management process
## Support
For issues related to:
- **Bicep**: Review [research.md](./research.md) for module documentation
- **Azure resources**: Check [data-model.md](./data-model.md) for architecture
- **Requirements**: See [spec.md](./spec.md) for detailed specifications
- **Governance**: Review [constitution.md](../../.specify/memory/constitution.md) for principles
For Azure support, visit: https://azure.microsoft.com/support/
/speckit.plan Create a detailed plan for the spec. Build with the latest version of Terraform and the latest available version of each Azure Verified Module. Use the Terraform MCP server ("io.github.hashicorp/terraform-mcp-server") to find out what's the latest version of each module - install and configure this MCP server as needed. Do NOT use the "Bicep/list_avm_metadata" MCP tool!
Only include direct resource references in the Terraform solution template (root module) if no related AVM resource modules are available. If there is no Azure Verified Module available, use `Azure/azapi` resources or data sources for all control-plane resources and supported data-plane operations.
AzureRM may be used only under the [TFFR3](https://azure.github.io/Azure-Verified-Modules/spec/TFFR3) exception for a specific data-plane/non-ARM operation that AzAPI genuinely cannot implement. Every exceptional `azurerm_*` block must be scoped to that operation, pin AzureRM to `~> 4.0`, include the prescribed TFLint exclusion, document the AzAPI gap and upstream issue or pull request, and be replaced when AzAPI support ships.
Never use AzureRM for a control-plane resource or as a convenience fallback. Always use module interfaces for diagnostic settings, role assignments, resource locks, tags, managed identities, private endpoints, customer managed keys, etc.; use the related interface built into each resource module when available.
Do not create and reference local modules, or any other Terraform files. If a subset of the deployments fail, don't delete anything, just attempt redeploying the whole solution after fixing any bugs. Follow IaC best practices: define everything in a single root module using the standard module files of `main.tf`, `variables.tf`, `outputs.tf`, `terraform.tf`, and `terraform.tfvars`.
Always build Terraform explicit dependencies to determine order of deployment for each Azure resource, only use explicit dependencies with the `depends_on` meta-argument when it's not possible to otherwise determine the order of deployment. The Azure subscription ID will always be supplied as an env var or via az cli, it must not be exposed as a variable.
The subscription ID will be provided at deployment time via environment variable or az cli, it should not be exposed as a variable in the code.
When generating the admin password for the VM, use the secret feature built into the AVM Key Vault module. Leverage the random_password resource in the random provider to generate a new random password and do not use any external helper script (including deployment scripts) for generating the password. Provide this password to the VM module by referencing the Key vault secret that stores it. The solution template (root module) must first generate this password including a random, complex string, using the random_password Terraform resource, store it in Key Vault and then reference it for the VM to use it as admin password at deployment time. Ephemeral resources and write only attributes should be used for the password.
Don't connect the file share to the VM just yet - i.e., no need to extract storage keys or shared access signatures - we will do this later.
If implementing resource level locks, always use the built-in AVM "interface" for resource locks, instead of directly deploying the "Microsoft.Authorization/locks" resource.
Terraform solution template (root module) must validate without warnings or errors using the latest stable Terraform CLI version. Generate a warning when not the latest version of an AVM module is used. Before validating the solution template (root module) or attempting the first deployment, always fix all warnings or errors related to the AVM module versioning by updating to the latest available version of each module.
Always use snake case for Terraform HCL resource names, module names, variable names, output names, map keys, etc. Never shorten names, always use the full name. E.g. `network_security_group` instead of `nsg`, `virtual_machine` instead of `vm`, etc.
Ephemeral resources and write only attributes should be used for passwords.
β Expand to see the results
Notice how the plan step creates the plan.md file and a number of additional helper files. These may very depending on your prompts, the solution you are building, the version of Spec Kit and the LLM used. These typically include: data-model.md, research.md, quickstart.md and optional files in the contracts folder, such as outputs.md and parameters.md.
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
In the Copilot chat window, you should see results, similar to this:
<!-- markdownlint-disable --># Implementation Plan: Legacy Business Application Infrastructure
**Branch**: `001-my-legacy-workload` | **Date**: 2026-02-18 | **Spec**: [spec.md](./spec.md)
**Input**: Feature specification from `/specs/001-my-legacy-workload/spec.md`**Note**: This plan implements the `/speckit.plan` command workflow.
## Summary
Deploy a legacy Windows Server 2016 business application infrastructure using Terraform and Azure Verified Modules (AVM). The solution includes:
- **Core Compute**: Standard_D2s_v3 VM with Windows Server 2016, 500GB data disk, managed in isolated VNet
- **Network Security**: VNet (10.0.0.0/24) with 3 subnets, NSGs with deny-by-default rules, Azure Bastion for secure RDP
- **Storage**: 1TB Azure Files share accessible via private endpoint
- **Secrets Management**: Azure Key Vault storing VM admin password (generated with random_password resource)
- **Internet Access**: NAT Gateway for outbound-only connectivity
- **Observability**: Log Analytics (180-day retention) with diagnostic logging and critical alerts
**Technical Approach**: Single Terraform root module deploying all resources via AVM modules from Terraform Registry. No backup solution (infrastructure is disposable/recreatable). All configuration in terraform.tfvars per specification. VM password generated using random_password resource, stored in Key Vault via AVM module interface, then referenced by VM module.
## Technical Context
**Infrastructure Language**: Terraform >= 1.9.0 (latest stable as of 2026-02-18)
**Required Providers**:
-`Azure/azapi` ~> 2.12 (required for all direct Azure resource interactions)
-`hashicorp/azurerm` ~> 4.0 (required transitively by currently published AVM modules)
-`hashicorp/random` ~> 3.6 (for random_password and random_string resources)
**AVM Modules** (versions to be verified from Terraform Registry during Phase 0):
-`Azure/avm-res-resources-resourcegroup/azurerm` - Resource group
-`Azure/avm-res-network-virtualnetwork/azurerm` - VNet with 3 subnets
-`Azure/avm-res-network-networksecuritygroup/azurerm` - NSGs for each subnet
-`Azure/avm-res-compute-virtualmachine/azurerm` - Windows Server 2016 VM
-`Azure/avm-res-network-bastionhost/azurerm` - Azure Bastion
-`Azure/avm-res-keyvault-vault/azurerm` - Key Vault for secrets
-`Azure/avm-res-storage-storageaccount/azurerm` - Storage account with file share
-`Azure/avm-res-network-privateendpoint/azurerm` - Private endpoint (if not included in storage module)
-`Azure/avm-res-network-natgateway/azurerm` - NAT Gateway
-`Azure/avm-res-operationalinsights-workspace/azurerm` - Log Analytics Workspace
**Note**: Exact module names and latest versions must be verified from https://registry.terraform.io/namespaces/Azure during Phase 0 research. If no AVM module exists, use AzAPI directly. AzureRM is permitted only for a specific data-plane/non-ARM operation that AzAPI cannot implement, never for a control-plane resource.
**State Backend**: Azure Storage Account (pre-existing, not managed by this Terraform)
**State File**: `my-legacy-workload-prod.tfstate`**Target Region**: westus3
**Project Type**: Infrastructure-only (Terraform root module)
**Deployment Method**: Manual terraform apply via CLI (CI/CD pipeline optional for Phase 2)
**Security Tooling**: tfsec >= 1.28, checkov >= 3.0 (for static security analysis)
**Complexity**: 12 Azure resources via AVM modules, estimated ~300-400 lines of Terraform
**Estimated Monthly Cost**: <$200/month (per spec SC-013)
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*Based on `.specify/memory/constitution.md` version 1.0.0:
- [x]**Principle I**: All Azure resources defined in Terraform `.tf` files (no imperative scripts except justified)
- All 12 resources deployed via Terraform AVM modules
- No custom PowerShell/CLI scripts for resource deployment
- [x]**Principle II**: All modules sourced from Azure Verified Modules (AVM) Terraform Registry (`Azure/avm-*`)
- Zero custom/third-party modules
- All resources use official AVM modules where available
- Direct Azure resources use AzAPI only when no AVM module is available
- [x]**Principle III**: Security requirements met:
- [x] VM managed identity (system-assigned) configured via AVM module interface
- [x] VM password generated with random_password, stored in Key Vault via AVM secrets interface
- [x] NSGs with deny-by-default rules, explicit allow for RDP from Bastion only
- [x] Diagnostic settings enabled via AVM module diagnostic_settings interface
- [x] Encryption at rest (default Microsoft-managed keys)
- [x] Resource locks via AVM module lock interface
- [x] No secrets in .tf or .tfvars files (password generated at runtime, stored in Key Vault)
- [x]**Principle IV**: Single root module pattern (all resources in terraform/ directory root)
- terraform/main.tf contains all module instantiations
- No local child modules created
- Terraform dependency graph manages deployment order
- [x]**Principle V**: Deployment includes terraform validate and terraform plan review gates
- Validation workflow: init β fmt β validate β plan β review β apply
- Plan file (plan.tfplan) generated and reviewed before apply
- [x]**Deployment Standards**: Target region is `westus3`, naming convention followed (`<type>-avmlegacy-<suffix>`)
- All resources use location = var.location (default: "westus3")
- Naming via locals using random_string for uniqueness
- [x]**Project Constraints**: No HA/DR/scalability features added (legacy workload, cost-optimized)
- Single VM (no availability set, no load balancer)
- No backup policies (infrastructure disposable per clarification session)
- Standard/HDD tier for cost optimization
**Constitution Compliance**: β **PASSED** - All principles satisfied
## Project Structure
### Documentation (this feature)
```
specs/001-my-legacy-workload/
βββ spec.md # Feature specification (input)
βββ plan.md # This file (Phase 0-1 output)
βββ research.md # Phase 0 research findings (to be created)
βββ data-model.md # Phase 1 data model (infrastructure entities - to be created)
βββ quickstart.md # Phase 1 deployment guide (to be created)
βββ contracts/ # Phase 1 contracts (N/A for infrastructure, no external APIs)
βββ checklists/
β βββ requirements.md # Specification validation checklist (exists)
βββ tasks.md # Phase 2 task breakdown (created by /speckit.tasks command)
```### Source Code (repository root)
```
terraform/
βββ main.tf # Primary resource declarations and AVM module calls
βββ variables.tf # Input variable definitions with descriptions
βββ outputs.tf # Output value definitions for infrastructure details
βββ terraform.tf # Terraform version and provider configurations
βββ backend.tf # Remote state backend configuration (Azure Storage)
βββ locals.tf # Local value computations (naming, tags)
βββ prod.tfvars # Production environment variable values (this is the ONLY tfvars file)
βββ README.md # Terraform deployment instructions
docs/
βββ README.md # Project overview and setup instructions
βββ architecture.md # Infrastructure architecture diagram and design decisions
.github/
βββ workflows/
βββ terraform-validate.yml # CI/CD pipeline for validation (optional Phase 2)
.gitignore # Terraform-specific ignore patterns (.terraform/, *.tfstate, *.tfvars except prod.tfvars.example)
```**Structure Decision**: Selected Option 1 (Terraform Infrastructure). This is a pure infrastructure deployment with no application code. All Terraform files in `terraform/` directory at repository root. Single `prod.tfvars` file per spec requirement (no dev/test environments).
## Complexity Tracking
> **Note**: No constitution violations - this section documents architectural decisions only
| Decision | Rationale | Alternative Considered |
|----------|-----------|------------------------|
| No local Terraform modules | Per spec requirements and constitution, use AVM modules exclusively. Local modules only if AVM unavailable | Could create local modules for repeated patterns - rejected per spec FR-025 |
| Single tfvars file (prod.tfvars) | Spec requires production environment only (per clarification: no dev/test/staging) | Could use terraform workspaces - rejected per spec FR-024 |
| No backup automation | Per clarification session: infrastructure is disposable, recreatable from Terraform. No backup needed | Could add Azure Backup via AVM module - rejected per clarification |
| Minimal VNet (/24) | Per clarification session: cost-optimized, no growth expected for legacy workload | Could use /23 or larger - rejected for cost optimization |
| 1TB file share | Per clarification session: large capacity selected to avoid future expansion | Could use smaller quota (100GB-500GB) - rejected per user preference |
---
## Phase 0: Outline & Research
**Objective**: Resolve all "NEEDS CLARIFICATION" items from Technical Context and research AVM module capabilities
### Research Tasks
#### Task 1: Verify Latest Terraform Version
**Research**: Confirm Terraform stable version >= 1.9.0 available
**Method**: Check https://developer.hashicorp.com/terraform/downloads or run `terraform version`**Outputs**: Exact Terraform version constraint for terraform.tf
#### Task 2: Verify AzAPI Provider Version
**Research**: Confirm the latest AzAPI 2.x provider version compatible with AVM requirements
**Method**: Check https://registry.terraform.io/providers/Azure/azapi/latest and AVM module documentation
**Outputs**: Exact provider version constraint
#### Task 3: Research AVM Module Availability and Versions
**Research**: For each required Azure resource, identify:
1. Official AVM module name on Terraform Registry
2. Latest stable version (semantic versioning)
3. Module README documentation link
4. Key input variables and interfaces (diagnostic_settings, lock, managed_identities, private_endpoints, secrets)
**Method**: Visit https://registry.terraform.io/namespaces/Azure and search for:
-`avm-res-network-virtualnetwork`-`avm-res-network-networksecuritygroup`-`avm-res-compute-virtualmachine`-`avm-res-network-bastionhost`-`avm-res-keyvault-vault`-`avm-res-storage-storageaccount`-`avm-res-network-privateendpoint` (or check if storage module has built-in private endpoint interface)
-`avm-res-network-natgateway`-`avm-res-operationalinsights-workspace`- Insights/monitoring module for metric alerts (name TBD)
**Critical**: Verify each module supports:
-`diagnostic_settings` interface for Log Analytics integration
-`lock` interface for resource locks (CanNotDelete)
-`managed_identities` interface for system-assigned identity
-`secrets` interface (Key Vault module only) for storing random_password output
-`private_endpoints` interface (storage module) for private connectivity
**Outputs**: Populate `research.md` with findings:
```markdown
## AVM Module Research
### Module: avm-res-network-virtualnetwork
- **Registry Path**: Azure/avm-res-network-virtualnetwork/azurerm
- **Latest Version**: [VERSION] (verify from registry)
- **Documentation**: https://registry.terraform.io/modules/Azure/avm-res-network-virtualnetwork/azurerm/latest
- **Key Interfaces**:
- Subnets: Supports multiple subnet definitions with CIDR allocation
- NSG Association: [Check if built-in or separate]
- Diagnostic Settings: [Verify interface availability]
- **Variables Required for Spec**:
- address_space = ["10.0.0.0/24"]
- subnets = { vm = "10.0.0.0/27", bastion = "10.0.0.32/26", private_endpoint = "10.0.0.96/28" }
- location, resource_group_name, etc.
[Repeat for each module...]
```#### Task 4: Research NSG Rule Patterns
**Research**: Best practices for NSG rules in AVM network security group module:
- Deny-by-default posture
- Allow RDP (3389) from Bastion subnet to VM subnet
- Allow HTTPS (443) inbound to Bastion subnet (Azure Bastion requirement)
- Allow SMB (445) from VM subnet to Private Endpoint subnet
**Method**: Review AVM NSG module documentation for security_rules input structure
**Outputs**: Document NSG rule schema in research.md
#### Task 5: Research VM Password Flow with Key Vault
**Research**: Confirm workflow for generating password and storing in Key Vault via AVM:
1. Create random_password resource (length, complexity requirements)
2. Pass random_password.result to Key Vault AVM module's `secrets` interface
3. Reference Key Vault secret in VM AVM module's admin_password input
**Method**: Review AVM Key Vault module's `secrets` interface and VM module's authentication inputs
**Outputs**: Document password generation pattern in research.md
#### Task 6: Research Private Endpoint Integration
**Research**: Determine if storage account AVM module has built-in private endpoint interface or requires separate private endpoint module
**Method**: Check AVM storage account module documentation for `private_endpoints` input variable
**Outputs**: Decision in research.md - use built-in interface vs separate module
#### Task 7: Research Log Analytics Integration Patterns
**Research**: How to configure diagnostic settings for VM, Key Vault, Storage Account to send logs to Log Analytics
**Method**: Review each AVM module's `diagnostic_settings` interface structure
**Outputs**: Document diagnostic_settings input schema in research.md
#### Task 8: Research Alerting Approach
**Research**: AVM modules or direct AzAPI resources for metric alerts (VM stopped, disk >90%, Key Vault access failures)
**Method**: Check for AVM alerting/monitoring modules; if none exists, use AzAPI `Microsoft.Insights/metricAlerts`**Outputs**: Decision documented in research.md
### Research Consolidation
**Output**: `research.md` file with structure:
```markdown
# Research Findings: Legacy Business Application Infrastructure
## Decision Log
### Decision 1: Terraform Version
- **Chosen**: Terraform 1.9.x (latest stable)
- **Rationale**: Latest features, bug fixes, security patches
- **Alternatives Considered**: 1.8.x (stable but older), 1.10+ (if available, may have breaking changes)
### Decision 2: AVM Module Versions
- **Chosen**: Latest stable version for each module (semver ~> X.Y.0)
- **Rationale**: Latest features, security fixes, Azure API compatibility
- **Alternatives Considered**: Pin to specific patch versions (rejected - want latest patches)
[Continue for each research task...]
## Module Documentation Summary
### VNet Module
[Findings from Task 3...]
### NSG Module
[Findings from Task 3 and Task 4...]
[etc.]
```---
## Phase 1: Design & Contracts
**Prerequisites:**`research.md` complete with all module versions and interfaces documented
### Design Artifacts
#### 1. Data Model (Infrastructure Entities)
**Output**: `data-model.md````markdown
# Infrastructure Data Model: Legacy Business Application Infrastructure
## Entity Relationships
```βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Resource Group (rg-avmlegacy-wus3) β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Virtual Network (10.0.0.0/24) β β
β β ββ VM Subnet (10.0.0.0/27) β β
β β ββ Bastion Subnet (10.0.0.32/26) β β
β β ββ Private Endpoint Subnet (10.0.0.96/28) β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β β
β β β β β
β ββββββββββΌβββββ βββββΌβββββββ ββββββΌβββββββββ β
β β NSG (VM) β βNSG(Bastn)β βNSG(PrivEndpt)β β
β βββββββββββββββ ββββββββββββ ββββββββββββββββ β
β β β β
β ββββββββββΌββββββββββ β β
β β VM (Std_D2s_v3) β β β
β β - OS Disk βββββββββββ β β
β β - Data Disk β β β β
β βββββββββββββββββββ β β β
β β β β β
β β ββββββββ΄βββββββΌβββββββ β
β β β Key Vault β β
β β β - VM Admin Password β β
β βΌ βββββββββββββββββββββββ β
β ββββββββββββ β β
β β Bastion β β β
β β (RDP) β β β
β ββββββββββββ β β
β β β β
β ββββββββββΌββββββββββ β β
β β NAT Gateway β β β
β β (Outbound Only) β β β
β ββββββββββββββββββββ β β
β β β
β ββββββββββββββββββββββββββββ β β
β β Storage Account β β β
β β - File Share (1TB) β β β
β β - Private Endpoint βββββββΌβββ β
β ββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββ β
β β Log Analytics Workspace β β
β β - 180-day retention β β
β β - Diagnostic logs (VM, β β
β β Key Vault, Storage) β β
β β - Metric Alerts (3) β β
β ββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
## Core Entities
### 1. Resource Group
- **Name**: rg-avmlegacy-wus3
- **Location**: westus3
- **Lock**: CanNotDelete
- **Purpose**: Container for all infrastructure resources
### 2. Virtual Network
- **Name**: vnet-avmlegacy-{random}
- **Address Space**: 10.0.0.0/24
- **Subnets**:
- vm_subnet: 10.0.0.0/27 (30 usable IPs)
- AzureBastionSubnet: 10.0.0.32/26 (62 usable IPs, Azure requirement)
- private_endpoint_subnet: 10.0.0.96/28 (14 usable IPs)
- **Diagnostic Settings**: Enabled, logs to Log Analytics
### 3. Network Security Groups (3)
- **vm_nsg**:
- Inbound Rules: Allow RDP (3389) from AzureBastionSubnet CIDR
- Outbound Rules: Allow all (default), NAT Gateway handles internet access
- **bastion_nsg**:
- Inbound Rules: Allow HTTPS (443) from Internet (Azure Bastion requirement)
- Outbound Rules: Allow RDP (3389) to vm_subnet CIDR
- **private_endpoint_nsg**:
- Inbound Rules: Allow SMB (445) from vm_subnet CIDR
- Outbound Rules: Deny all (implicit)
### 4. Virtual Machine
- **Name**: vm-avmlegacy-{random} (ensure β€15 chars per spec)
- **Computer Name**: Derived from VM name, truncated to 15 chars if needed
- **Size**: Standard_D2s_v3
- **OS**: Windows Server 2016
- **OS Disk**: Standard HDD (127GB default)
- **Data Disk**: 500GB Standard HDD, LUN 0
- **Admin Username**: vmadmin
- **Admin Password**: Sourced from Key Vault secret (generated via random_password)
- **Managed Identity**: System-assigned
- **Availability Zone**: Zone 1 (or 2, 3 per requirement - never -1)
- **Diagnostic Settings**: Enabled, logs to Log Analytics
- **Lock**: CanNotDelete
### 5. Azure Bastion
- **Name**: bastion-avmlegacy-{random}
- **SKU**: Basic or Standard (verify cost in Phase 0)
- **Subnet**: AzureBastionSubnet (/26)
- **Public IP**: Managed by Bastion
- **Lock**: CanNotDelete
### 6. Key Vault
- **Name**: kv-avmlegacy-{random} (3-24 chars, globally unique)
- **SKU**: Standard
- **Soft Delete**: Enabled (90 days default)
- **Purge Protection**: Enabled
- **RBAC vs Access Policies**: Use RBAC (recommended for AVM)
- **Secrets**:
- vm-admin-password: Generated from random_password resource
- **Diagnostic Settings**: Enabled, logs to Log Analytics
- **Lock**: CanNotDelete
### 7. Storage Account
- **Name**: stavmlegacy{random} (3-24 chars, lowercase alphanumeric, globally unique)
- **SKU**: Standard_LRS
- **Kind**: StorageV2
- **File Share**:
- Name**: legacyappdata (or from tfvars)
- Quota**: 1024 GB (1TB)
- Tier**: TransactionOptimized (Standard)
- **Public Network Access**: Disabled
- **Private Endpoint**: Enabled, connected to private_endpoint_subnet
- **Diagnostic Settings**: Enabled, logs to Log Analytics
- **Lock**: CanNotDelete
### 8. Private Endpoint
- **Name**: pe-storage-avmlegacy-{random}
- **Subnet**: private_endpoint_subnet
- **Private DNS Integration**: Enabled (creates privatelink.file.core.windows.net DNS entry)
- **Sub-resource**: file (for Azure Files)
### 9. NAT Gateway
- **Name**: nat-avmlegacy-{random}
- **SKU**: Standard
- **Public IP**: Dedicated public IP for outbound traffic
- **Associated Subnets**: vm_subnet only
- **Idle Timeout**: 4 minutes (default)
### 10. Log Analytics Workspace
- **Name**: law-avmlegacy-{random}
- **SKU**: PerGB2018
- **Retention**: 180 days
- **Daily Cap**: None (or set based on cost constraints)
- **Diagnostic Log Sources**: VM, Key Vault, Storage Account
### 11. Metric Alerts (3)
- **VM Stopped Alert**:
- Metric**: VM Availability (or PowerState)
- Condition**: Threshold = 0 (stopped)
- Action Group**: (email/webhook TBD in tfvars)
- **VM Disk Usage Alert**:
- Metric**: Disk Space Used Percentage
- Condition**: Threshold > 90%
- Action Group**: (same as above)
- **Key Vault Access Failure Alert**:
- Metric**: Failed requests or Access denied events
- Condition**: Count > 0 over 5 minutes
- Action Group**: (same as above)
### 12. Supporting Resources
- **random_string**: Generate 6-character unique suffix for naming
- **random_password**: Generate VM admin password (16+ chars, complexity requirements)
## Terraform State Dependencies
Implicit dependency order (Terraform will resolve):
1. random_string, random_password (no dependencies)
2. Resource Group
3. Log Analytics Workspace (for diagnostic settings)
4. Key Vault β secrets (stores random_password)
5. VNet β Subnets
6. NSGs (reference VNet for associations)
7. NAT Gateway β Public IP
8. VM (references Key Vault secret, VNet subnet, NSG)
9. Bastion (references VNet Bastion subnet)
10. Storage Account β File Share β Private Endpoint
11. Diagnostic Settings (references Log Analytics, resources)
12. Metric Alerts (references resources, Log Analytics)
13. Resource Locks (references resources)
```#### 2. API Contracts
**Output**: N/A for infrastructure project (no external APIs to define)
#### 3. Quickstart Guide
**Output**: `quickstart.md````markdown
# Quickstart: Deploy Legacy Business Application Infrastructure
## Prerequisites
1.**Terraform CLI**: Version >= 1.9.0
```bash
terraform version
# Terraform v1.9.x
```
2.**Azure CLI**: Authenticated with sufficient permissions
```bash
az login
az account show
# Verify correct subscription
```
3.**Azure Subscription**: Contributor role on target subscription or resource group
4.**Terraform State Backend**: Pre-existing Azure Storage Account with container for state
- Storage Account name: `<your-state-storage>`- Container name: `tfstate`- SAS token or Storage Account Key
5.**Security Tools** (optional but recommended):
- tfsec >= 1.28
- checkov >= 3.0
## Setup Steps
### Step 1: Clone Repository and Navigate to Terraform Directory
```bash
git clone <repository-url>
cd <repository>/terraform
```### Step 2: Configure Backend
Create `backend.hcl` file (not committed to git):
```hcl
storage_account_name ="<your-state-storage>"container_name ="tfstate"key ="my-legacy-workload-prod.tfstate"resource_group_name ="<state-storage-resource-group>"```### Step 3: Review and Customize prod.tfvars
Edit `prod.tfvars` to customize deployment:
```hcl
# Required variables
location ="westus3"workload_name ="avmlegacy"environment ="prod"vm_admin_secret_name ="vm-admin-password" # Key Vault secret name
# Optional overrides (defaults provided in variables.tf)
vm_size ="Standard_D2s_v3"vm_data_disk_size_gb =500file_share_quota_gb =1024log_analytics_retention_days =180availability_zone =1 # or 2, 3 - never -1
# Alert action group (email/webhook)
alert_action_group_email ="admin@example.com"```### Step 4: Initialize Terraform
```bash
terraform init -backend-config=backend.hcl
```Expected output:
```
Terraform has been successfully initialized!
```### Step 5: Format and Validate
```bash
terraform fmt -recursive
terraform validate
```Expected output:
```
Success! The configuration is valid.
```### Step 6: Run Security Scans (Optional)
```bash
tfsec .
checkov -d .
```Fix any HIGH or CRITICAL findings before proceeding.
### Step 7: Plan Deployment
```bash
terraform plan -var-file=prod.tfvars -out=plan.tfplan
```**Review the plan carefully**:
- Verify 12-15 resources to be created (exact count depends on AVM module resource expansion)
- Check resource names match naming convention
- Verify no unexpected deletions or replacements
- Confirm all resources deploying to westus3
### Step 8: Apply Deployment
```bash
terraform apply plan.tfplan
```Deployment takes approximately 20-30 minutes. Progress:
1. Resource Group, Log Analytics (1-2 min)
2. VNet, NSGs, Key Vault (3-5 min)
3. Storage Account, Private Endpoint (5-7 min)
4. NAT Gateway, Bastion (10-15 min - Bastion is slowest)
5. VM (7-10 min)
6. Diagnostic Settings, Alerts, Locks (2-3 min)
### Step 9: Verify Deployment
```bash
# Get outputsterraform output
# Expected outputs:# resource_group_name = "rg-avmlegacy-wus3"# vm_name = "vm-avmlegacy-a1b2c3"# key_vault_name = "kv-avmlegacy-a1b2c3"# storage_account_name = "stavmlegacya1b2c3"# log_analytics_workspace_id = "/subscriptions/..."```Check Azure Portal:
1. Navigate to Resource Group `rg-avmlegacy-wus3`2. Verify VM is running
3. Test Bastion connection (Connect β Bastion)
4. Retrieve password from Key Vault secret
5. Verify Log Analytics has diagnostic logs
## Post-Deployment
### Connect to VM via Bastion
1. Azure Portal β Virtual Machines β `vm-avmlegacy-...`2. Click "Connect" β "Bastion"
3. Username: `vmadmin`4. Password: Retrieve from Key Vault:
```bash
az keyvault secret show --name vm-admin-password --vault-name <kv-name> --query value -o tsv
```
5. Click "Connect"
### Mount Azure Files Share
From within the VM (via Bastion RDP session):
```powershell
# Get storage account name from terraform output$storageAccountName = "<storage-account-name>"$fileShareName = "legacyappdata"# Note: Authentication via private endpoint - no key needed for mounted drive# Access share via UNC path using private endpoint IP or FQDNnet use Z: \\$storageAccountName.privatelink.file.core.windows.net\$fileShareName
```### Verify Internet Connectivity
```powershell
# From VMInvoke-WebRequest -Uri "https://www.microsoft.com" -UseBasicParsing
# Should succeed via NAT Gateway```### Check Diagnostic Logs
Azure Portal β Log Analytics Workspace β Logs:
```kusto
// VM metrics
Perf
| where Computer startswith "vm-avmlegacy"
| where TimeGenerated > ago(1h)
| take 10
// Key Vault access logs
AzureDiagnostics
| where ResourceType == "VAULTS"
| where TimeGenerated > ago(1h)
| take 10
```## Troubleshooting
### Issue: Terraform init fails with backend authentication error
**Solution**: Verify backend.hcl credentials and ensure storage account allows access from your IP
### Issue: VM creation fails with quota error
**Solution**: Check Azure subscription quotas for Standard_D2s_v3 in westus3 region
### Issue: Bastion deployment times out
**Solution**: Bastion can take 15-20 minutes. If timeout occurs, run `terraform apply` again (idempotent)
### Issue: Cannot connect via Bastion
**Solution**: Verify NSG rules allow RDP from Bastion subnet. Check VM is running. Verify password from Key Vault.
### Issue: File share inaccessible from VM
**Solution**: Verify private endpoint deployed correctly. Check NSG allows SMB (445) from VM subnet. Verify private DNS resolution.
## Cleanup
**Warning**: This destroys all infrastructure. Ensure data is backed up if needed (though per spec, infrastructure is disposable).
```bash
terraform destroy -var-file=prod.tfvars
```Confirm with `yes` when prompted.
**Note**: Some resources (Key Vault with purge protection) may enter soft-delete state and require manual purge after 90 days.
```
#### 4. Agent Context Update
**Output**: Run agent context update script (if applicable for Copilot context files)
```bash
# Run from repository root
./.specify/scripts/powershell/update-agent-context.ps1 -AgentType copilot
```This updates .github/copilot-instructions.md or similar with:
- Terraform/AVM technology stack
- westus3 region
- Constitution principles
- Preserves manual additions between markers
#### 5. Re-evaluate Constitution Check
**Post-Design Validation**: Review design artifacts against constitution:
- [x]**Principle I**: All resources in Terraform (data-model.md documents 12 resources via AVM modules)
- [x]**Principle II**: Only AVM modules used (no custom modules in design)
- [x]**Principle III**: Security controls documented in data-model.md (NSGs, Key Vault, managed identity, diagnostic logging, locks)
- [x]**Principle IV**: Single root module structure documented in project structure
- [x]**Principle V**: Quickstart.md documents validation workflow (init β fmt β validate β plan β apply)
**Constitution Compliance Post-Design**: β **MAINTAINED**---
## Terraform Code Structure
### File: terraform.tf
```hcl
# Terraform and Provider Configuration
# Constitution Principle I & V: Use latest stable Terraform and AzAPI provider
terraform {
required_version = ">=1.9.0"required_providers {
azurerm = {
source ="hashicorp/azurerm" version ="~> 4.0" }
azapi = {
source ="Azure/azapi" version ="~> 2.12" }
random = {
source ="hashicorp/random" version ="~> 3.6" }
} # Backend configuration - parameterized via backend.hcl
backend"azurerm" { # Configured via: terraform init -backend-config=backend.hcl
# backend.hcl contains:
# storage_account_name = "..."
# container_name = "tfstate"
# key = "my-legacy-workload-prod.tfstate"
# resource_group_name = "..."
}
}
provider"azapi" {
enable_preflight =true}
provider"azurerm" {
features {}
}
provider"random" {}
```### File: variables.tf
```hcl
# Input Variables for Legacy Business Application Infrastructure
# Constitution Principle I: All configurable values in terraform.tfvars
# Required Variables
variable"location" {
description ="Azure region for all resources. Per constitution: westus3" type =string default ="westus3"validation {
condition = var.location =="westus3" error_message ="Per constitution IC-001, all resources must deploy to westus3." }
}
variable"workload_name" {
description ="Workload identifier for naming convention. Per constitution: avmlegacy" type =string default ="avmlegacy"}
variable"environment" {
description ="Environment name. Per spec: prod only" type =string default ="prod"validation {
condition = var.environment =="prod" error_message ="Per spec FR-024, only production environment is deployed." }
}# VM Configuration
variable"vm_size" {
description ="Azure VM SKU. Per clarification: Standard_D2s_v3" type =string default ="Standard_D2s_v3"}
variable"vm_admin_username" {
description ="VM administrator username. Per spec FR-005: vmadmin" type =string default ="vmadmin"validation {
condition = var.vm_admin_username =="vmadmin" error_message ="Per spec FR-005, VM admin username must be vmadmin." }
}
variable"vm_admin_secret_name" {
description ="Key Vault secret name for VM admin password. Per spec FR-016: configurable" type =string default ="vm-admin-password"}
variable"vm_data_disk_size_gb" {
description ="VM data disk size in GB. Per spec FR-003: 500GB" type =number default =500validation {
condition = var.vm_data_disk_size_gb ==500 error_message ="Per spec FR-003, VM data disk must be 500GB." }
}
variable"availability_zone" {
description ="Availability zone for VM. Per spec FR-023: 1, 2, or 3 (never -1)" type =number default =1validation {
condition =contains([1, 2, 3], var.availability_zone)
error_message ="Per spec FR-023 and IC-006, availability zone must be 1, 2, or 3." }
}# Network Configuration
variable"vnet_address_space" {
description ="VNet address space. Per clarification: 10.0.0.0/24" type =list(string)
default = ["10.0.0.0/24"]
validation {
condition = length(var.vnet_address_space) == 1 && var.vnet_address_space[0] =="10.0.0.0/24" error_message ="Per clarification, VNet must use 10.0.0.0/24 address space." }
}
variable"vm_subnet_cidr" {
description ="VM subnet CIDR. Per clarification: 10.0.0.0/27" type =string default ="10.0.0.0/27"}
variable"bastion_subnet_cidr" {
description ="Bastion subnet CIDR. Per clarification: 10.0.0.32/26 (Azure requires /26 minimum)" type =string default ="10.0.0.32/26"}
variable"private_endpoint_subnet_cidr" {
description ="Private Endpoint subnet CIDR. Per clarification: 10.0.0.96/28" type =string default ="10.0.0.96/28"}# Storage Configuration
variable"file_share_name" {
description ="Azure Files share name" type =string default ="legacyappdata"}
variable"file_share_quota_gb" {
description ="File share quota in GB. Per clarification: 1024GB (1TB)" type =number default =1024validation {
condition = var.file_share_quota_gb ==1024 error_message ="Per clarification, file share quota must be 1TB (1024GB)." }
}# Observability Configuration
variable"log_analytics_retention_days" {
description ="Log Analytics retention in days. Per clarification: 180 days" type =number default =180validation {
condition = var.log_analytics_retention_days ==180 error_message ="Per clarification, Log Analytics retention must be 180 days." }
}
variable"alert_action_group_email" {
description ="Email address for alert notification action group" type =string # No default - must be provided in tfvars
}# Tags
variable"tags" {
description ="Common tags for all resources" type =map(string)
default = {
Environment ="Production" Workload ="Legacy Business Application" ManagedBy ="Terraform" CostCenter ="IT-Infrastructure" }
}
```### File: locals.tf
```hcl
# Local Values for Computed Names and Configurations
# Constitution Principle: Naming convention <type>-<workload>-<suffix>
locals { # Generate unique suffix for globally unique names
unique_suffix =random_string.unique_suffix.result # Location abbreviation
location_abbr ="wus3" # westus3
# Naming per constitution IC-003
resource_group_name ="rg-${var.workload_name}-${var.environment}-${local.location_abbr}" vnet_name ="vnet-${var.workload_name}-${local.unique_suffix}" vm_nsg_name ="nsg-vm-${var.workload_name}-${local.unique_suffix}" bastion_nsg_name ="nsg-bastion-${var.workload_name}-${local.unique_suffix}" private_endpoint_nsg_name ="nsg-pe-${var.workload_name}-${local.unique_suffix}" # VM name must be β€15 chars for computer name (Windows NetBIOS limit per spec FR-004)
vm_name_raw ="vm-${var.workload_name}-${local.unique_suffix}" vm_name =substr(local.vm_name_raw, 0, min(length(local.vm_name_raw), 15))
vm_computer_name =local.vm_name # Same as VM name, truncated to 15 chars
bastion_name ="bastion-${var.workload_name}-${local.unique_suffix}" key_vault_name ="kv-${var.workload_name}-${local.unique_suffix}" # Storage account name: lowercase alphanumeric only, max 24 chars
storage_account_name ="st${var.workload_name}${local.unique_suffix}" # e.g., "stavmlegacya1b2c3" private_endpoint_name ="pe-storage-${var.workload_name}-${local.unique_suffix}" nat_gateway_name ="nat-${var.workload_name}-${local.unique_suffix}" nat_public_ip_name ="pip-nat-${var.workload_name}-${local.unique_suffix}" law_name ="law-${var.workload_name}-${local.unique_suffix}" action_group_name ="ag-${var.workload_name}-${local.unique_suffix}" # Subnet names
vm_subnet_name ="vm-subnet" bastion_subnet_name ="AzureBastionSubnet" # Azure requirement: exact name
private_endpoint_subnet_name ="private-endpoint-subnet" # Common tags
common_tags =merge(
var.tags,
{
DeployedBy ="Terraform" Region =var.location Spec ="001-my-legacy-workload" }
)
}
```### File: main.tf
```hcl
#############################################################################
# Legacy Business Application Infrastructure - Main Configuration
# Constitution Compliance: All principles I-V enforced
# Spec: 001-my-legacy-workload
#############################################################################
# Random Resources for Naming
resource"random_string" "unique_suffix" {
length =6 special =false upper =false numeric =true}# Per spec: Generate VM admin password using random_password
# This will be stored in Key Vault via AVM module interface
resource"random_password" "vm_admin_password" {
length =24 special =true min_lower =2 min_upper =2 min_numeric =2 min_special =2 override_special = "!@#$%^&*()-_=+[]{}|;:,.<>?"}#############################################################################
# Resource Group
# Constitution IC-005: Single resource group for all resources
#############################################################################
module"resource_group" {
source ="Azure/avm-res-resources-resourcegroup/azurerm" version ="~> 0.2" name =local.resource_group_name location =var.location tags =local.common_tags lock = {
kind ="CanNotDelete" name ="rg-lock-do-not-delete" }
}#############################################################################
# Log Analytics Workspace
# Spec FR-018: Log Analytics for centralized logging
# Created early for diagnostic settings on other resources
#############################################################################
module"log_analytics" {
source ="Azure/avm-res-operationalinsights-workspace/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION from Terraform Registry
name =local.law_name resource_group_name =module.resource_group.name location =var.location # Per clarification: 180-day retention
sku ="PerGB2018" retention_in_days =var.log_analytics_retention_days daily_quota_gb =-1 # No daily cap (or set based on cost requirements)
tags =local.common_tags # Lock interface (if supported by AVM module)
lock = {
kind ="CanNotDelete" name ="law-lock-do-not-delete" }
}#############################################################################
# Virtual Network
# Spec FR-007: VNet with 3 subnets
# Constitution IC-008: 10.0.0.0/24 with specific CIDR allocations
#############################################################################
module"virtual_network" {
source ="Azure/avm-res-network-virtualnetwork/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.vnet_name resource_group_name =module.resource_group.name location =var.location address_space =var.vnet_address_space # Define 3 subnets per spec FR-007
subnets = {
vm_subnet = {
name =local.vm_subnet_name address_prefixes = [var.vm_subnet_cidr]
network_security_group_resource_id =module.vm_nsg.resource_id }
bastion_subnet = {
name =local.bastion_subnet_name # Must be exact name per Azure requirement
address_prefixes = [var.bastion_subnet_cidr]
network_security_group_resource_id =module.bastion_nsg.resource_id }
private_endpoint_subnet = {
name =local.private_endpoint_subnet_name address_prefixes = [var.private_endpoint_subnet_cidr]
network_security_group_resource_id =module.private_endpoint_nsg.resource_id # Per spec IC-009: Disable network policies for private endpoints
private_endpoint_network_policies_enabled =false }
}
tags =local.common_tags # Diagnostic settings - Constitution SEC-010
diagnostic_settings = {
law_diag = {
name ="vnet-diagnostics" workspace_resource_id =module.log_analytics.resource_id # Enable all log categories and metrics (check module documentation for exact syntax)
}
} # Lock interface
lock = {
kind ="CanNotDelete" name ="vnet-lock-do-not-delete" }
}#############################################################################
# Network Security Groups
# Spec FR-008: NSGs with deny-by-default posture
# Constitution SEC-004: Explicit allow rules only
#############################################################################
# VM Subnet NSG
module"vm_nsg" {
source ="Azure/avm-res-network-networksecuritygroup/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.vm_nsg_name resource_group_name =module.resource_group.name location =var.location # Spec FR-009: Allow RDP from Bastion subnet only
security_rules = [
{
name ="Allow-RDP-From-Bastion" priority =100 direction ="Inbound" access ="Allow" protocol ="Tcp" source_port_range ="*" destination_port_range ="3389" source_address_prefix =var.bastion_subnet_cidr destination_address_prefix =var.vm_subnet_cidr description ="Allow RDP from Bastion subnet per spec FR-009" },
{
name ="Deny-All-Inbound" priority =4096 direction ="Inbound" access ="Deny" protocol ="*" source_port_range ="*" destination_port_range ="*" source_address_prefix ="*" destination_address_prefix ="*" description ="Explicit deny-by-default per constitution SEC-004" }
]
tags =local.common_tags diagnostic_settings = {
law_diag = {
name ="nsg-vm-diagnostics" workspace_resource_id =module.log_analytics.resource_id }
}
}# Bastion Subnet NSG
module"bastion_nsg" {
source ="Azure/avm-res-network-networksecuritygroup/azurerm" version ="~> 0.1.0" name =local.bastion_nsg_name resource_group_name =module.resource_group.name location =var.location # Bastion NSG rules per Azure Bastion requirements
# See: https://learn.microsoft.com/azure/bastion/bastion-nsg
security_rules = [
{
name ="Allow-HTTPS-Inbound" priority =100 direction ="Inbound" access ="Allow" protocol ="Tcp" source_port_range ="*" destination_port_range ="443" source_address_prefix ="Internet" destination_address_prefix ="*" description ="Allow HTTPS from Internet per Azure Bastion requirement" },
{
name ="Allow-GatewayManager-Inbound" priority =110 direction ="Inbound" access ="Allow" protocol ="Tcp" source_port_range ="*" destination_port_range ="443" source_address_prefix ="GatewayManager" destination_address_prefix ="*" description ="Allow Azure Bastion control plane" },
{
name ="Allow-RDP-To-VM-Subnet" priority =100 direction ="Outbound" access ="Allow" protocol ="Tcp" source_port_range ="*" destination_port_range ="3389" source_address_prefix ="*" destination_address_prefix =var.vm_subnet_cidr description ="Allow RDP to VM subnet per spec SEC-006" },
{
name ="Allow-AzureCloud-Outbound" priority =110 direction ="Outbound" access ="Allow" protocol ="Tcp" source_port_range ="*" destination_port_range ="443" source_address_prefix ="*" destination_address_prefix ="AzureCloud" description ="Allow Bastion to Azure services" }
]
tags =local.common_tags diagnostic_settings = {
law_diag = {
name ="nsg-bastion-diagnostics" workspace_resource_id =module.log_analytics.resource_id }
}
}# Private Endpoint Subnet NSG
module"private_endpoint_nsg" {
source ="Azure/avm-res-network-networksecuritygroup/azurerm" version ="~> 0.1.0" name =local.private_endpoint_nsg_name resource_group_name =module.resource_group.name location =var.location # Spec SEC-007: Allow SMB from VM subnet
security_rules = [
{
name ="Allow-SMB-From-VM-Subnet" priority =100 direction ="Inbound" access ="Allow" protocol ="Tcp" source_port_range ="*" destination_port_range ="445" source_address_prefix =var.vm_subnet_cidr destination_address_prefix =var.private_endpoint_subnet_cidr description ="Allow SMB from VM subnet per spec SEC-007" },
{
name ="Deny-All-Inbound" priority =4096 direction ="Inbound" access ="Deny" protocol ="*" source_port_range ="*" destination_port_range ="*" source_address_prefix ="*" destination_address_prefix ="*" description ="Explicit deny-by-default" }
]
tags =local.common_tags diagnostic_settings = {
law_diag = {
name ="nsg-pe-diagnostics" workspace_resource_id =module.log_analytics.resource_id }
}
}#############################################################################
# NAT Gateway
# Spec FR-012: NAT Gateway for outbound internet access
#############################################################################
module"nat_gateway" {
source ="Azure/avm-res-network-natgateway/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.nat_gateway_name resource_group_name =module.resource_group.name location =var.location # Public IP for outbound traffic
public_ip_addresses = [
{
name =local.nat_public_ip_name zones = [var.availability_zone] # Match VM availability zone per best practice
}
] # Associate with VM subnet
subnet_associations = [
{
subnet_id =module.virtual_network.subnets["vm_subnet"].id }
]
tags =local.common_tags}#############################################################################
# Key Vault
# Spec FR-015: Key Vault for VM admin password
# Constitution SEC-002: Store secrets in Key Vault
#############################################################################
data"azapi_client_config" "current" {}
module"key_vault" {
source ="Azure/avm-res-keyvault-vault/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.key_vault_name resource_group_name =module.resource_group.name location =var.location tenant_id =data.azapi_client_config.current.tenant_id sku_name ="standard" soft_delete_retention_days =90 purge_protection_enabled =true # Per spec SEC-012
# Use RBAC authorization (recommended over access policies)
enable_rbac_authorization =true # Per spec FR-006 & FR-016: Store VM admin password as secret
# AVM secrets interface (check module documentation for exact syntax)
secrets = {
vm_admin_password = {
name =var.vm_admin_secret_name value =random_password.vm_admin_password.result # Optionally set expiration, content_type, etc.
}
}
tags =local.common_tags # Diagnostic settings - Constitution SEC-010
diagnostic_settings = {
law_diag = {
name ="kv-diagnostics" workspace_resource_id =module.log_analytics.resource_id }
} # Lock - Constitution SEC-011
lock = {
kind ="CanNotDelete" name ="kv-lock-do-not-delete" }
role_assignments = {
deployment_identity_secrets_officer = {
role_definition_id_or_name ="Key Vault Secrets Officer" principal_id =data.azapi_client_config.current.object_id }
}
depends_on = [random_password.vm_admin_password]
}#############################################################################
# Storage Account with File Share
# Spec FR-013: Storage account with Azure Files
# Spec FR-014: Private endpoint access only
#############################################################################
module"storage_account" {
source ="Azure/avm-res-storage-storageaccount/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.storage_account_name resource_group_name =module.resource_group.name location =var.location account_kind ="StorageV2" account_tier ="Standard" # HDD per spec IC-007
account_replication_type ="LRS" # No geo-redundancy per constitution IC-004
# Per spec SEC-009: Disable public network access
public_network_access_enabled =false # Encryption per spec SEC-013
enable_infrastructure_encryption =true # File share configuration
file_shares = {
legacy_app_data = {
name =var.file_share_name quota =var.file_share_quota_gb tier ="TransactionOptimized" # Standard tier
}
} # Private endpoint configuration (if supported by module interface)
private_endpoints = {
file_endpoint = {
name =local.private_endpoint_name subnet_resource_id =module.virtual_network.subnets["private_endpoint_subnet"].id subresource_names = ["file"] # For Azure Files
private_dns_zone_group_name ="file-private-dns" # Private DNS zone integration (auto-created or existing)
private_dns_zone_resource_ids = [] # Or specify existing zone
}
}
tags =local.common_tags # Diagnostic settings
diagnostic_settings = {
law_diag = {
name ="storage-diagnostics" workspace_resource_id =module.log_analytics.resource_id }
} # Lock
lock = {
kind ="CanNotDelete" name ="storage-lock-do-not-delete" }
}#############################################################################
# Azure Bastion
# Spec FR-010: Azure Bastion for secure RDP access
#############################################################################
module"bastion" {
source ="Azure/avm-res-network-bastionhost/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.bastion_name resource_group_name =module.resource_group.name location =var.location # Bastion subnet (must be exact name "AzureBastionSubnet")
subnet_id =module.virtual_network.subnets["bastion_subnet"].id # SKU: Basic or Standard (check cost implications)
sku ="Basic" # Or "Standard"foradditionalfeatures # Public IP managed by Bastion module
# (AVM module typically creates this automatically)
tags =local.common_tags # Lock
lock = {
kind ="CanNotDelete" name ="bastion-lock-do-not-delete" }
}#############################################################################
# Virtual Machine
# Spec FR-001: Windows Server 2016 VM with Standard_D2s_v3
#############################################################################
module"virtual_machine" {
source ="Azure/avm-res-compute-virtualmachine/azurerm" version ="~> 0.1.0" # VERIFY LATEST VERSION
name =local.vm_name # Truncated to 15 chars
resource_group_name =module.resource_group.name location =var.location # Per spec FR-004: Computer name (NetBIOS) β€15 chars
computer_name =local.vm_computer_name # Per clarification: Standard_D2s_v3
vm_size =var.vm_size # Per spec IC-006: Availability zone 1, 2, or 3 (never -1)
zone =var.availability_zone # Windows Server 2016 image
os_profile = {
windows = {
admin_username =var.vm_admin_username # Reference password from Key Vault secret
admin_password =module.key_vault.secrets[var.vm_admin_secret_name].value }
}
source_image_reference = {
publisher ="MicrosoftWindowsServer" offer ="WindowsServer" sku ="2016-Datacenter" version ="latest" } # Network configuration
network_interfaces = {
nic1 = {
name ="${local.vm_name}-nic" ip_configurations = {
ipconfig1 = {
name ="ipconfig1" subnet_id =module.virtual_network.subnets["vm_subnet"].id private_ip_address_allocation ="Dynamic" # Per spec FR-011: No public IP
public_ip_address_id =null }
}
}
} # OS disk: Standard HDD per spec FR-002
os_disk = {
name ="${local.vm_name}-osdisk" caching ="ReadWrite" storage_account_type ="Standard_LRS" # Standard HDD
disk_size_gb =127 # Default Windows Server size
} # Data disk: 500GB Standard HDD per spec FR-003
data_disks = {
data1 = {
name ="${local.vm_name}-datadisk" lun =0 caching ="ReadWrite" storage_account_type ="Standard_LRS" disk_size_gb =var.vm_data_disk_size_gb }
} # Per constitution SEC-001: System-assigned managed identity
managed_identities = {
system_assigned =true }
tags =local.common_tags # Diagnostic settings - Constitution SEC-010
diagnostic_settings = {
law_diag = {
name ="vm-diagnostics" workspace_resource_id =module.log_analytics.resource_id }
} # Lock - Constitution SEC-011
lock = {
kind ="CanNotDelete" name ="vm-lock-do-not-delete" }
depends_on = [module.key_vault]
}#############################################################################
# Monitoring and Alerts
# Spec FR-020: Critical alerts for VM stopped, disk usage, Key Vault access
#############################################################################
# Action Group for Alert Notifications
resource"azapi_resource" "action_group" {
type ="Microsoft.Insights/actionGroups@2023-01-01" name =local.action_group_name parent_id =module.resource_group.resource_id location ="global" tags =local.common_tags body = {
properties = {
enabled =true groupShortName ="avmalerts" emailReceivers = [
{
name ="admin-email" emailAddress =var.alert_action_group_email useCommonAlertSchema =true }
]
}
}
response_export_values = []
}# Alert 1: VM Stopped/Deallocated
resource"azapi_resource" "vm_stopped_metric_alert" {
type ="Microsoft.Insights/metricAlerts@2018-03-01" name ="alert-vm-stopped-${local.vm_name}" parent_id =module.resource_group.resource_id location ="global" tags =local.common_tags body = {
properties = {
description ="Alert when VM is stopped or deallocated" severity =0 enabled =true scopes = [module.virtual_machine.resource_id]
evaluationFrequency ="PT5M" windowSize ="PT5M" criteria = {
"odata.type" ="Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria" allOf = [
{
name ="vm_availability" criterionType ="StaticThresholdCriterion" metricNamespace ="Microsoft.Compute/virtualMachines" metricName ="VmAvailabilityMetric" operator ="LessThan" threshold =1 timeAggregation ="Average" }
]
}
actions = [{ actionGroupId =azapi_resource.action_group.id }]
}
}
response_export_values = []
}# Alert 2: VM Disk Usage >90%
resource"azapi_resource" "vm_disk_usage_metric_alert" {
type ="Microsoft.Insights/metricAlerts@2018-03-01" name ="alert-vm-disk-usage-${local.vm_name}" parent_id =module.resource_group.resource_id location ="global" tags =local.common_tags body = {
properties = {
description ="Alert when VM disk usage exceeds 90%" severity =0 enabled =true scopes = [module.virtual_machine.resource_id]
evaluationFrequency ="PT15M" windowSize ="PT15M" criteria = {
"odata.type" ="Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria" allOf = [
{
name ="vm_disk_usage" criterionType ="StaticThresholdCriterion" metricNamespace ="Microsoft.Compute/virtualMachines" metricName ="OS Disk Used Percent" operator ="GreaterThan" threshold =90 timeAggregation ="Average" }
]
}
actions = [{ actionGroupId =azapi_resource.action_group.id }]
}
}
response_export_values = []
}# Alert 3: Key Vault Access Failures
resource"azapi_resource" "key_vault_access_failures_metric_alert" {
type ="Microsoft.Insights/metricAlerts@2018-03-01" name ="alert-kv-access-failures-${local.key_vault_name}" parent_id =module.resource_group.resource_id location ="global" tags =local.common_tags body = {
properties = {
description ="Alert when Key Vault access failures occur" severity =0 enabled =true scopes = [module.key_vault.resource_id]
evaluationFrequency ="PT5M" windowSize ="PT5M" criteria = {
"odata.type" ="Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria" allOf = [
{
name ="key_vault_access_failures" criterionType ="StaticThresholdCriterion" metricNamespace ="Microsoft.KeyVault/vaults" metricName ="ServiceApiResult" operator ="GreaterThan" threshold =0 timeAggregation ="Count" dimensions = [
{
name ="StatusCode" operator ="Include" values = ["403"]
}
]
}
]
}
actions = [{ actionGroupId =azapi_resource.action_group.id }]
}
}
response_export_values = []
}#############################################################################
# Note: File share mount to VM will be implemented in a later phase
# Per instructions: "Don't connect the file share to the VM just yet"
#############################################################################
```### File: outputs.tf
```hcl
# Outputs for Legacy Business Application Infrastructure
# These values can be used by external modules or for manual reference
output"resource_group_name" {
description ="Name of the resource group containing all resources" value =module.resource_group.name}
output"resource_group_id" {
description ="ID of the resource group" value =module.resource_group.resource_id}
output"virtual_network_name" {
description ="Name of the virtual network" value =module.virtual_network.name}
output"virtual_network_id" {
description ="ID of the virtual network" value =module.virtual_network.resource_id}
output"vm_name" {
description ="Name of the virtual machine" value =module.virtual_machine.name}
output"vm_id" {
description ="ID of the virtual machine" value =module.virtual_machine.resource_id}
output"vm_private_ip_address" {
description ="Private IP address of the VM" value =module.virtual_machine.network_interfaces["nic1"].ip_configurations["ipconfig1"].private_ip_address}
output"vm_computer_name" {
description ="Computer name (NetBIOS name) of the VM" value =local.vm_computer_name}
output"key_vault_name" {
description ="Name of the Key Vault" value =module.key_vault.name}
output"key_vault_id" {
description ="ID of the Key Vault" value =module.key_vault.resource_id}
output"key_vault_uri" {
description ="URI of the Key Vault" value =module.key_vault.vault_uri}
output"vm_admin_secret_name" {
description ="Name of the Key Vault secret containing VM admin password" value =var.vm_admin_secret_name sensitive =true}
output"storage_account_name" {
description ="Name of the storage account" value =module.storage_account.name}
output"storage_account_id" {
description ="ID of the storage account" value =module.storage_account.resource_id}
output"file_share_name" {
description ="Name of the Azure Files share" value =var.file_share_name}
output"bastion_name" {
description ="Name of the Azure Bastion host" value =module.bastion.name}
output"bastion_id" {
description ="ID of the Azure Bastion host" value =module.bastion.resource_id}
output"log_analytics_workspace_name" {
description ="Name of the Log Analytics workspace" value =module.log_analytics.name}
output"log_analytics_workspace_id" {
description ="ID of the Log Analytics workspace" value =module.log_analytics.resource_id}
output"nat_gateway_name" {
description ="Name of the NAT Gateway" value =module.nat_gateway.name}
output"nat_gateway_public_ip" {
description ="Public IP address of the NAT Gateway" value =module.nat_gateway.public_ip_addresses[0].ip_address}# Sensitive outputs - use with caution
output"vm_admin_password" {
description ="VM administrator password (retrieve from Key Vault instead)" value =random_password.vm_admin_password.result sensitive =true}# Instructions for accessing resources
output"bastion_connect_instructions" {
description ="Instructions for connecting to VM via Bastion" value =<<-EOT1. NavigatetoAzurePortal2. GotoVirtualMachines->${module.virtual_machine.name}3. Click"Connect" -> "Bastion"4. Username:${var.vm_admin_username}5. Password:RetrievefromKeyVaultsecret"${var.vm_admin_secret_name}"Command:azkeyvaultsecretshow--name${var.vm_admin_secret_name}--vault-name${module.key_vault.name}--queryvalue-otsvEOT}
output"file_share_mount_instructions" {
description ="Instructions for mounting Azure Files share from VM" value =<<-EOTFromwithintheVM (viaBastionRDP):1. OpenPowerShellasAdministrator2. Run:netuseZ:\\${module.storage_account.name}.privatelink.file.core.windows.net\${var.file_share_name}3. Verify:dirZ:Note:Authenticationviaprivateendpoint-nostoragekeyneededformounteddriveEOT}
```### File: prod.tfvars
```hcl
# Production Environment Configuration
# Legacy Business Application Infrastructure
#
# Per spec FR-021: All configurable values in this file (not hardcoded in main.tf)
# Per spec FR-022: Rich comments explaining purpose
#############################################################################
# Core Configuration
#############################################################################
# Azure region for all resources
# Per constitution IC-001: Must be westus3
location ="westus3"# Workload identifier for resource naming
# Per constitution: avmlegacy for legacy workload
workload_name ="avmlegacy"# Environment name
# Per spec FR-024: Production only (no dev/test/staging)
environment ="prod"#############################################################################
# Virtual Machine Configuration
#############################################################################
# VM size/SKU
# Per clarification: Standard_D2s_v3 (2 cores, 8GB RAM)
vm_size ="Standard_D2s_v3"# VM administrator username
# Per spec FR-005: Must be "vmadmin"
vm_admin_username ="vmadmin"# Key Vault secret name for VM admin password
# Per spec FR-016: Configurable via this variable
# Password will be automatically generated and stored in Key Vault
vm_admin_secret_name ="vm-admin-password"# VM data disk size in GB
# Per spec FR-003: Must be 500GB HDD
vm_data_disk_size_gb =500# Availability zone for VM
# Per spec FR-023: Must be 1, 2, or 3 (never -1)
# Choose based on region availability
availability_zone =1#############################################################################
# Network Configuration
#############################################################################
# Virtual network address space
# Per clarification: 10.0.0.0/24 (minimal allocation, cost-optimized)
vnet_add_space = ["10.0.0.0/24"]# VM subnet CIDR
# Per clarification: 10.0.0.0/27 (30 usable IPs)
vm_subnet_cidr ="10.0.0.0/27"# Bastion subnet CIDR
# Per clarification: 10.0.0.32/26 (62 usable IPs, Azure /26 minimum requirement)
bastion_subnet_cidr ="10.0.0.32/26"# Private Endpoint subnet CIDR
# Per clarification: 10.0.0.96/28 (14 usable IPs, sufficient for storage private endpoint)
private_endpoint_subnet_cidr ="10.0.0.96/28"#############################################################################
# Storage Configuration
#############################################################################
# Azure Files share name
# Default: legacyappdata
# Change if specific naming required by legacy application
file_share_name ="legacyappdata"# File share provisioned capacity in GB
# Per clarification: 1024GB (1TB) for large capacity and growth
file_share_quota_gb =1024#############################################################################
# Observability Configuration
#############################################################################
# Log Analytics retention period in days
# Per clarification: 180 days for extended compliance coverage
log_analytics_retention_days =180# Email address for alert notifications
# **REQUIRED**: Update with actual administrator email
# Receives critical alerts for VM stopped, disk >90%, Key Vault access failures
alert_action_group_email ="admin@example.com" # β οΈ UPDATE THIS
#############################################################################
# Resource Tags
#############################################################################
# Common tags applied to all resources
# Add additional cost center, project, owner tags as needed
tags = {
Environment ="Production" Workload ="Legacy Business Application" ManagedBy ="Terraform" CostCenter ="IT-Infrastructure" Compliance ="Required" DeployedBy ="Infrastructure Team" DeployedDate ="2026-02-18" Spec ="001-my-legacy-workload"}#############################################################################
# Notes
#############################################################################
# 1. Per clarification: No backup solution (infrastructure is disposable/recreatable from Terraform)
# 2. Per constitution: Single production environment only (no dev/test)
# 3. Per spec: All resources in westus3 region, single resource group
# 4. Per spec: VM password auto-generated, stored in Key Vault, not in this file
# 5. File share not yet mounted to VM - will be configured in later phase
#############################################################################
```---
## Summary
Implementation plan complete with:
β **Phase 0 Research**: Documented tasks for verifying Terraform/provider versions and researching 10 AVM modules
β **Phase 1 Design**: Created data-model.md structure, quickstart guide, and agent context update approach
β **Terraform Code**: Complete root module with 5 files (terraform.tf, variables.tf, locals.tf, main.tf, outputs.tf, prod.tfvars)
β **Constitution Compliance**: All 5 principles validated pre and post-design
β **Security**: VM password via random_password β Key Vault β VM reference flow, NSGs, diagnostic logging, resource locks
β **Spec Compliance**: All 25 functional requirements addressed in code structure
**Next Steps**:
1. Execute Phase 0 research to verify exact AVM module versions from Terraform Registry
2. Run `/speckit.tasks` to generate detailed task breakdown for implementation
3. Begin implementation with terraform init and validation workflow
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture the changes in your project, with a comment of something like Plan created.
5. Checklist (Optional)
Spec Kit uses /speckit.checklist to validate the requirements. The prompt doesn’t require any specific inputs as it analyzes the existing plan for gaps.
Info
To learn more about the checklist step, see the Checklist chapter in the Spec Kit article.
Run the following prompt to generate checklist items for our example:
/speckit.checklist
β Expand to see the results
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
When running the checklist prompt, Copilot may ask you a number of depth questions to clarify certain aspects of the plan. Here’s an example of what that looks like. You can answer in the following format, e.g.: Q1: E, Q2:A, Q3:A
In the Copilot chat window, you should see results, similar to this:
<!-- markdownlint-disable --># Implementation Plan Quality Validation Checklist
**Purpose**: Validate quality, completeness, and clarity of implementation plan and supporting documentation
**Created**: 2026-01-27
**Scope**: Comprehensive review across functional, security, network, and monitoring requirements
**Depth**: Standard (~40 items)
**Feature**: [spec.md](../spec.md) | [plan.md](../plan.md)
---
## Requirement Completeness
Requirements documentation coverage and thoroughness.
- [ ] CHK001 - Are VM compute requirements (CPU, memory, disk) explicitly specified with exact values? [Completeness, Spec Β§FR-001]
- [ ] CHK002 - Are all three network subnet ranges defined with CIDR notation and purpose documented? [Completeness, Spec Β§FR-003]
- [ ] CHK003 - Are storage account requirements specified for both file share quota and performance tier? [Completeness, Spec Β§FR-005]
- [ ] CHK004 - Are availability zone requirements documented with explicit valid range (1-3, never -1)? [Completeness, Spec Β§FR-014]
- [ ] CHK005 - Are diagnostic logging requirements defined for all resource types requiring monitoring? [Completeness, Spec Β§SEC-001]
- [ ] CHK006 - Are all 12 AVM modules documented with exact version numbers and purpose statements? [Completeness, Plan Β§Technical Context]
- [ ] CHK007 - Are deployment sequence phases defined with resource dependencies explicitly stated? [Completeness, Data-Model Β§Deployment Sequence]
- [ ] CHK008 - Are NSG security rules specified for all three subnets with protocol, port, and direction details? [Completeness, Data-Model Β§NSG Configuration]
## Requirement Clarity
Specificity and measurability of requirements to eliminate ambiguity.
- [ ] CHK009 - Is "Standard HDD" quantified with specific Azure SKU names (e.g., StandardSSD_LRS)? [Clarity, Spec Β§FR-001, FR-002]
- [ ] CHK010 - Is "minimal naming" defined with exact pattern format and character count range? [Clarity, Constitution Β§V, Plan Β§Technical Context]
- [ ] CHK011 - Are alert thresholds specified with exact percentage values and evaluation windows? [Clarity, Spec Β§MON-004, Data-Model Β§Alert Configuration]
- [ ] CHK012 - Is "secure remote access" quantified with specific protocol (RDP), port, and authentication method? [Clarity, Spec Β§FR-004]
- [ ] CHK013 - Are "least-privilege NSG rules" defined with concrete allow/deny examples per subnet? [Clarity, Spec Β§SEC-003]
- [ ] CHK014 - Is "deployment within 20 minutes" defined as a measurable success criterion with verification method? [Measurability, Spec Β§SC-001]
- [ ] CHK015 - Is password generation approach explicitly defined with uniqueString() seed sources documented? [Clarity, Research Β§Password Generation]
- [ ] CHK016 - Are resource name length constraints specified with Azure limits (e.g., Storage 24 chars, VM NetBIOS 15 chars)? [Clarity, Spec Β§FR-010, Data-Model Β§Resource Names]
## Requirement Consistency
Alignment and non-contradiction across specification, plan, and supporting documents.
- [ ] CHK017 - Do VM sizing requirements in spec match the data model configuration (Standard_D2s_v3 consistently specified)? [Consistency, Spec Β§FR-001, Data-Model Β§VM Config]
- [ ] CHK018 - Do network CIDR blocks in spec align with data model subnet allocations (10.0.0.0/24 breakdown)? [Consistency, Spec Β§FR-003, Data-Model Β§Network Topology]
- [ ] CHK019 - Do AVM module versions in plan match research document module selections (all 12 modules)? [Consistency, Plan Β§AVM Modules, Research Β§Module Inventory]
- [ ] CHK020 - Do alert requirements in spec match alert configuration in data model (3 critical alerts)? [Consistency, Spec Β§MON-003-005, Data-Model Β§Alerts]
- [ ] CHK021 - Do diagnostic logging requirements align across SEC-001 (spec) and technical context (plan)? [Consistency, Spec Β§SEC-001, Plan Β§Security Baseline]
- [ ] CHK022 - Does naming convention in constitution match implementation in data model? [Consistency, Constitution Β§V, Data-Model Β§Naming Model]
- [ ] CHK023 - Do deployment phases in plan align with dependency graph in data model? [Consistency, Plan Β§Phase 3, Data-Model Β§Deployment Sequence]
## Acceptance Criteria Quality
Measurability and testability of success criteria.
- [ ] CHK024 - Are all 11 success criteria (SC-001 to SC-011) objectively measurable with pass/fail conditions? [Measurability, Spec Β§Success Criteria]
- [ ] CHK025 - Can VM accessibility (SC-004) be verified through documented test procedure in quickstart? [Testability, Spec Β§SC-004, Quickstart Β§4.2]
- [ ] CHK026 - Can NSG rule effectiveness (SC-009) be validated with concrete test scenarios? [Testability, Spec Β§SC-009]
- [ ] CHK027 - Can Log Analytics ingestion (SC-007) be verified within specified 5-minute timeframe? [Measurability, Spec Β§SC-007]
- [ ] CHK028 - Are constitution compliance gates (all 6 principles) verifiable with documented evidence? [Measurability, Plan Β§Constitution Check]
## Scenario Coverage
Completeness of primary, alternate, error, recovery, and non-functional scenarios.
- [ ] CHK029 - Are all five user stories independently testable as documented in spec? [Coverage, Primary Flows, Spec Β§User Scenarios]
- [ ] CHK030 - Are VM computer name length violations (>15 chars) addressed with edge case handling? [Coverage, Edge Case, Spec Β§Edge Cases]
- [ ] CHK031 - Are storage account naming violations (>24 chars, invalid chars) documented as edge cases? [Coverage, Edge Case, Spec Β§Edge Cases]
- [ ] CHK032 - Are private endpoint deployment failures with successful storage account handled? [Coverage, Exception Flow, Spec Β§Edge Cases]
- [ ] CHK033 - Are Key Vault secret access failures monitored with alert configuration? [Coverage, Exception Flow, Spec Β§MON-005]
- [ ] CHK034 - Are availability zone validation requirements (1-3 only, never -1) enforced? [Coverage, Edge Case, Spec Β§FR-014]
- [ ] CHK035 - Are performance requirements addressed for standard HDD selection rationale? [Coverage, Non-Functional, Research Β§Storage Module]
## Edge Case Coverage
Boundary conditions, error states, and exceptional scenarios.
- [ ] CHK036 - Are requirements defined for zero-subnet scenarios or invalid CIDR blocks? [Gap, Edge Case]
- [ ] CHK037 - Are rollback requirements defined if VM deployment succeeds but Key Vault secret creation fails? [Gap, Recovery Flow]
- [ ] CHK038 - Are concurrent deployment conflict scenarios (multiple simultaneous deployments) addressed? [Gap, Edge Case]
- [ ] CHK039 - Are requirements specified for when Log Analytics workspace is unavailable during resource deployment? [Gap, Exception Flow]
## Dependencies & Assumptions
External dependencies, prerequisites, and assumption documentation.
- [ ] CHK040 - Are all Azure resource provider registration requirements documented as prerequisites? [Dependency, Quickstart Β§Prerequisites]
- [ ] CHK041 - Are subscription quota requirements validated as documented assumptions? [Assumption, Spec Β§Assumptions]
- [ ] CHK042 - Are tool version requirements (Bicep 0.33.0+, Azure CLI 2.65.0+) specified with verification commands? [Dependency, Plan Β§Technical Context, Quickstart Β§Prerequisites]
- [ ] CHK043 - Are required Azure permissions documented with specific role names? [Dependency, Quickstart Β§Prerequisites]
- [ ] CHK044 - Is the assumption about Windows Server 2016 image availability in westus3 validated? [Assumption, Spec Β§Assumptions]
## Traceability
Linkage between requirements, specifications, and implementation artifacts.
- [ ] CHK045 - Do all functional requirements (FR-001 to FR-016) have corresponding implementation guidance in plan phases? [Traceability]
- [ ] CHK046 - Do all security requirements (SEC-001 to SEC-008) map to specific AVM module configurations in research? [Traceability]
- [ ] CHK047 - Do all monitoring requirements (MON-001 to MON-005) trace to alert definitions in data model? [Traceability]
- [ ] CHK048 - Do all infrastructure constraints (IC-001 to IC-006) align with constitution principles? [Traceability]
## Ambiguities & Conflicts
Identification of unclear, contradictory, or incomplete requirement areas.
- [ ] CHK049 - Is "HDD-backed file share" disambiguated between Standard_LRS vs other HDD SKUs? [Ambiguity, Spec Β§FR-005]
- [ ] CHK050 - Is "Portal notifications only" for alerts clearly documented as excluding Action Groups? [Clarity, Spec Β§MON-003]
- [ ] CHK051 - Is the deployment timeframe "within 20 minutes" inclusive of validation steps or deployment only? [Ambiguity, Spec Β§SC-001]
- [ ] CHK052 - Are "rich comments" requirements quantified with minimum comment density or coverage percentage? [Ambiguity, Spec Β§FR-015]
---
## Validation Summary
**Total Items**: 52
**Pass Threshold**: β₯90% (47+ items checked)
**Review Date**: _________________**Reviewer**: _________________**Status**: β PASSED | β NEEDS REVISION | β BLOCKED
### Issues Identified
_Document any requirement quality issues discovered during validation:_1.
2.
3.
### Recommendations
_Suggested improvements for requirement clarity, completeness, or testability:_1.
2.
3.
---
**Next Steps**:
- If PASSED β Proceed to Phase 2 implementation (Bicep template creation)
- If NEEDS REVISION β Address identified issues, re-validate
- If BLOCKED β Escalate missing information to stakeholders
/speckit.checklist
β Expand to see the results
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
When running the checklist prompt, Copilot may ask you a number of depth questions to clarify certain aspects of the plan. Here’s an example of what that looks like.
In the Copilot chat window, you should see results, similar to this:
# Requirements Quality Checklist: Implementation Readiness
**Type**: Implementation Readiness Validation
**Focus**: Comprehensive Coverage
**Depth**: Standard
**Audience**: Implementation Team
**Created**: 2026-02-18
**Spec**: [001-my-legacy-workload](../spec.md)
**Plan**: [plan.md](../plan.md)
**Purpose**: Validate that requirements provide complete, clear, and consistent guidance for Terraform implementation using Azure Verified Modules. This checklist tests requirement quality, NOT implementation correctness.
---
## Requirement Completeness
### Infrastructure Resources
- [ ] CHK001 - Are AVM module references specified for all required Azure resources? [Completeness, Spec Infrastructure Requirements]
- [ ] CHK002 - Are resource naming requirements defined with specific patterns and constraints? [Completeness, Spec IC-003, IC-010]
- [ ] CHK003 - Are all resource configuration requirements specified (SKUs, tiers, capacity)? [Completeness, Spec FR-001 through FR-025]
- [ ] CHK004 - Are provider version constraints documented for AzAPI, published AVM dependencies, and random, with direct AzureRM resources explicitly excluded? [Completeness, Plan Technical Context]
- [ ] CHK005 - Are all 12 Azure resources accounted for in both spec and plan? [Completeness, Cross-reference]
### Terraform-Specific Requirements
- [ ] CHK006 - Are requirements defined for all 5 Terraform files (terraform.tf, variables.tf, main.tf, outputs.tf, tfvars)? [Completeness, Spec FR-021, FR-022]
- [ ] CHK007 - Are state backend configuration requirements completely specified? [Completeness, Spec IC-002, State Management section]
- [ ] CHK008 - Are variable definition requirements clear for all configurable values? [Completeness, Spec FR-021]
- [ ] CHK009 - Are output requirements defined for infrastructure consumption by external consumers? [Gap, Plan outputs.tf section]
- [ ] CHK010 - Are Terraform validation workflow steps documented? [Completeness, Plan Constitution Principle V]
### Network Architecture
- [ ] CHK011 - Are VNet address space and subnet CIDR allocations completely specified? [Completeness, Spec IC-008, Clarifications]
- [ ] CHK012 - Are NSG rule requirements defined for all 3 subnets with source/destination specificity? [Completeness, Spec SEC-004 through SEC-007]
- [ ] CHK013 - Are private endpoint connectivity requirements fully documented? [Completeness, Spec FR-014, SEC-009, SEC-014]
- [ ] CHK014 - Are NAT Gateway association requirements clear (which subnets)? [Completeness, Spec FR-012]
### Security & Authentication
- [ ] CHK015 - Are password generation requirements specified with complexity constraints? [Completeness, Spec FR-006, SEC-002]
- [ ] CHK016 - Is the Key Vault secret storage and VM password reference flow clearly documented? [Completeness, Plan Password Flow section]
- [ ] CHK017 - Are managed identity requirements specified for all applicable resources? [Completeness, Spec SEC-001, SEC-003]
- [ ] CHK018 - Are diagnostic logging requirements defined for all monitored resources? [Completeness, Spec SEC-010]
- [ ] CHK019 - Are resource lock requirements specified with lock type and target resources? [Completeness, Spec SEC-011]
### Monitoring & Alerts
- [ ] CHK020 - Are alert condition thresholds quantified for all 3 critical alerts? [Completeness, Spec FR-020, Clarifications]
- [ ] CHK021 - Are Log Analytics retention requirements specified? [Completeness, Spec Clarifications - 180 days]
- [ ] CHK022 - Are alert action group requirements defined (notification method)? [Completeness, Spec Clarifications - Portal notifications]
---
## Requirement Clarity
### Ambiguity Resolution
- [ ] CHK023 - Is "Standard_D2s_v3" VM size explicitly stated (not "2 core, 8GB" generically)? [Clarity, Spec FR-001, Clarifications]
- [ ] CHK024 - Is "Standard HDD" tier explicitly specified vs ambiguous "standard storage"? [Clarity, Spec FR-002, FR-003, IC-007]
- [ ] CHK025 - Is "10.0.0.0/24" VNet address space quantified vs vague "small VNet"? [Clarity, Spec IC-008, Clarifications]
- [ ] CHK026 - Is "180 days" Log Analytics retention quantified vs vague "extended retention"? [Clarity, Spec Clarifications]
- [ ] CHK027 - Is "1TB" file share quota quantified vs vague "large capacity"? [Clarity, Spec Clarifications]
### Terraform-Specific Clarity
- [ ] CHK028 - Are AVM module variable names and structures referenced from module documentation? [Clarity, Spec FR-025]
- [ ] CHK029 - Is the random_password resource explicitly specified vs generic "password generator"? [Clarity, Plan main.tf section]
- [ ] CHK030 - Are AVM module "interfaces" (diagnostic_settings, lock, secrets) explicitly documented? [Clarity, Plan Constitution Principle III]
- [ ] CHK031 - Is "terraform.tfvars" explicit vs ambiguous "variable file"? [Clarity, Spec FR-021]
### Constraint Precision
- [ ] CHK032 - Is "15 characters or fewer" computer name limit quantified? [Clarity, Spec FR-004, IC-010]
- [ ] CHK033 - Is "westus3" region explicitly specified (not "US West" or "West US 3")? [Clarity, Spec IC-001]
- [ ] CHK034 - Is "vmadmin" username exact string specified? [Clarity, Spec FR-005]
- [ ] CHK035 - Are availability zone options explicitly defined as "1, 2, or 3 - NEVER -1"? [Clarity, Spec FR-023, IC-006]
---
## Requirement Consistency
### Cross-Reference Validation
- [ ] CHK036 - Do VNet subnet CIDRs in IC-008 match the clarifications section allocations? [Consistency, Cross-check IC-008 vs Clarifications]
- [ ] CHK037 - Is VM size requirement (FR-001) consistent across spec, user stories, and plan? [Consistency, FR-001, US1, Plan]
- [ ] CHK038 - Are file share capacity requirements consistent (1TB) across FR-013 and clarifications? [Consistency]
- [ ] CHK039 - Are NSG rule requirements consistent with subnet design (3 NSGs for 3 subnets)? [Consistency, FR-008, IC-008]
- [ ] CHK040 - Is Key Vault secret name requirement consistent (configurable via tfvars)? [Consistency, FR-016, SEC-002]
### Security Alignment
- [ ] CHK041 - Do NSG requirements align with zero-trust principles (deny-by-default in SEC-004)? [Consistency, SEC-004 through SEC-007]
- [ ] CHK042 - Are managed identity requirements consistent with "no credentials in code" requirement? [Consistency, SEC-001, SEC-003]
- [ ] CHK043 - Are private endpoint requirements consistent with "no public access" requirements? [Consistency, FR-014, SEC-009]
### Constitution Alignment
- [ ] CHK044 - Do spec requirements align with constitution Principle II (AVM-only)? [Consistency, Infrastructure Requirements vs Constitution]
- [ ] CHK045 - Do security requirements align with constitution Principle III (security controls)? [Consistency, SEC requirements vs Constitution]
- [ ] CHK046 - Do deployment requirements align with constitution Principle V (validation workflow)? [Consistency, SC-009 vs Constitution]
---
## Acceptance Criteria Quality
### Measurability
- [ ] CHK047 - Can "infrastructure deployment within 30 minutes" be objectively measured? [Measurability, SC-001]
- [ ] CHK048 - Can "RDP connection within 2 minutes" be objectively timed? [Measurability, SC-002]
- [ ] CHK049 - Can "diagnostic logs appear within 15 minutes" be objectively verified? [Measurability, SC-007]
- [ ] CHK050 - Can "total cost under $200/month" be objectively calculated? [Measurability, SC-013]
### Testability
- [ ] CHK051 - Are acceptance criteria testable with concrete validation steps? [Testability, All SC items]
- [ ] CHK052 - Are user story test scenarios written in Given/When/Then format? [Testability, User Stories 1-4]
- [ ] CHK053 - Do edge cases include expected behavior or just failure scenarios? [Testability, Edge Cases section]
### Completeness of Success Criteria
- [ ] CHK054 - Are success criteria defined for all 4 user stories? [Completeness, SC items map to US1-US4]
- [ ] CHK055 - Are success criteria defined for Terraform code quality (fmt, validate, tfsec)? [Completeness, SC-009]
- [ ] CHK056 - Are success criteria defined for security controls (no public IP, logs flowing)? [Completeness, SC-006, SC-007, SC-008]
---
## Scenario Coverage
### Primary Scenario Validation
- [ ] CHK057 - Are requirements defined for initial Terraform deployment (terraform apply)? [Coverage, Primary Flow]
- [ ] CHK058 - Are requirements defined for RDP access via Bastion post-deployment? [Coverage, US2]
- [ ] CHK059 - Are requirements defined for file share access via private endpoint? [Coverage, US3]
- [ ] CHK060 - Are requirements defined for internet access via NAT Gateway? [Coverage, US4]
### Alternate Scenario Coverage
- [ ] CHK061 - Are requirements defined for Terraform state backend configuration? [Coverage, Alternate Flow]
- [ ] CHK062 - Are requirements defined for variable customization via tfvars? [Coverage, FR-021]
- [ ] CHK063 - Are requirements defined for manual post-deployment file share mounting? [Coverage, Clarifications]
### Exception/Error Scenario Coverage
- [ ] CHK064 - Are requirements defined for handling VM naming exceeding 15 chars? [Coverage, Edge Cases]
- [ ] CHK065 - Are requirements defined for storage account name conflicts? [Coverage, Edge Cases]
- [ ] CHK066 - Are requirements defined for CIDR allocation failures? [Coverage, Edge Cases]
- [ ] CHK067 - Are requirements defined for partial deployment failures? [Coverage, Clarifications - incremental redeployment]
- [ ] CHK068 - Are requirements defined for Key Vault secret name conflicts? [Coverage, Edge Cases]
### Recovery Scenario Coverage
- [ ] CHK069 - Are requirements defined for redeploying after fixing errors? [Coverage, Clarifications - keep resources, fix, redeploy]
- [ ] CHK070 - Is the "no rollback/delete" approach clearly specified for failed deployments? [Coverage, Clarifications]
---
## Edge Case Coverage
### Boundary Conditions
- [ ] CHK071 - Is the 15-character NetBIOSlimit explicitly tested in edge cases? [Edge Case, IC-010, Edge Cases section]
- [ ] CHK072 - Are availability zone unavailability scenarios addressed? [Edge Case, Edge Cases section]
- [ ] CHK073 - Are VNet address space exhaustion scenarios addressed? [Edge Case, Edge Cases section]
- [ ] CHK074 - Are global naming conflicts (Key Vault, Storage Account) addressed? [Edge Case, Edge Cases section]
### Configuration Edge Cases
- [ ] CHK075 - Are NSG rule conflict scenarios addressed? [Edge Case, Edge Cases section]
- [ ] CHK076 - Are private DNS resolution failure scenarios addressed? [Edge Case, Edge Cases section]
- [ ] CHK077 - Are disk attachment failure scenarios addressed? [Edge Case, Edge Cases section]
---
## Non-Functional Requirements
### Performance Requirements
- [ ] CHK078 - Are deployment time expectations quantified (30 minutes in SC-001)? [NFR, SC-001]
- [ ] CHK079 - Are connection time expectations quantified (2 minutes RDP in SC-002)? [NFR, SC-002]
- [ ] CHK080 - Are log ingestion timeframes quantified (15 minutes in SC-007)? [NFR, SC-007]
- [ ] CHK081 - Is "Standard HDD is adequate" assumption documented? [NFR, Assumption A-009]
### Cost Requirements
- [ ] CHK082 - Is the cost constraint quantified (<$200/month)? [NFR, SC-013]
- [ ] CHK083 - Are cost optimization requirements specified (HDD vs SSD)? [NFR, IC-007]
### Security Requirements (Non-Functional)
- [ ] CHK084 - Are all security requirements explicitly listed in SEC section? [NFR, SEC-001 through SEC-014]
- [ ] CHK085 - Are encryption requirements specified (at-rest with Microsoft keys)? [NFR, SEC-013]
- [ ] CHK086 - Are soft-delete and purge protection requirements specified? [NFR, SEC-012]
### Compliance Requirements
- [ ] CHK087 - Are log retention requirements specified (180 days)? [NFR, Clarifications]
- [ ] CHK088 - Are resource lock requirements specified for compliance-critical resources? [NFR, SEC-011]
---
## Dependencies & Assumptions
### External Dependencies
- [ ] CHK089 - Are all Terraform/Azure CLI version dependencies documented? [Dependency, D-001, D-002]
- [ ] CHK090 - Is the pre-existing state backend dependency documented? [Dependency, D-005, A-002]
- [ ] CHK091 - Are AVM module registry dependencies documented? [Dependency, D-003]
- [ ] CHK092 - Are deployment permission dependencies documented? [Dependency, A-003]
### Assumption Validation
- [ ] CHK093 - Are quota assumptions documented (VM size, Bastion, NAT Gateway)? [Assumption, A-001]
- [ ] CHK094 - Are availability zone support assumptions documented? [Assumption, A-005]
- [ ] CHK095 - Are naming conflict assumptions documented? [Assumption, A-004]
- [ ] CHK096 - Is the "no domain join" assumption explicitly stated? [Assumption, A-014]
- [ ] CHK097 - Is the "no ExpressRoute/VPN" assumption explicitly stated? [Assumption, A-013]
### Validated Constraints
- [ ] CHK098 - Are all infrastructure constraints (IC-001 through IC-010) fully documented? [Dependency, Infrastructure Constraints section]
- [ ] CHK099 - Are Terraform provider version constraints specified? [Dependency, Plan Technical Context]
---
## Ambiguities & Conflicts
### Potential Ambiguities
- [ ] CHK100 - Is "Bastion SKU (Basic or Standard)" resolved to specific choice? [Ambiguity, Data Model section]
- [ ] CHK101 - Is "RBAC vs Access Policies" for Key Vault resolved to specific choice? [Ambiguity, Data Model section]
- [ ] CHK102 - Is "Action Group notification target" specified beyond "email or webhook"? [Ambiguity, Assumption A-011]
- [ ] CHK103 - Are AVM module version selection criteria specified (always latest stable)? [Ambiguity, Plan Technical Context note]
### Potential Conflicts
- [ ] CHK104 - Do VNet subnet CIDRs in spec match Clarifications section? [Conflict Check, IC-008 vs Clarifications]
- [ ] CHK105 - Does "no backup" decision conflict with any compliance requirements? [Conflict Check, Clarifications vs OS-006]
- [ ] CHK106 - Does "Standard HDD" choice conflict with performance expectations? [Conflict Check, IC-007, A-009]
### Specification Gaps
- [ ] CHK107 - Are requirements missing for NSG flow log configuration? [Gap, SEC-014 mentions flow logs]
- [ ] CHK108 - Are requirements missing for custom DNS configuration? [Gap, Private endpoint DNS]
- [ ] CHK109 - Are requirements missing for alert action group email address? [Gap, Clarifications mention portal only]
- [ ] CHK110 - Are requirements missing for VM OS disk size specification? [Gap, FR-002 mentions standard HDD but not size]
---
## Traceability & Documentation
### Requirement Traceability
- [ ] CHK111 - Are all functional requirements (FR-001 through FR-025) traceable to user stories? [Traceability]
- [ ] CHK112 - Are all security requirements (SEC-001 through SEC-014) traceable to constitution? [Traceability]
- [ ] CHK113 - Are all infrastructure constraints (IC-001 through IC-010) traceable to constitution or clarifications? [Traceability]
- [ ] CHK114 - Are all success criteria (SC-001 through SC-013) traceable to user stories? [Traceability]
### Clarification Documentation
- [ ] CHK115 - Are all clarification session Q&A pairs documented with decisions? [Documentation, Clarifications section]
- [ ] CHK116 - Are clarification decisions integrated into requirements (not just listed)? [Documentation, Requirements reflect clarifications]
- [ ] CHK117 - Are out-of-scope items explicitly documented? [Documentation, Out of Scope section]
### Plan-Spec Alignment
- [ ] CHK118 - Does the plan reference all 25 functional requirements? [Traceability, Plan addresses all FRs]
- [ ] CHK119 - Does the plan reference all 14 security requirements? [Traceability, Plan addresses all SECs]
- [ ] CHK120 - Does the plan reference all 10 infrastructure constraints? [Traceability, Plan addresses all ICs]
---
## Summary
**Total Checklist Items**: 120
**Expected Completion Time**: 2-3 hours for comprehensive review
**Target Audience**: Implementation team preparing to build Terraform code
**Usage Instructions**:
1. Review each checklist item sequentially
2. Mark β for satisfied requirements, β for gaps/issues
3. Document findings in adjacent notes column (if needed)
4. Escalate any β items to spec author for clarification/resolution
5. Re-validate after spec updates
**Pass Criteria**:
- β₯95% items marked β (114+ passing items)
- Zero CRITICAL gaps (ambiguities in security, naming, or Terraform structure)
- All conflicts resolved before implementation begins
**Next Steps After Completion**:
- If β₯95% pass: Proceed to implementation (terraform code generation)
- If <95%pass:Updatespec.mdtoaddressgaps,thenre-runchecklist-Archivethischecklistwithimplementationforaudittrail
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture your new checklist, with a comment of something like Checklist prepared.
6. Tasks
Spec Kit uses /speckit.tasks to generate the tasks.md file. The prompt doesn’t require any specific inputs as it analyzes the existing plan to break it down into actionable tasks. Tasks can be evolved through iterating over the tasks.md file by either manually editing it or repeatedly fine tuning the prompt used with /speckit.tasks, or leveraging /speckit.analyze to review/validate and challenge the tasks.
Info
To learn more about what the tasks should include, see the Tasks chapter in the Spec Kit article.
Run the following prompt to generate tasks for our example:
/speckit.tasks
β Expand to see the results
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
In the Copilot chat window, you should see something like this:
<!-- markdownlint-disable --># Tasks: Legacy VM Workload Infrastructure
**Feature**: [spec.md](./spec.md) | **Plan**: [plan.md](./plan.md)
**Prerequisites**: plan.md, spec.md, research.md, data-model.md, quickstart.md
**Date**: 2026-01-27
**Branch**: `001-legacy-vm-workload`**Organization**: Tasks are grouped by user story (US1-US5) to enable independent implementation and testing.
## Format: `[ID] [P?] [Story?] Description`
- **[P]**: Parallelizable (different files, no blocking dependencies)
- **[Story]**: User story label (US1, US2, US3, US4, US5)
- File paths included in descriptions
---
## Phase 1: Setup (Project Initialization)
**Purpose**: Basic project structure and Bicep configuration
- [ ] T001 Create infrastructure directory structure: infra/, infra/docs/
- [ ] T002 Create bicepconfig.json with AVM analyzer rules at infra/bicepconfig.json
- [ ] T003 [P] Create .gitignore file to exclude .bicep build artifacts (*.json from main.bicep compilation)
- [ ] T004 [P] Create project README.md at repository root with quickstart reference
- [ ] T005 Initialize main.bicep with metadata, targetScope='resourceGroup', location parameter
---
## Phase 2: Foundational (Blocking Prerequisites for All User Stories)
**Purpose**: Shared infrastructure that MUST be complete before any user story implementation
**β οΈ CRITICAL**: No user story work can begin until this phase is complete
- [ ] T006 Add parameters to main.bicep: vmSize (default: Standard_D2s_v3), vmAdminUsername (default: vmadmin), vmAdminPasswordSecretName (default: 'vm-admin-password'), availabilityZone (default: 1), fileShareQuotaGiB (default: 1024), logAnalyticsRetentionDays (default: 30)
- [ ] T007 Define variables in main.bicep: suffix = uniqueString(resourceGroup().id), vmPassword = 'P@ssw0rd!${uniqueString(resourceGroup().id, deployment().name, utcNow('u'))}' (NOTE: utcNow() makes deployment non-idempotent - password regenerates on each deploy. Acceptable for initial deployment; consider removing utcNow() for idempotent redeployments)
- [ ] T008 Define resource naming variables: vnetName, vmName, kvName, lawName, stName (storage: no hyphens, max 24 chars)
- [ ] T009 [P] Define tags variable: workload='legacy-vm', environment='production', compliance='legacy-retention', managedBy='bicep-avm'
- [ ] T010 Add AVM module for Log Analytics Workspace (avm/res/operational-insights/workspace:0.15.0) at infra/main.bicep
- [ ] T011 Configure Log Analytics parameters: name, location, retentionInDays, tags
- [ ] T012 Create main.bicepparam file at infra/main.bicepparam with 'using' directive and parameter defaults
**Checkpoint**: Foundation ready - user story phases can now proceed in parallel (if staffed) or sequentially by priority
---
## Phase 3: User Story 1 - Core VM Infrastructure (Priority: P1) π― MVP
**Goal**: Deploy VNet, VM with Windows Server 2016, basic networking - foundational workload infrastructure
**Independent Test**: Deploy to test resource group, verify VM created with correct specs (Standard_D2s_v3, Windows Server 2016), VM communicates within VNet
### Validation for User Story 1 (MANDATORY - Constitution Principle III) β οΈ
> **NOTE: These validation tasks must be executed BEFORE deployment**
- [ ] T013 [US1] Run `bicep build infra/main.bicep` to compile and check syntax errors
- [ ] T014 [US1] Run `az deployment group validate --resource-group rg-legacyvm-test --template-file main.bicep --parameters main.bicepparam`- [ ] T015 [US1] Run `az deployment group what-if --resource-group rg-legacyvm-test --template-file main.bicep --parameters main.bicepparam`- [ ] T016 [US1] Review what-if output: verify VNet, VM, NIC will be created with no unexpected changes
### Implementation for User Story 1
- [ ] T017 [P] [US1] Add AVM module for Virtual Network (avm/res/network/virtual-network:0.7.2) in main.bicep
- [ ] T018 [US1] Configure VNet parameters: name, location, addressPrefixes=['10.0.0.0/24'], subnets array with 3 subnets (VM: 10.0.0.0/27, Bastion: 10.0.0.64/26, PE: 10.0.0.128/27)
- [ ] T019 [US1] Add diagnostic settings to VNet module: send to Log Analytics workspace ID reference
- [ ] T020 [P] [US1] Add AVM module for Virtual Machine (avm/res/compute/virtual-machine:0.21.0) in main.bicep
- [ ] T021 [US1] Configure VM parameters: name='vm-legacyvm-${suffix}', computerName='vm-${substring(suffix,0,10)}' (β€15 chars), size=vmSize parameter, adminUsername=vmAdminUsername, adminPassword=kvSecretReference, zone=availabilityZone
- [ ] T022 [US1] Configure VM OS: imageReference for Windows Server 2016, osDisk with Standard_LRS SKU (HDD performance tier)
- [ ] T023 [US1] Configure VM managed identity: type='SystemAssigned'
- [ ] T024 [US1] Configure VM NIC: attach to VM subnet, no public IP, dynamic private IP
- [ ] T025 [US1] Add VM diagnostic settings to Log Analytics workspace
- [ ] T026 [US1] Add VM outputs: vmName, vmResourceId, vmPrivateIP
### Deployment for User Story 1
- [ ] T027 [US1] Create Azure resource group: `az group create --name rg-legacyvm-test --location westus3`- [ ] T028 [US1] Deploy to test resource group: `az deployment group create --resource-group rg-legacyvm-test --template-file main.bicep --parameters main.bicepparam`- [ ] T029 [US1] Verify VNet created with 3 subnets in Azure Portal (10.0.0.0/24 address space)
- [ ] T030 [US1] Verify VM created with Windows Server 2016, Standard_D2s_v3, correct zone
- [ ] T031 [US1] Verify VM computer name is β€15 characters (NetBIOS limit)
- [ ] T032 [US1] Verify diagnostic logs flowing to Log Analytics workspace within 5 minutes
**Checkpoint**: User Story 1 complete - VM infrastructure deployed and validated. Ready to proceed with US2 and US3 in parallel.
---
## Phase 4: User Story 2 - Secure Storage and Data Disk (Priority: P2)
**Goal**: Attach 500GB data disk to VM, deploy storage account with 1TB file share via private endpoint
**Independent Test**: Verify 500GB HDD data disk attached to VM, file share accessible from VM through private endpoint (no internet traversal)
### Implementation for User Story 2
- [ ] T033 [P] [US2] Add data disk to VM module configuration in main.bicep: dataDisks array with disk size=500, sku=Standard_LRS, lun=0, name='datadisk-01'
- [ ] T034 [P] [US2] Add AVM module for Storage Account (avm/res/storage/storage-account:0.31.0) in main.bicep
- [ ] T035 [US2] Configure storage parameters: name='st${replace(suffix, '-', '')}' (max 24 chars, no hyphens), kind='StorageV2', sku='Standard_LRS', accessTier='Hot', publicNetworkAccess='Disabled'
- [ ] T036 [US2] Configure file share in storage module: fileServices with share name='fileshare', quota=fileShareQuotaGiB (1024 GiB)
- [ ] T037 [US2] Add diagnostic settings to storage module: send to Log Analytics workspace
- [ ] T038 [P] [US2] Add AVM module for Private DNS Zone (avm/res/network/private-dns-zone:0.8.0) in main.bicep
- [ ] T039 [US2] Configure DNS zone name: 'privatelink.file.core.windows.net', VNet link to main VNet
- [ ] T040 [P] [US2] Add AVM module for Private Endpoint (avm/res/network/private-endpoint:0.11.1) in main.bicep
- [ ] T041 [US2] Configure private endpoint: subnet=PE subnet, groupIds=['file'], privateDnsZoneResourceIds=[DNS zone ID], link to storage account resource
- [ ] T042 [US2] Add storage outputs: storageAccountName, fileShareName, privateEndpointIP
### Deployment for User Story 2
- [ ] T043 [US2] Re-run validation: `bicep build`, `az deployment validate`, `what-if` analysis
- [ ] T044 [US2] Deploy updated template to test resource group
- [ ] T045 [US2] Verify 500GB data disk attached to VM in Azure Portal (LUN 0, Standard_LRS)
- [ ] T046 [US2] Verify storage account created with public access disabled
- [ ] T047 [US2] Verify file share created with 1024 GiB quota
- [ ] T048 [US2] Verify private endpoint resolves to internal IP (10.0.0.128/27 range): `nslookup st{random}.file.core.windows.net` from VM
- [ ] T049 [US2] Test file share access from VM via Bastion: `Test-NetConnection -ComputerName st{random}.file.core.windows.net -Port 445`**Checkpoint**: User Stories 1 AND 2 complete - VM with data disk and storage file share via private endpoint validated.
---
## Phase 5: User Story 3 - Secure Access and Secrets Management (Priority: P2)
**Goal**: Deploy Azure Bastion for secure RDP access, Key Vault for storing VM password
**Independent Test**: Connect to VM through Bastion host using password retrieved from Key Vault (no public IP on VM)
### Implementation for User Story 3
- [ ] T050 [P] [US3] Add AVM module for Key Vault (avm/res/key-vault/vault:0.13.3) in main.bicep
- [ ] T051 [US3] Configure Key Vault parameters: name='kv-legacyvm-${suffix}', sku='standard', enableRbacAuthorization=true, softDeleteRetentionInDays=90
- [ ] T052 [US3] Add Key Vault secret via module's secrets parameter: name=vmAdminPasswordSecretName parameter, value=vmPassword variable, contentType='text/plain'
- [ ] T053 [US3] Add RBAC role assignment in Key Vault module: principalId=VM managed identity, roleDefinitionIdOrName='Key Vault Secrets User'
- [ ] T054 [US3] Add Key Vault diagnostic settings to Log Analytics workspace
- [ ] T055 [P] [US3] Update VM module configuration: change adminPassword to reference Key Vault secret (use getSecret() or secretReference)
- [ ] T056 [P] [US3] Add AVM module for Bastion Host (avm/res/network/bastion-host:0.8.2) in main.bicep
- [ ] T057 [US3] Configure Bastion parameters: name='bas-legacyvm-${suffix}', sku='Basic', vnetId=VNet resource ID, subnetName='AzureBastionSubnet'
- [ ] T058 [US3] Add Bastion diagnostic settings to Log Analytics workspace
- [ ] T059 [US3] Add Key Vault and Bastion outputs: kvName, kvResourceId, bastionName, bastionResourceId
### Deployment for User Story 3
- [ ] T060 [US3] Re-run validation: `bicep build`, `az deployment validate`, `what-if` analysis
- [ ] T061 [US3] Deploy updated template to test resource group (expected duration: 15-20 minutes for Bastion)
- [ ] T062 [US3] Verify Key Vault created with RBAC enabled (not access policies)
- [ ] T063 [US3] Verify VM password stored as Key Vault secret: `az keyvault secret show --name vm-admin-password --vault-name kv-legacyvm-{suffix}`- [ ] T064 [US3] Verify VM managed identity has 'Key Vault Secrets User' role on Key Vault
- [ ] T065 [US3] Verify Azure Bastion deployed successfully in Bastion subnet
- [ ] T066 [US3] Test Bastion connectivity: Connect to VM via Azure Portal β VM β Connect β Bastion, use username='vmadmin' and password from Key Vault
- [ ] T067 [US3] Verify VM has no public IP address assigned (confirm access only through Bastion)
**Checkpoint**: User Stories 1, 2, AND 3 complete - Full VM infrastructure with secure access and storage operational.
---
## Phase 6: User Story 4 - Internet Connectivity and Network Security (Priority: P3)
**Goal**: Configure NAT Gateway for outbound internet, implement NSGs for all subnets with least-privilege rules
**Independent Test**: Verify VM reaches internet through NAT Gateway, NSG rules block unauthorized traffic
### Implementation for User Story 4
- [ ] T068 [P] [US4] Add AVM module for NAT Gateway (avm/res/network/nat-gateway:2.0.1) in main.bicep
- [ ] T069 [US4] Configure NAT Gateway parameters: name='nat-legacyvm-${suffix}', zone=availabilityZone, publicIpAddressObjects=[{name: 'pip-nat'}]
- [ ] T070 [US4] Update VNet module configuration: associate NAT Gateway with VM subnet (natGatewayId in subnet definition)
- [ ] T071 [US4] Add NAT Gateway diagnostic settings to Log Analytics workspace
- [ ] T072 [P] [US4] Add AVM module for VM Subnet NSG (avm/res/network/network-security-group:0.5.2) in main.bicep
- [ ] T073 [US4] Configure VM NSG security rules: **CRITICAL - inbound allow TCP 3389 from Bastion subnet (10.0.0.64/26) priority 100**, inbound deny all (priority 4096), outbound allow Internet (priority 100), outbound allow VNet (priority 200), outbound deny all (priority 4096)
- [ ] T074 [US4] Update VNet module: associate VM NSG with VM subnet (networkSecurityGroupId in subnet definition)
- [ ] T075 [US4] Add VM NSG diagnostic settings to Log Analytics workspace
- [ ] T076 [P] [US4] Add AVM module for Bastion Subnet NSG (avm/res/network/network-security-group:0.5.2) in main.bicep
- [ ] T077 [US4] Configure Bastion NSG security rules: inbound allow 443 from Internet, allow GatewayManager 443, allow AzureLoadBalancer 443, allow Bastion communication 8080/5701; outbound allow SSH/RDP to VNet, allow Azure Cloud 443, allow Bastion communication, allow HTTP 80
- [ ] T078 [US4] Update VNet module: associate Bastion NSG with Bastion subnet
- [ ] T079 [US4] Add Bastion NSG diagnostic settings to Log Analytics workspace
- [ ] T080 [P] [US4] Add AVM module for PE Subnet NSG (avm/res/network/network-security-group:0.5.2) in main.bicep
- [ ] T081 [US4] Configure PE NSG security rules: inbound allow TCP 445 from VM subnet (10.0.0.0/27), inbound deny all; outbound allow all
- [ ] T082 [US4] Update VNet module: associate PE NSG with PE subnet
- [ ] T083 [US4] Add PE NSG diagnostic settings to Log Analytics workspace
- [ ] T084 [US4] Add NSG and NAT Gateway outputs: nsgVmName, nsgBastionName, nsgPeName, natGatewayName
### Deployment for User Story 4
- [ ] T085 [US4] Re-run validation: `bicep build`, `az deployment validate`, `what-if` analysis
- [ ] T086 [US4] Deploy updated template to test resource group
- [ ] T087 [US4] Verify NAT Gateway created with public IP and associated with VM subnet
- [ ] T088 [US4] Verify 3 NSGs created and associated with correct subnets
- [ ] T089 [US4] Test outbound internet from VM via Bastion RDP session: `Test-NetConnection -ComputerName google.com -Port 443` (should succeed through NAT Gateway)
- [ ] T090 [US4] Test NSG deny rules: attempt unauthorized inbound connection to VM (should be blocked)
- [ ] T091 [US4] Verify all NSG diagnostic logs flowing to Log Analytics workspace
**Checkpoint**: User Stories 1-4 complete - Full network security and internet connectivity operational.
---
## Phase 7: User Story 5 - Monitoring and Alerting (Priority: P3)
**Goal**: Configure diagnostic settings for all resources, deploy 3 critical alerts (VM stopped, disk >85%, Key Vault access failures)
**Independent Test**: Verify diagnostic logs flowing to Log Analytics, trigger test alert scenarios and confirm alerts fire
### Implementation for User Story 5
- [ ] T092 [P] [US5] Add AVM module for VM Stopped Alert (avm/res/insights/metric-alert:0.4.1) in main.bicep
- [ ] T093 [US5] Configure VM stopped alert: name='alert-vm-stopped-legacyvm-${suffix}', targetResourceId=VM resource ID, metricName='Percentage CPU', operator='LessThan', threshold=1, aggregation='Average', windowSize='PT15M', severity=0 (Critical), enabled=true, autoMitigate=false
- [ ] T094 [US5] Ensure no action groups configured (Portal-only notifications per MON-003)
- [ ] T095 [P] [US5] Add AVM module for Disk Space Alert (avm/res/insights/metric-alert:0.4.1) in main.bicep
- [ ] T096 [US5] Configure disk space alert: name='alert-disk-space-legacyvm-${suffix}', targetResourceId=VM resource ID, metricName='OS Disk Used Percentage', operator='GreaterThan', threshold=85, aggregation='Average', windowSize='PT5M', severity=0, enabled=true, autoMitigate=false
- [ ] T097 [P] [US5] Add AVM module for Key Vault Access Failure Alert (avm/res/insights/metric-alert:0.4.1) in main.bicep
- [ ] T098 [US5] Configure KV alert: name='alert-kv-access-fail-legacyvm-${suffix}', targetResourceId=Key Vault resource ID, metricName='ServiceApiHit', dimensions=[{name: 'ActivityName', operator: 'Include', values: ['SecretGet']}, {name: 'StatusCode', operator: 'Include', values: ['Unauthorized']}], operator='GreaterThan', threshold=0, aggregation='Count', windowSize='PT5M', severity=0
- [ ] T099 [US5] Review all existing resource modules: verify diagnostic settings already configured for VNet, VM, Storage, Key Vault, NSGs, NAT Gateway, Bastion (completed in previous phases)
- [ ] T100 [US5] Add alert outputs: alertVmStoppedName, alertDiskSpaceName, alertKvFailureName
### Deployment for User Story 5
- [ ] T101 [US5] Re-run validation: `bicep build`, `az deployment validate`, `what-if` analysis
- [ ] T102 [US5] Deploy updated template to test resource group
- [ ] T103 [US5] Verify Log Analytics workspace contains logs from all resources: run query in Azure Portal β Log Analytics β Logs β `AzureDiagnostics | where ResourceGroup == 'rg-legacyvm-test' | summarize count() by ResourceType`- [ ] T104 [US5] Verify 3 metric alerts created and enabled in Azure Portal β Monitor β Alerts
- [ ] T105 [US5] Test VM stopped alert: Stop VM, wait 15 minutes, verify alert fires and visible in Portal
- [ ] T106 [US5] Test Key Vault access failure alert: Attempt to access non-existent secret `az keyvault secret show --name fake-secret --vault-name kv-legacyvm-{suffix}`, wait 5 minutes, verify alert fires
- [ ] T107 [US5] Verify alert notifications visible in Azure Portal β Monitor β Alerts (no external action groups configured)
- [ ] T108 [US5] Document alert testing procedures in infra/docs/deployment.md
**Checkpoint**: All 5 user stories complete - Full monitoring and alerting operational. MVP infrastructure complete!
---
## Phase 8: Polish & Cross-Cutting Concerns
**Purpose**: Final improvements and documentation that span multiple user stories
- [ ] T109 [P] Review main.bicep for code quality: verify all resources have comments explaining purpose
- [ ] T110 [P] Review main.bicepparam for documentation: verify parameter descriptions and defaults documented
- [ ] T111 [P] Validate constitution compliance: check all 6 principles satisfied (IC-001 to IC-006, SEC-001 to SEC-008)
- [ ] T112 [P] Run final validation suite: `bicep build`, `az deployment validate`, `what-if` analysis
- [ ] T113 Update infra/docs/deployment.md with full deployment outcomes and lessons learned
- [ ] T114 [P] Create architecture diagram in infra/docs/architecture.md showing all resources and dependencies
- [ ] T115 Verify all success criteria met (SC-001 to SC-011): deployment time <20minutes,allresourcesoperational,logsflowing,alertsworking- [ ]T116Executequickstart.mdvalidationend-to-end:followdeploymentguidesteps,verifysuccessfuldeployment- [ ]T117[P]ReviewAzureSecurityCenterrecommendations:addressanyhigh-severitycomplianceissues- [ ]T118DocumentestimatedmonthlycostsinREADME.md:VM~$70,Storage~$50,Bastion~$140,Other~$10 =Total~$270/month- [ ]T119CreateCHANGELOG.mdentry:documentinitialdeploymentdate,version1.0.0,allresourcesdeployed- [ ]T120Finalcodereview:verifynohardcodedvalues,allparametersinmain.bicepparam,richcommentspresent**Checkpoint**:Production-readyinfrastructurecomplete.Readyforoperationalhandoff.---## Dependencies & Execution Order
### Phase Dependencies
1.**Setup (Phase 1)**:Nodependencies-startimmediately2.**Foundational (Phase 2)**:DependsonSetup-BLOCKSalluserstories3.**User Story 1 (Phase 3)**:DependsonFoundational-MVPfoundation,MUSTcompletefirst4.**User Story 2 (Phase 4)**:DependsonFoundational-CanproceedafterUS1orinparallel5.**User Story 3 (Phase 5)**:DependsonFoundationalandUS1(VMmustexistforKeyVaultpasswordreference)-BastiondependsonVNetfromUS16.**User Story 4 (Phase 6)**:DependsonFoundationalandUS1(NATGatewayandNSGsassociatewithVNetsubnetsfromUS1)7.**User Story 5 (Phase 7)**:Dependsonallprevioususerstories(alertstargetVM,KeyVault;diagnosticsettingsreferenceLogAnalyticsfromFoundational)8.**Polish (Phase 8)**:Dependsonalluserstoriescomplete### User Story Interdependencies
-**US1(CoreVM)**:IndependentafterFoundational-canstartfirst-**US2(Storage)**:DependsonUS1(datadiskattachestoVM,privateendpointneedsVNet)-**US3(SecureAccess)**:DependsonUS1(KeyVaultstorespasswordforVM,BastionaccessesVM,bothneedVNet)-**US4(NetworkSecurity)**:DependsonUS1(NATGatewayandNSGsassociatewithVNetsubnets)-**US5(Monitoring)**:DependsonUS1,US3(alertstargetVMandKeyVaultresources)### Recommended Execution Sequence
**Option 1 - Sequential by Priority**(singledeveloper):1.SetupβFoundationalβUS1βUS2βUS3βUS4βUS5βPolish**Option 2 - Parallel with Blocking**(teamof3):1.SetupβFoundational2.US1(Developer1)3.AfterUS1:US2+US3+US4inparallel(Developers1,2,3)4.AfterUS2/US3/US4:US5(anydeveloper)5.Polish### Validation Cadence
-Run`bicep build`aftereveryfilemodification-Run`az deployment validate`beforeeverydeployment-Run`what-if`analysisbeforeeverydeploymenttotest/production-Testeachuserstoryindependentlyafteritsdeploymentphase### MVP Definition
**Minimum Viable Product = User Story 1 Complete**AtT032completion,youhave:-WindowsServer2016VMoperational-VNetwith3subnetsconfigured-BasicinfrastructurevalidatedThisissufficienttodemonstratefoundationalworkloadcapabilities.Subsequentuserstoriesaddstorage,secureaccess,networksecurity,andmonitoringincrementally.---## Parallel Execution Opportunities
### Tasks That Can Run in Parallel
**Phase 1 (Setup)**:T003,T004canruninparallelwithT002**Phase 2 (Foundational)**:T009,T012canruninparallelafterT008**Phase 3 (US1)**:T017,T020canruninparallel(researchdifferentmodules)**Phase 4 (US2)**:T033,T034,T038,T040canruninparallel(differentmoduleadditions)**Phase 5 (US3)**:T050,T055,T056canruninparallel(KeyVault,Bastion,VMupdate)**Phase 6 (US4)**:T068,T072,T076,T080canruninparallel(NATGateway+3NSGs)**Phase 7 (US5)**:T092,T095,T097canruninparallel(3independentalertmodules)**Phase 8 (Polish)**:T109,T110,T111,T114,T117,T118canruninparallel(differentfileupdates)### Example Parallel Workflow (3 developers)
**Sprint 1 (Week 1)**:-Dev1:T001-T012(Setup+Foundational)-Dev2:T003-T004inparallelwithDev1-Dev3:StartplanningUS2tasks**Sprint 2 (Week 2)**:-Dev1:T013-T032(US1-CoreVM)-Dev2+Dev3:PrepareforUS2/US3parallelwork**Sprint 3 (Week 3)**:-Dev1:T033-T049(US2-Storage)-Dev2:T050-T067(US3-SecureAccess)-Dev3:T068-T091(US4-NetworkSecurity)**Sprint 4 (Week 4)**:-Dev1:T092-T108(US5-Monitoring)-Dev2+Dev3:T109-T120(Polish)inparallel**Total Duration**:~4weekswith3developers,or~6weekssequential---## Implementation Strategy
### MVP-First Approach
1.**Deliver US1 first**(Phase3:CoreVMInfrastructure)-Providesfoundationalvalue:operationalVMwithnetworking-Independenttestableincrement-ValidatesBiceptemplatestructureandAVMmoduleusage2.**Add US2 + US3**(Phase4-5:Storage+SecureAccess)-Providessecureoperationscapabilities-Datastoragelayercomplete-Bastionaccessoperational3.**Add US4 + US5**(Phase6-7:NetworkSecurity+Monitoring)-Production-gradesecurityandobservability-Completeinfrastructurecompliance### Incremental Delivery Value
|CompletionPoint|ValueDelivered|CanDeploytoProduction?||------------------|-----------------|---------------------------||AfterUS1|BasicVMworkloadoperational|No-missingsecuritycontrols||AfterUS1+US3|VMwithsecureaccess|No-missingstorageandmonitoring||AfterUS1+US2+US3|VMwithstorageandsecureaccess|Maybe-basicfunctionalitycomplete,butnomonitoring||AfterUS1-US4|Fullnetworksecurityinplace|Maybe-functionallycomplete,limitedobservability||AfterUS1-US5|Fullmonitoringandalerting|**YES**-production-ready|### Rollback Strategy
-Eachuserstorydeploymentisincremental-previousstatepreserved-ARMdeploymentmode:Incremental(default)-onlyadds/updatesresources-Rollback:Redeploypreviousversionofmain.bicep(ifmaintainedingit)-Nuclearoption:Deleteresourcegroupandredeployfromscratch(acceptableforthissingle-RGworkload)---## Task Validation Checklist
Beforemarkingtasks.mdascomplete,verify:- [ ]All5userstoriesfromspec.mdmappedtotaskphases- [ ]Eachuserstoryhasvalidationtasks(T013-T016patternforBicep/ARMvalidation)- [ ]EachuserstoryhasimplementationtaskswithAVMmodulereferences- [ ]Eachuserstoryhasdeploymenttaskswithverificationsteps- [ ]Eachuserstoryisindependentlytestable(checkpointverificationsdefined)- [ ]All16functionalrequirements(FR-001toFR-016)coveredintasks- [ ]All8securityrequirements(SEC-001toSEC-008)coveredintasks- [ ]All6infrastructureconstraints(IC-001toIC-006)coveredintasks- [ ]All5monitoringrequirements(MON-001toMON-005)coveredintasks- [ ]TaskIDssequential(T001toT120)- [ ]Paralleltasksmarkedwith[P]- [ ]Userstorytasksmarkedwith[US1]to[US5]- [ ]Filepathsincludedintaskdescriptions- [ ]Constitutionvalidationtasksincluded(T111)- [ ]Quickstartvalidationtaskincluded(T116)**Total Tasks**:120**Estimated Duration**:4-6weeks(dependingonteamsizeandparallelexecution)
/speckit.tasks
β Expand to see the results
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
In the Copilot chat window, you should see something like this:
# Implementation Tasks: Legacy Business Application Infrastructure
**Feature**: 001-my-legacy-workload
**Status**: Ready for Implementation
**Created**: 2026-02-18
**Input**: [spec.md](./spec.md) | [plan.md](./plan.md)
**Total Tasks**: 78
**Organization**: Tasks organized by User Story to enable independent implementation and parallel execution. Each phase delivers a complete, independently testable capability.
**Task Format**: `- [ ] [TaskID] [P] [StoryLabel] Description with file path`- **[P]** = Parallelizable (different files, no dependencies on incomplete tasks)
- **[Story]** = User Story label (US1, US2, US3, US4)
---
## Task Execution Strategy
### Implementation Approach
- **MVP First**: Complete User Story 1 (P1) before moving to other stories
- **Incremental Delivery**: Each user story phase is fully functional and independently testable
- **Parallel Opportunities**: Tasks marked [P] can run concurrently within the same phase
- **Validation Gates**: Terraform validate + plan review between phases
### Dependency Flow
1.**Setup** β **Foundational** (blocking)
2.**Foundational** β **US1** (P1 - Core Compute)
3.**US1** β **US2** (P2 - Secure Access)
4.**US1 + US2** β **US3** (P3 - Storage)
5.**US1 + US2 + US3** β **US4** (P4 - Observability)
6.**All User Stories** β **Polish**### Independent Test Criteria Per Story
- **US1**: VM running in VNet with NSGs, no external access
- **US2**: RDP via Bastion using Key Vault password
- **US3**: File share accessible from VM via private endpoint
- **US4**: Internet via NAT, logs in Log Analytics, alerts functional
---
## Phase 1: Setup & Project Initialization
**Objective**: Initialize Terraform project structure, install tooling, configure remote state backend
**Prerequisites**: Azure subscription with Contributor access, Azure CLI authenticated, Terraform >= 1.9.0 installed
### Project Structure Tasks
- [ ] T001 Create terraform/ directory at repository root
- [ ] T002 Create docs/ directory for documentation
- [ ] T003 Create .github/workflows/ directory for CI/CD (optional)
- [ ] T004 Create .gitignore file with Terraform patterns (.terraform/, *.tfstate, *.tfplan, *.tfvars except *.tfvars.example)
### Terraform Configuration Files (Shell)
- [ ] T005 [P] Create terraform/terraform.tf with provider version constraints (Terraform >= 1.9.0, AzAPI ~> 2.12 for direct resources, AzureRM ~> 4.0 for published AVM dependencies, random ~> 3.6)
- [ ] T006 [P] Create terraform/variables.tf shell with empty file (will populate in Phase 2)
- [ ] T007 [P] Create terraform/locals.tf shell with empty file (will populate in Phase 2)
- [ ] T008 [P] Create terraform/main.tf shell with header comment
- [ ] T009 [P] Create terraform/outputs.tf shell with empty file (will populate per user story)
- [ ] T010 [P] Create terraform/prod.tfvars.example template file
### State Backend Configuration
- [ ] T011 Verify pre-existing Azure Storage Account for Terraform state exists (per spec dependency D-005)
- [ ] T012 Create terraform/backend.hcl.example with backend configuration template (storage_account_name, container_name, key, resource_group_name)
- [ ] T013 Document backend configuration in terraform/README.md (instructions for creating backend.hcl from example)
### Tooling Installation
- [ ] T014 [P] Install tfsec >= 1.28 for security scanning (per plan Security Tooling)
- [ ] T015 [P] Install checkov >= 3.0 for compliance scanning (per plan Security Tooling)
- [ ] T016 [P] Verify Terraform CLI >= 1.9.0 installed (terraform version)
### Documentation
- [ ] T017 Create terraform/README.md with deployment instructions (init β fmt β validate β plan β apply workflow)
- [ ] T018 Create docs/README.md with project overview
- [ ] T019 Create docs/architecture.md placeholder for infrastructure diagrams
**Phase 1 Validation**:
- β Directory structure created
- β All Terraform shell files exist
- β Backend configuration documented
- β Security tooling installed
---
## Phase 2: Foundational Infrastructure (Blocking Prerequisites)
**Objective**: Deploy foundational resources required by all user stories (Resource Group, naming resources, Log Analytics for diagnostic settings)
**Prerequisites**: Phase 1 complete, backend.hcl configured, Terraform initialized
### Terraform Initialization
- [ ] T020 Run terraform init -backend-config=backend.hcl to initialize backend and download providers
### Random Resources for Naming
- [ ] T021 [US1] Implement random_string resource in terraform/main.tf for unique suffix (6 chars, lowercase alphanumeric)
- [ ] T022 [US1] Implement random_password resource in terraform/main.tf for VM admin password (24 chars, complexity requirements per plan)
### Locals for Naming Convention
- [ ] T023 [US1] Define locals.tf unique_suffix from random_string
- [ ] T024 [US1] Define locals.tf location_abbr = "wus3"
- [ ] T025 [US1] [P] Define locals.tf resource group name (rg-avmlegacy-prod-wus3)
- [ ] T026 [US1] [P] Define locals.tf common_tags map with Environment, Workload, ManagedBy, Region, Spec
### Core Variables
- [ ] T027 [P] Define variables.tf location variable (default: westus3, validation: must equal westus3)
- [ ] T028 [P] Define variables.tf workload_name variable (default: avmlegacy)
- [ ] T029 [P] Define variables.tf environment variable (default: prod, validation: must equal prod)
- [ ] T030 [P] Define variables.tf tags variable (map of strings)
### Resource Group
- [ ] T031 [US1] Implement the Resource Group AVM module in terraform/main.tf (name from locals, location from var.location, tags from locals.common_tags)
- [ ] T032 [US1] Configure the Resource Group lock through the module lock interface (CanNotDelete per spec SEC-011)
### Log Analytics Workspace (Required for Diagnostic Settings)
- [ ] T033 Implement module block for Log Analytics Workspace in terraform/main.tf using Azure/avm-res-operationalinsights-workspace/azurerm
- [ ] T034 Configure Log Analytics SKU = PerGB2018, retention = 180 days (per spec clarifications)
- [ ] T035 Configure Log Analytics lock via AVM module lock interface (CanNotDelete)
- [ ] T036 [P] Define variables.tf log_analytics_retention_days variable (default: 180, validation: must equal 180)
- [ ] T037 Define locals.tf law_name using naming convention (law-avmlegacy-{suffix})
- [ ] T038 [P] Implement terraform/outputs.tf log_analytics_workspace_id output
- [ ] T039 [P] Implement terraform/outputs.tf log_analytics_workspace_name output
### Foundational Validation
- [ ] T040 Populate terraform/prod.tfvars with foundational variable values (location, workload_name, environment, tags)
- [ ] T041 Run terraform fmt -recursive to format all .tf files
- [ ] T042 Run terraform validate to check syntax
- [ ] T043 Run terraform plan -var-file=prod.tfvars to preview foundational resources (expect: Resource Group + Lock + Random resources + Log Analytics)
- [ ] T044 Review plan output for correctness (naming, tags, lock, retention)
- [ ] T045 Run terraform apply plan.tfplan to deploy foundational infrastructure
- [ ] T046 Verify Resource Group, random resources, and Log Analytics created in Azure Portal
**Phase 2 Validation**:
- β Resource Group deployed to westus3
- β Resource Group lock (CanNotDelete) applied
- β Random resources generated (suffix, password)
- β Log Analytics Workspace deployed with 180-day retention
- β Terraform state stored in remote backend
---
## Phase 3: User Story 1 (P1) - Core Compute and Network Infrastructure
**Objective**: Deploy Windows Server 2016 VM within isolated VNet with proper subnet segmentation and network security controls
**User Story**: Deploy a Windows Server 2016 virtual machine within an isolated virtual network with proper subnet segmentation and network security controls.
**Independent Test**: Verify VM is created and running in specified VNet with proper subnets. Confirm NSGs attached to subnets and default deny rules in place. VM should be isolated with no internet or external access.
**Prerequisites**: Phase 2 (Foundational) complete - Resource Group and Log Analytics exist
### Variables for Networking and VM
- [ ] T047 [P] [US1] Define variables.tf vnet_address_space variable (default: ["10.0.0.0/24"], validation: must equal 10.0.0.0/24)
- [ ] T048 [P] [US1] Define variables.tf vm_subnet_cidr variable (default: 10.0.0.0/27)
- [ ] T049 [P] [US1] Define variables.tf bastion_subnet_cidr variable (default: 10.0.0.32/26)
- [ ] T050 [P] [US1] Define variables.tf private_endpoint_subnet_cidr variable (default: 10.0.0.96/28)
- [ ] T051 [P] [US1] Define variables.tf vm_size variable (default: Standard_D2s_v3)
- [ ] T052 [P] [US1] Define variables.tf vm_admin_username variable (default: vmadmin, validation: must equal vmadmin)
- [ ] T053 [P] [US1] Define variables.tf vm_data_disk_size_gb variable (default: 500, validation: must equal 500)
- [ ] T054 [P] [US1] Define variables.tf availability_zone variable (default: 1, validation: must be 1, 2, or 3)
### Locals for Resource Naming
- [ ] T055 [US1] Define locals.tf vnet_name using naming convention (vnet-avmlegacy-{suffix})
- [ ] T056 [US1] [P] Define locals.tf vm_nsg_name (nsg-vm-avmlegacy-{suffix})
- [ ] T057 [US1] [P] Define locals.tf bastion_nsg_name (nsg-bastion-avmlegacy-{suffix})
- [ ] T058 [US1] [P] Define locals.tf private_endpoint_nsg_name (nsg-pe-avmlegacy-{suffix})
- [ ] T059 [US1] Define locals.tf vm_name_raw and vm_name (vm-avmlegacy-{suffix}, truncated to 15 chars for NetBIOS per spec FR-004)
- [ ] T060 [US1] Define locals.tf vm_computer_name = vm_name (same as VM name, ensures 15 char limit)
- [ ] T061 [US1] [P] Define locals.tf vm_subnet_name, bastion_subnet_name (AzureBastionSubnet exact), private_endpoint_subnet_name
### Virtual Network
- [ ] T062 [US1] Implement module block for VNet in terraform/main.tf using Azure/avm-res-network-virtualnetwork/azurerm
- [ ] T063 [US1] Configure VNet address_space = var.vnet_address_space (10.0.0.0/24)
- [ ] T064 [US1] Configure VNet subnets map with 3 subnets (vm_subnet, bastion_subnet, private_endpoint_subnet with CIDRs from variables)
- [ ] T065 [US1] Configure private_endpoint subnet with private_endpoint_network_policies_enabled = false (per spec IC-009)
- [ ] T066 [US1] Configure VNet diagnostic_settings sending logs to Log Analytics (reference module.log_analytics.resource_id)
- [ ] T067 [US1] Configure VNet lock via AVM module lock interface (CanNotDelete)
- [ ] T068 [US1] [P] Implement terraform/outputs.tf virtual_network_name output
- [ ] T069 [US1] [P] Implement terraform/outputs.tf virtual_network_id output
### Network Security Groups
- [ ] T070 [P] [US1] Implement module block for VM NSG in terraform/main.tf using Azure/avm-res-network-networksecuritygroup/azurerm
- [ ] T071 [US1] Configure VM NSG security_rules: Allow-RDP-From-Bastion (priority 100, source: bastion_subnet_cidr, dest: vm_subnet_cidr, port 3389, protocol TCP)
- [ ] T072 [US1] Configure VM NSG security_rules: Deny-All-Inbound (priority 4096, deny all per spec SEC-004)
- [ ] T073 [US1] Configure VM NSG diagnostic_settings sending logs to Log Analytics
- [ ] T074 [P] [US1] Implement module block for Bastion NSG in terraform/main.tf using Azure/avm-res-network-networksecuritygroup/azurerm
- [ ] T075 [US1] Configure Bastion NSG security_rules: Allow-HTTPS-Inbound (priority 100, source: Internet, port 443 per Azure Bastion requirement)
- [ ] T076 [US1] Configure Bastion NSG security_rules: Allow-GatewayManager-Inbound (priority 110, source: GatewayManager service tag, port 443)
- [ ] T077 [US1] Configure Bastion NSG security_rules: Allow-RDP-To-VM-Subnet (outbound, priority 100, dest: vm_subnet_cidr, port 3389)
- [ ] T078 [US1] Configure Bastion NSG security_rules: Allow-AzureCloud-Outbound (outbound, priority 110, dest: AzureCloud service tag, port 443)
- [ ] T079 [US1] Configure Bastion NSG diagnostic_settings sending logs to Log Analytics
- [ ] T080 [P] [US1] Implement module block for Private Endpoint NSG in terraform/main.tf using Azure/avm-res-network-networksecuritygroup/azurerm
- [ ] T081 [US1] Configure Private Endpoint NSG security_rules: Allow-SMB-From-VM-Subnet (priority 100, source: vm_subnet_cidr, port 445 per spec SEC-007)
- [ ] T082 [US1] Configure Private Endpoint NSG security_rules: Deny-All-Inbound (priority 4096, deny all)
- [ ] T083 [US1] Configure Private Endpoint NSG diagnostic_settings sending logs to Log Analytics
### NSG-Subnet Associations
- [ ] T084 [P] [US1] Configure the VNet module vm_subnet with module.vm_nsg.resource_id
- [ ] T085 [P] [US1] Configure the VNet module bastion_subnet with module.bastion_nsg.resource_id
- [ ] T086 [P] [US1] Configure the VNet module private_endpoint_subnet with module.private_endpoint_nsg.resource_id
### Virtual Machine
- [ ] T087 [US1] Implement module block for VM in terraform/main.tf using Azure/avm-res-compute-virtualmachine/azurerm
- [ ] T088 [US1] Configure VM name = locals.vm_name (truncated to 15 chars)
- [ ] T089 [US1] Configure VM computer_name = locals.vm_computer_name (same as name, β€15 chars per spec FR-004)
- [ ] T090 [US1] Configure VM vm_size = var.vm_size (Standard_D2s_v3)
- [ ] T091 [US1] Configure VM zone = var.availability_zone (1, 2, or 3 per spec FR-023)
- [ ] T092 [US1] Configure VM source_image_reference (publisher: MicrosoftWindowsServer, offer: WindowsServer, sku: 2016-Datacenter, version: latest)
- [ ] T093 [US1] Configure VM os_profile with admin_username = var.vm_admin_username (vmadmin)
- [ ] T094 [US1] Configure VM os_profile admin_password referencing Key Vault secret (will update in Phase 4 after Key Vault deployed - use placeholder for now)
- [ ] T095 [US1] Configure VM network_interfaces with nic1 connected to vm_subnet (subnet_id from module.virtual_network.subnets)
- [ ] T096 [US1] Configure VM network_interfaces with private_ip_address_allocation = Dynamic, public_ip_address_id = null (no public IP per spec FR-011)
- [ ] T097 [US1] Configure VM os_disk (name: {vm_name}-osdisk, caching: ReadWrite, storage_account_type: Standard_LRS per spec FR-002)
- [ ] T098 [US1] Configure VM data_disks with data1 (name: {vm_name}-datadisk, lun: 0, caching: ReadWrite, storage_account_type: Standard_LRS, disk_size_gb: 500 per spec FR-003)
- [ ] T099 [US1] Configure VM managed_identities with system_assigned = true (per spec SEC-001)
- [ ] T100 [US1] Configure VM diagnostic_settings sending logs to Log Analytics
- [ ] T101 [US1] Configure VM lock via AVM module lock interface (CanNotDelete per spec SEC-011)
- [ ] T102 [US1] Add depends_on for Key Vault module (will add in Phase 4)
- [ ] T103 [US1] [P] Implement terraform/outputs.tf vm_name output
- [ ] T104 [US1] [P] Implement terraform/outputs.tf vm_id output
- [ ] T105 [US1] [P] Implement terraform/outputs.tf vm_private_ip_address output
- [ ] T106 [US1] [P] Implement terraform/outputs.tf vm_computer_name output
### User Story 1 Deployment
- [ ] T107 [US1] Populate terraform/prod.tfvars with US1 variable values (vnet_address_space, subnet CIDRs, vm_size, vm_admin_username, availability_zone)
- [ ] T108 [US1] Run terraform fmt -recursive
- [ ] T109 [US1] Run terraform validate
- [ ] T110 [US1] Run terraform plan -var-file=prod.tfvars -out=us1.tfplan (expect: VNet + 3 subnets + 3 NSGs + 3 associations + VM with disks)
- [ ] T111 [US1] Review plan output for US1 completeness (check VM size, computer name β€15 chars, NSG rules, no public IP)
- [ ] T112 [US1] Run terraform apply us1.tfplan
- [ ] T113 [US1] Verify VM running in Azure Portal (check VM properties: size, computer name, admin username, no public IP)
- [ ] T114 [US1] Verify VNet has 3 subnets with correct CIDR allocations
- [ ] T115 [US1] Verify NSGs attached to each subnet
- [ ] T116 [US1] Verify NSG rules (VM NSG allows RDP from Bastion only, Bastion NSG allows HTTPS from Internet)
- [ ] T117 [US1] Verify VM has no external access (cannot reach internet, not reachable from internet)
**Phase 3 (US1) Validation**:
- β VM running with Standard_D2s_v3, Windows Server 2016, 500GB data disk
- β VNet (10.0.0.0/24) with 3 subnets created
- β NSGs attached to subnets with deny-by-default rules
- β VM isolated (no public IP, no internet access)
- β Computer name β€15 characters
- β VM admin username = vmadmin
**Parallel Execution Opportunities (US1)**:
- Tasks T047-T054 (variable definitions) can run in parallel
- Tasks T056-T058 (NSG naming locals) can run in parallel
- Tasks T070, T074, T080 (NSG module blocks) can run in parallel after VNet deployed
- Tasks T084-T086 (NSG associations) can run in parallel after NSGs created
- Tasks T103-T106 (output definitions) can run in parallel
---
## Phase 4: User Story 2 (P2) - Secure Remote Access
**Objective**: Enable secure remote access to VM through Azure Bastion and store VM administrator password securely in Azure Key Vault
**User Story**: Enable secure remote access to the virtual machine through Azure Bastion and store the VM administrator password securely in Azure Key Vault.
**Independent Test**: Verify administrators can connect to VM via Azure Bastion using credentials retrieved from Key Vault. Confirm VM has no public IP address.
**Prerequisites**: Phase 3 (US1) complete - VM and VNet deployed
### Variables for Key Vault and Bastion
- [ ] T118 [P] [US2] Define variables.tf vm_admin_secret_name variable (default: vm-admin-password for Key Vault secret name per spec FR-016)
### Locals for Resource Naming
- [ ] T119 [P] [US2] Define locals.tf bastion_name (bastion-avmlegacy-{suffix})
- [ ] T120 [P] [US2] Define locals.tf key_vault_name (kv-avmlegacy-{suffix}, note: 3-24 chars, globally unique)
### Key Vault
- [ ] T121 [US2] Implement module block for Key Vault in terraform/main.tf using Azure/avm-res-keyvault-vault/azurerm
- [ ] T122 [US2] Configure Key Vault name = locals.key_vault_name (3-24 chars)
- [ ] T123 [US2] Configure Key Vault tenant_id from data.azapi_client_config.current
- [ ] T124 [US2] Configure Key Vault sku_name = standard
- [ ] T125 [US2] Configure Key Vault soft_delete_retention_days = 90, purge_protection_enabled = true (per spec SEC-012)
- [ ] T126 [US2] Configure Key Vault enable_rbac_authorization = true (use RBAC vs access policies per plan)
- [ ] T127 [US2] Configure Key Vault secrets interface with vm_admin_password secret (name: var.vm_admin_secret_name, value: random_password.vm_admin_password.result)
- [ ] T128 [US2] Configure Key Vault diagnostic_settings sending logs to Log Analytics
- [ ] T129 [US2] Configure Key Vault lock via AVM module lock interface (CanNotDelete per spec SEC-011)
- [ ] T130 [US2] Add depends_on = [random_password.vm_admin_password]
- [ ] T131 [US2] [P] Implement terraform/outputs.tf key_vault_name output
- [ ] T132 [US2] [P] Implement terraform/outputs.tf key_vault_id output
- [ ] T133 [US2] [P] Implement terraform/outputs.tf key_vault_uri output
- [ ] T134 [US2] [P] Implement terraform/outputs.tf vm_admin_secret_name output (sensitive = true)
### Key Vault RBAC for Deployment Identity
- [ ] T135 [US2] Implement data.azapi_client_config.current in terraform/main.tf
- [ ] T136 [US2] Configure the Key Vault module role_assignments interface for the deployment identity (role: Key Vault Secrets Officer, principal_id: current identity)
### Update VM to Reference Key Vault Secret
- [ ] T137 [US2] Update VM module in terraform/main.tf to reference Key Vault secret for admin_password (module.key_vault.secrets[var.vm_admin_secret_name].value)
- [ ] T138 [US2] Update VM module depends_on to include module.key_vault
### Azure Bastion
- [ ] T139 [US2] Implement module block for Bastion in terraform/main.tf using Azure/avm-res-network-bastionhost/azurerm
- [ ] T140 [US2] Configure Bastion name = locals.bastion_name
- [ ] T141 [US2] Configure Bastion subnet_id referencing VNet module bastion_subnet (module.virtual_network.subnets["bastion_subnet"].id)
- [ ] T142 [US2] Configure Bastion sku = Basic (or Standard based on Phase 0 research cost analysis)
- [ ] T143 [US2] Configure Bastion lock via AVM module lock interface (CanNotDelete)
- [ ] T144 [US2] [P] Implement terraform/outputs.tf bastion_name output
- [ ] T145 [US2] [P] Implement terraform/outputs.tf bastion_id output
### Bastion Connection Instructions
- [ ] T146 [US2] Implement terraform/outputs.tf bastion_connect_instructions output with multi-line instructions (Portal navigation, username, password retrieval command)
### User Story 2 Deployment
- [ ] T147 [US2] Populate terraform/prod.tfvars with US2 variable values (vm_admin_secret_name)
- [ ] T148 [US2] Run terraform fmt -recursive
- [ ] T149 [US2] Run terraform validate
- [ ] T150 [US2] Run terraform plan -var-file=prod.tfvars -out=us2.tfplan (expect: Key Vault + secret + RBAC + Bastion + VM update)
- [ ] T151 [US2] Review plan output for US2 completeness (check Key Vault soft-delete, purge protection, secret stored, Bastion SKU)
- [ ] T152 [US2] Run terraform apply us2.tfplan
- [ ] T153 [US2] Verify Key Vault created with soft-delete and purge protection enabled
- [ ] T154 [US2] Verify Key Vault secret exists with name from vm_admin_secret_name variable
- [ ] T155 [US2] Retrieve password from Key Vault using Azure CLI: az keyvault secret show --name [secret-name] --vault-name [kv-name] --query value -o tsv
- [ ] T156 [US2] Verify Bastion deployed and connected to AzureBastionSubnet
- [ ] T157 [US2] Test RDP connection via Bastion (Portal β VM β Connect β Bastion, use vmadmin username and Key Vault password)
- [ ] T158 [US2] Verify VM has no public IP address (confirm from VM properties)
**Phase 4 (US2) Validation**:
- β Key Vault deployed with soft-delete and purge protection
- β VM admin password stored in Key Vault secret
- β Bastion deployed and connected to VNet
- β RDP connection successful via Bastion using Key Vault password
- β VM has no public IP address
**Parallel Execution Opportunities (US2)**:
- Tasks T118 (variable), T119-T120 (locals) can run in parallel
- Tasks T131-T134 (Key Vault outputs) can run in parallel
- Tasks T144-T145 (Bastion outputs) can run in parallel
---
## Phase 5: User Story 3 (P3) - Application Storage Integration
**Objective**: Provide secure access to Azure Files share for application data storage via private endpoint
**User Story**: Provide secure access to an Azure Files share for application data storage, connected via private endpoint to ensure data does not traverse the public internet.
**Independent Test**: From VM, mount Azure Files share using private endpoint IP. Verify data can be written to and read from the share without public internet connectivity.
**Prerequisites**: Phase 3 (US1) and Phase 4 (US2) complete - VM, VNet, and Key Vault deployed
### Variables for Storage
- [ ] T159 [P] [US3] Define variables.tf file_share_name variable (default: legacyappdata)
- [ ] T160 [P] [US3] Define variables.tf file_share_quota_gb variable (default: 1024, validation: must equal 1024 per spec clarifications)
### Locals for Storage Naming
- [ ] T161 [P] [US3] Define locals.tf storage_account_name (stavmlegacy{suffix}, lowercase alphanumeric, max 24 chars)
- [ ] T162 [P] [US3] Define locals.tf private_endpoint_name (pe-storage-avmlegacy-{suffix})
### Storage Account with File Share
- [ ] T163 [US3] Implement module block for Storage Account in terraform/main.tf using Azure/avm-res-storage-storageaccount/azurerm
- [ ] T164 [US3] Configure Storage Account name = locals.storage_account_name (lowercase alphanumeric)
- [ ] T165 [US3] Configure Storage Account account_kind = StorageV2
- [ ] T166 [US3] Configure Storage Account account_tier = Standard, account_replication_type = LRS (HDD per spec IC-007)
- [ ] T167 [US3] Configure Storage Account public_network_access_enabled = false (per spec SEC-009)
- [ ] T168 [US3] Configure Storage Account enable_infrastructure_encryption = true (per spec SEC-013)
- [ ] T169 [US3] Configure Storage Account file_shares with legacy_app_data share (name: var.file_share_name, quota: var.file_share_quota_gb, tier: TransactionOptimized)
- [ ] T170 [US3] Configure Storage Account private_endpoints interface for file subresource (check if built-in or need separate module per Phase 0 research Task 6)
- [ ] T171 [US3] Configure private endpoint name = locals.private_endpoint_name, subnet_resource_id = private_endpoint_subnet, subresource_names = ["file"]
- [ ] T172 [US3] Configure private endpoint private_dns_zone_group_name = "file-private-dns" (auto-create or existing zone per research)
- [ ] T173 [US3] Configure Storage Account diagnostic_settings sending logs to Log Analytics
- [ ] T174 [US3] Configure Storage Account lock via AVM module lock interface (CanNotDelete per spec SEC-011)
- [ ] T175 [US3] [P] Implement terraform/outputs.tf storage_account_name output
- [ ] T176 [US3] [P] Implement terraform/outputs.tf storage_account_id output
- [ ] T177 [US3] [P] Implement terraform/outputs.tf file_share_name output
### File Share Mount Instructions
- [ ] T178 [US3] Implement terraform/outputs.tf file_share_mount_instructions output with PowerShell commands for mounting from VM
### User Story 3 Deployment
- [ ] T179 [US3] Populate terraform/prod.tfvars with US3 variable values (file_share_name, file_share_quota_gb)
- [ ] T180 [US3] Run terraform fmt -recursive
- [ ] T181 [US3] Run terraform validate
- [ ] T182 [US3] Run terraform plan -var-file=prod.tfvars -out=us3.tfplan (expect: Storage Account + file share + private endpoint)
- [ ] T183 [US3] Review plan output for US3 completeness (check public_network_access = false, file share quota = 1TB, private endpoint connected)
- [ ] T184 [US3] Run terraform apply us3.tfplan
- [ ] T185 [US3] Verify Storage Account created with Standard_LRS replication
- [ ] T186 [US3] Verify file share created with 1TB quota (1024GB)
- [ ] T187 [US3] Verify Storage Account has public network access disabled
- [ ] T188 [US3] Verify private endpoint created and connected to private_endpoint_subnet
- [ ] T189 [US3] Test file share mounting from VM via Bastion RDP session (use output file_share_mount_instructions)
- [ ] T190 [US3] From VM: Run net use Z: \\[storage-account-name].privatelink.file.core.windows.net\[file-share-name]
- [ ] T191 [US3] From VM: Test write access by creating a test file on Z: drive
- [ ] T192 [US3] From VM: Test read access by reading the test file from Z: drive
- [ ] T193 [US3] Verify DNS resolution from VM resolves storage FQDN to private endpoint IP (not public IP)
**Phase 5 (US3) Validation**:
- β Storage Account deployed with Standard_LRS, no public access
- β File share created with 1TB quota
- β Private endpoint deployed and connected to VNet
- β File share accessible from VM via private endpoint (mount successful)
- β Read/write operations successful on mounted file share
- β DNS resolves to private IP (not public IP)
**Parallel Execution Opportunities (US3)**:
- Tasks T159-T160 (variables) can run in parallel
- Tasks T161-T162 (locals) can run in parallel
- Tasks T175-T177 (outputs) can run in parallel
---
## Phase 6: User Story 4 (P4) - Internet Access and Observability
**Objective**: Enable outbound internet access via NAT Gateway and implement comprehensive monitoring through Log Analytics with critical alerts
**User Story**: Enable outbound internet access via NAT Gateway for Windows Updates and patches, and implement comprehensive monitoring through Log Analytics with diagnostic logging and critical alerts.
**Independent Test**: From VM, verify outbound internet connectivity (e.g., download Windows Update). Confirm diagnostic logs flowing to Log Analytics and test alerts trigger correctly.
**Prerequisites**: Phase 3 (US1), Phase 4 (US2), Phase 5 (US3) complete - All infrastructure deployed
### Variables for NAT Gateway and Alerts
- [ ] T194 [P] [US4] Define variables.tf alert_action_group_email variable (no default - must be provided in tfvars)
### Locals for NAT Gateway and Alerts
- [ ] T195 [P] [US4] Define locals.tf nat_gateway_name (nat-avmlegacy-{suffix})
- [ ] T196 [P] [US4] Define locals.tf nat_public_ip_name (pip-nat-avmlegacy-{suffix})
- [ ] T197 [P] [US4] Define locals.tf action_group_name (ag-avmlegacy-{suffix})
### NAT Gateway
- [ ] T198 [US4] Implement module block for NAT Gateway in terraform/main.tf using Azure/avm-res-network-natgateway/azurerm
- [ ] T199 [US4] Configure NAT Gateway name = locals.nat_gateway_name
- [ ] T200 [US4] Configure NAT Gateway public_ip_addresses with pip-nat public IP (name: locals.nat_public_ip_name, zones: [var.availability_zone])
- [ ] T201 [US4] Configure NAT Gateway subnet_associations with vm_subnet (subnet_id from module.virtual_network.subnets["vm_subnet"].id)
- [ ] T202 [US4] [P] Implement terraform/outputs.tf nat_gateway_name output
- [ ] T203 [US4] [P] Implement terraform/outputs.tf nat_gateway_public_ip output
### Action Group for Alerts
- [ ] T204 [US4] Implement an AzAPI `Microsoft.Insights/actionGroups` resource in terraform/main.tf (name: locals.action_group_name, short name: avmalerts)
- [ ] T205 [US4] Configure action group email_receiver (name: admin-email, email_address: var.alert_action_group_email)
### Metric Alerts
- [ ] T206 [P] [US4] Implement an AzAPI `Microsoft.Insights/metricAlerts` resource for VM stopped in terraform/main.tf (name: alert-vm-stopped-{vm_name}, scope: VM ID)
- [ ] T207 [US4] Configure VM stopped alert criteria (metric: VmAvailabilityMetric, aggregation: Average, operator: LessThan, threshold: 1, severity: 0)
- [ ] T208 [US4] Configure VM stopped alert frequency = PT5M, window_size = PT5M
- [ ] T209 [US4] Configure VM stopped alert action referencing action group
- [ ] T210 [P] [US4] Implement an AzAPI `Microsoft.Insights/metricAlerts` resource for VM disk usage in terraform/main.tf (name: alert-vm-disk-usage-{vm_name}, scope: VM ID)
- [ ] T211 [US4] Configure VM disk alert criteria (metric: OS Disk Used Percent, aggregation: Average, operator: GreaterThan, threshold: 90, severity: 0)
- [ ] T212 [US4] Configure VM disk alert frequency = PT15M, window_size = PT15M
- [ ] T213 [US4] Configure VM disk alert action referencing action group
- [ ] T214 [P] [US4] Implement an AzAPI `Microsoft.Insights/metricAlerts` resource for Key Vault access failures in terraform/main.tf (name: alert-kv-access-failures-{kv_name}, scope: Key Vault ID)
- [ ] T215 [US4] Configure Key Vault alert criteria (metric: ServiceApiResult, aggregation: Count, operator: GreaterThan, threshold: 0, severity: 0)
- [ ] T216 [US4] Configure Key Vault alert dimension filter (name: StatusCode, operator: Include, values: ["403"])
- [ ] T217 [US4] Configure Key Vault alert frequency = PT5M, window_size = PT5M
- [ ] T218 [US4] Configure Key Vault alert action referencing action group
### User Story 4 Deployment
- [ ] T219 [US4] Populate terraform/prod.tfvars with US4 variable values (alert_action_group_email - **UPDATE THIS**)
- [ ] T220 [US4] Run terraform fmt -recursive
- [ ] T221 [US4] Run terraform validate
- [ ] T222 [US4] Run terraform plan -var-file=prod.tfvars -out=us4.tfplan (expect: NAT Gateway + public IP + action group + 3 alerts)
- [ ] T223 [US4] Review plan output for US4 completeness (check NAT Gateway associated with vm_subnet, alerts configured with correct thresholds)
- [ ] T224 [US4] Run terraform apply us4.tfplan
- [ ] T225 [US4] Verify NAT Gateway deployed with public IP
- [ ] T226 [US4] Verify NAT Gateway associated with vm_subnet
- [ ] T227 [US4] Test outbound internet connectivity from VM via Bastion RDP session (`Invoke-WebRequest -Uri "https://www.microsoft.com" -UseBasicParsing`)
- [ ] T228 [US4] Verify VM cannot receive inbound connections from internet (remains inaccessible)
- [ ] T229 [US4] Verify diagnostic logs from VM in Log Analytics (run query: Perf | where Computer startswith "vm-avmlegacy" | take 10)
- [ ] T230 [US4] Verify diagnostic logs from Key Vault in Log Analytics (run query: AzureDiagnostics | where ResourceType == "VAULTS" | take 10)
- [ ] T231 [US4] Verify diagnostic logs from Storage Account in Log Analytics
- [ ] T232 [US4] Test VM stopped alert by stopping VM in Portal (wait 5 minutes, verify alert notification)
- [ ] T233 [US4] Test alert action group email notification received
- [ ] T234 [US4] Start VM after alert test
**Phase 6 (US4) Validation**:
- β NAT Gateway deployed and associated with vm_subnet
- β VM has outbound internet access via NAT Gateway
- β VM remains inaccessible from internet (inbound blocked)
- β Diagnostic logs flowing to Log Analytics from VM, Key Vault, Storage Account
- β 3 metric alerts configured and functional (VM stopped, disk >90%, Key Vault failures)
- β Alert notifications delivered to action group
**Parallel Execution Opportunities (US4)**:
- Tasks T195-T197 (locals) can run in parallel
- Tasks T202-T203 (NAT Gateway outputs) can run in parallel
- Tasks T206, T210, T214 (alert resource creation) can run in parallel after action group created
---
## Phase 7: Polish & Cross-Cutting Concerns
**Objective**: Final validation, documentation, cost analysis, and CI/CD pipeline setup (optional)
**Prerequisites**: All user stories (US1-US4) complete and validated
### Final Terraform Validation
- [ ] T235 Run terraform fmt -recursive -check to ensure all files formatted
- [ ] T236 Run terraform validate to ensure no syntax errors
- [ ] T237 Run tfsec . to scan for security issues (expect: zero HIGH or CRITICAL findings per spec SC-009)
- [ ] T238 Run checkov -d . to scan for compliance issues
- [ ] T239 Address any HIGH or CRITICAL findings from security scans
### Cost Validation
- [ ] T240 Use Azure Pricing Calculator to estimate monthly cost of deployed infrastructure
- [ ] T241 Verify estimated cost is under $200/month per spec SC-013
- [ ] T242 Document cost breakdown in docs/README.md (VM, Bastion, NAT Gateway, Log Analytics, Storage, Key Vault)
### Documentation Finalization
- [ ] T243 Update terraform/README.md with complete deployment instructions (prerequisites, backend setup, variable customization, deployment steps)
- [ ] T244 Update docs/README.md with project overview (architecture summary, cost estimate, deployment time estimate)
- [ ] T245 Update docs/architecture.md with infrastructure diagram (VNet topology, resource relationships, security boundaries)
- [ ] T246 Document all outputs in terraform/README.md (how to retrieve VM password, connect via Bastion, mount file share)
- [ ] T247 Create terraform/prod.tfvars.example with all variables and rich comments (remove sensitive values)
### Deployment Success Criteria Verification
- [ ] T248 Verify SC-001: Infrastructure deployment completed within 30 minutes (time terraform apply)
- [ ] T249 Verify SC-002: RDP connection via Bastion established within 2 minutes
- [ ] T250 Verify SC-003: VM password from Key Vault successfully authenticates RDP session (100% success rate)
- [ ] T251 Verify SC-004: VM can mount Azure Files share and perform read/write operations
- [ ] T252 Verify SC-005: VM can download content from internet via NAT Gateway (test Windows Update or HTTP GET)
- [ ] T253 Verify SC-006: VM is NOT reachable via direct internet connection (external port scan shows no open ports)
- [ ] T254 Verify SC-007: Diagnostic logs from VM, Key Vault, Storage appear in Log Analytics within 15 minutes
- [ ] T255 Verify SC-008: Critical alerts trigger within 5 minutes (test VM stopped alert)
- [ ] T256 Verify SC-009: terraform fmt -check, terraform validate, tfsec pass with zero HIGH/CRITICAL findings
- [ ] T257 Verify SC-010: All values from terraform.tfvars (no hardcoded values in main.tf)
- [ ] T258 Verify SC-011: AVM module variables correctly structured per module documentation
- [ ] T259 Verify SC-012: VM computer name is 15 characters or fewer
- [ ] T260 Verify SC-013: Total monthly cost under $200/month
### Optional CI/CD Pipeline
- [ ] T261 [P] Create .github/workflows/terraform-validate.yml for CI/CD pipeline
- [ ] T262 [P] Configure pipeline to run terraform fmt -check on pull requests
- [ ] T263 [P] Configure pipeline to run terraform validate on pull requests
- [ ] T264 [P] Configure pipeline to run tfsec scan on pull requests
- [ ] T265 [P] Configure pipeline to fail on HIGH or CRITICAL security findings
- [ ] T266 [P] Test pipeline by creating a test pull request
### Final Acceptance
- [ ] T267 Execute complete teardown and redeploy to verify infrastructure is fully recreatable (terraform destroy β terraform apply)
- [ ] T268 Time full deployment from scratch (should complete within 30 minutes per SC-001)
- [ ] T269 Document actual deployment time and cost in docs/README.md
**Phase 7 Validation**:
- β All 13 success criteria (SC-001 through SC-013) met
- β Terraform validation passing (fmt, validate, tfsec, checkov)
- β Cost under $200/month confirmed
- β Complete documentation available (README, architecture, deployment guide)
- β Infrastructure fully recreatable from Terraform
---
## Dependencies Summary
### Phase Dependencies
```text
Phase 1 (Setup)
β
Phase 2 (Foundational) [BLOCKS all user stories]
β
Phase 3 (US1 - Core Compute) [BLOCKS all subsequent stories]
β
Phase 4 (US2 - Secure Access) [Independent of US3, US4]
β
Phase 5 (US3 - Storage) [Independent of US4, depends on US1+US2]
β
Phase 6 (US4 - Observability) [Depends on US1+US2+US3]
β
Phase 7 (Polish) [Depends on all user stories]
```### Critical Path
1. Setup (Phase 1) β Foundational (Phase 2) β US1 (Phase 3) β US2 (Phase 4) β US3 (Phase 5) β US4 (Phase 6) β Polish (Phase 7)
### Parallel Opportunities
- **Setup Phase**: Tasks T005-T010 (Terraform file shells), T014-T016 (tooling installation)
- **Foundational Phase**: Variable definitions (T027-T030), outputs (T038-T039)
- **US1 Phase**: Variable definitions (T047-T054), NSG module blocks (T070, T074, T080), NSG associations (T084-T086), outputs (T068-T069, T103-T106)
- **US2 Phase**: Variable/locals (T118-T120), Key Vault outputs (T131-T134), Bastion outputs (T144-T145)
- **US3 Phase**: Variables (T159-T160), locals (T161-T162), outputs (T175-T177)
- **US4 Phase**: Locals (T195-T197), NAT Gateway outputs (T202-T203), alert resource creation (T206, T210, T214)
- **Polish Phase**: CI/CD pipeline tasks (T261-T266)
---
## Notes
### Tests
- **Not Generated**: Per spec, no test infrastructure requested. User story acceptance scenarios serve as manual test criteria.
### MVP Recommendation
- **Suggested MVP**: Complete through Phase 4 (US1 + US2) for minimum viable secure infrastructure (VM with RDP access via Bastion, password in Key Vault)
- **Optional for MVP**: US3 (Storage) and US4 (Observability) can be deferred
### File Share Mount
- **Post-Deployment Manual Step**: File share mounting to VM is manual per spec clarifications (no automation, aligns with IaC-first principle)
- **Instructions**: Provided in terraform/outputs.tf file_share_mount_instructions output
### AVM Module Versions
- **Research Required**: Phase 0 research (plan.md Phase 0) must verify latest AVM module versions from Terraform Registry before implementation
- **Version Constraints**: Use pessimistic versioning (~> X.Y.0) per constitution Principle II
### Constitution Compliance
- **All tasks align with**: Constitution Principles I-V (Terraform-first, AVM-only, Security/Reliability, Single-template, Validation-first)
- **No local modules**: All tasks use AVM modules exclusively (no custom module creation)
### Validation Gates
- **Between Phases**: Run terraform fmt β validate β plan β review before apply
- **Security Scanning**: Run tfsec and checkov before final deployment
- **Manual Testing**: Each user story has independent test criteria in spec.md
---
**End of Tasks Document****Total Tasks**: 269
**Estimated Implementation Time**: 20-30 hours (including research, implementation, testing, documentation)
**Deployment Time**: ~30 minutes per spec SC-001
**Cost**: <$200/month per spec SC-013
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture your task list, with a comment of something like Tasks generated.
7. Analyze (Optional)
Spec Kit uses /speckit.analyze to generate an analysis report. The prompt doesn’t require any specific inputs as it analyzes the existing spec, plan and tasks to produce the report.
Info
To learn more about the analyze step, see the Analyze chapter in the Spec Kit article.
Run the following prompt to generate an analysis report for our example:
/speckit.analyze
β Expand to see the results
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
In the Copilot chat window, you should see something like this:
<!-- markdownlint-disable --># Specification Analysis Report
**Feature**: 001-legacy-vm-workload
**Analyzed Files**: spec.md, plan.md, tasks.md, constitution.md
**Date**: 2026-01-26
**Analysis Mode**: READ-ONLY (no modifications applied)
---
## Executive Summary
Analyzed **24 functional requirements**, **4 user stories**, and **61 implementation tasks** across the specification artifacts. Identified **16 findings** (0 CRITICAL, 5 HIGH, 8 MEDIUM, 3 LOW). Constitution compliance: **100% aligned** with all 5 principles satisfied. Primary concerns: **ambiguous terminology** (Standard HDD), **missing technical specifications** (AVM module versions, NSG rules, encryption details), and **underspecified monitoring thresholds**.
**Overall Assessment**: β **SAFE TO PROCEED** with implementation after resolving 5 HIGH severity issues. No CRITICAL or constitution-blocking issues detected.
---
## Findings
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| A1 | Ambiguity | HIGH | spec.md:FR-003, FR-008, tasks.md:T025, T030, T033 | "Standard HDD" not mapped to explicit Azure SKU (Standard_LRS vs StandardSSD_LRS) | Specify `Standard_LRS` explicitly in spec FR-003, FR-008; update tasks T025, T030, T033 with SKU name |
| A2 | Underspecification | HIGH | spec.md:FR-022, tasks.md:T040 | "Disk utilization >90%" threshold ambiguous - percentage of what? (capacity, IOPS, throughput) | Clarify as "OS disk used capacity >90%" or "Data disk used capacity >90%"; specify which disk(s) |
| A3 | Underspecification | HIGH | spec.md:FR-020, plan.md, tasks.md:T012 | NSG rules incomplete - missing explicit allow rules for Key Vault (443), storage (445), Log Analytics (443) | Document required outbound NSG rules: Azure services (AzureCloud service tag) port 443 for KV/Storage/LA |
| A4 | Coverage Gap | HIGH | spec.md:FR-011, tasks.md:T013-T015 | Password complexity requirements not validated against Azure VM password policy (12-123 chars, 3 of 4 types) | Add validation task or clarify password generation formula meets Azure requirements |
| A5 | Underspecification | HIGH | All documents | AVM module version constraints missing - no "latest stable" definition or version pinning strategy | Add research task to query MCR for latest versions; specify version pinning strategy (exact vs ^0.x) |
| U1 | Underspecification | MEDIUM | spec.md:FR-019, tasks.md:T016, T020, T027, T036 | Diagnostic log categories not specified - which logs to collect per resource type? | Define log categories: VM (Performance, Security), KV (AuditEvent), Storage (Transaction, StorageRead) |
| U2 | Inconsistency | MEDIUM | spec.md:US4 acceptance scenario, plan.md | Key Vault access model conflict - spec mentions "access policies", plan says "RBAC". Which to use? | Resolve: Use RBAC per plan (T015 specifies enableRbacAuthorization: true); update spec to remove access policies reference |
| U3 | Coverage Gap | MEDIUM | spec.md, tasks.md | Encryption-at-rest requirements implicit but not explicit for VM disks, storage account, Key Vault | Add requirement: "All storage must use Azure-managed encryption at rest" or assume default encryption |
| U4 | Underspecification | MEDIUM | spec.md:FR-022, tasks.md:T039-T041 | Alert notification destinations undefined - who receives alerts? Email? Action group? | Document assumption: Alert rules created without notification actions (configured post-deployment) |
| U5 | Inconsistency | MEDIUM | spec.md:FR-016, plan.md, tasks.md:T007 | Availability zone terminology: spec says "selection", plan/tasks say "parameter" - is it user choice or fixed? | Clarify: availabilityZone is a parameter with default 1; user can select 1, 2, or 3 (not random assignment) |
| U6 | Underspecification | MEDIUM | spec.md:FR-024, plan.md | File share growth monitoring "documented procedures" - what procedures? Manual check? Alert? | Specify: Document manual procedure to query file share usage via Azure CLI/Portal; no automated monitoring |
| U7 | Coverage Gap | MEDIUM | spec.md, tasks.md:T028 | VM boot diagnostics storage account not specified - uses managed storage or custom? | Add clarification: Use managed boot diagnostics (no separate storage account); T028 should specify this |
| U8 | Underspecification | MEDIUM | spec.md:FR-014, plan.md, tasks.md:T009 | Random suffix generation uses uniqueString(resourceGroup().id) - what's the character length? | Specify: 6-character suffix using substring(uniqueString(resourceGroup().id), 0, 6) |
| T1 | Terminology Drift | LOW | spec.md uses "Azure Storage Account", tasks.md uses "Storage Account" | Minor inconsistency in terminology - not functionally impactful | Standardize on "Storage Account" throughout |
| T2 | Duplication | LOW | spec.md:FR-005, FR-017 + plan.md Technical Context | Resource group designation repeated - spec says "production", plan implies via parameter 'environment' | Consolidate: Resource group is deployment target (not created by template); environment tag controlled by parameter |
| T3 | Coverage Gap | LOW | tasks.md:T002 | No task detail for creating bicepconfig.json analyzer rules despite constitution principle IV requiring it | Add detail to T002: Include analyzer rule `use-recent-module-versions: warning` in bicepconfig.json |
---
## Coverage Summary
### Requirements-to-Tasks Mapping
| Requirement Key | Has Task? | Task IDs | Coverage Status |
|-----------------|-----------|----------|-----------------|
| FR-001 (WinServer2016 US West 3) | β | T006, T023 | β Covered by location param + imageReference |
| FR-002 (2 cores, 8GB RAM) | β | T023 | β vmSize parameter (Standard_D2s_v3) |
| FR-003 (Standard HDD OS) | β | T025 | β οΈ Ambiguous - need SKU clarification (A1) |
| FR-004 (500GB data disk) | β | T030 | β οΈ Ambiguous - need SKU clarification (A1) |
| FR-005 (Single RG) | β | Implicit | β Deployment target (no task needed) |
| FR-006 (VNet) | β | T011 | β 3 subnets defined |
| FR-007 (Bastion) | β | T018-T021 | β Fully covered |
| FR-008 (Storage + file share) | β | T032-T033 | β οΈ Ambiguous SKU (A1) |
| FR-009 (Private endpoint) | β | T035 | β Covered |
| FR-010 (Key Vault) | β | T014 | β Covered |
| FR-011 (Password gen + store) | β | T013, T015 | β οΈ Complexity validation gap (A4) |
| FR-012 (Username = administrator) | β | T024, T053 | β Covered |
| FR-013 (Secret name param) | β | T015, T053 | β Covered |
| FR-014 (Naming convention) | β | T009 + all resources | β οΈ Length not specified (U8) |
| FR-015 (AVM modules only) | β | All module tasks | β οΈ No version constraints (A5) |
| FR-016 (Zones 1-3) | β | T007 | β οΈ Terminology inconsistency (U5) |
| FR-017 (Parameter-driven) | β | T005-T008, T053 | β Covered |
| FR-018 (CanNotDelete locks) | β | T017, T021, T029, T031, T037, T038 | β Covered |
| FR-019 (Diagnostic logging) | β | T016, T020, T027, T036 | β οΈ Log categories unspecified (U1) |
| FR-020 (NSG rules) | β | T012 | β οΈ Incomplete rules (A3) |
| FR-021 (No public access) | β | T034 | β Covered |
| FR-022 (Critical alerts) | β | T039-T041 | β οΈ Threshold + notification gaps (A2, U4) |
| FR-023 (Log Analytics) | β | T010 | β Covered |
| FR-024 (File share growth) | β | Documented in spec | β οΈ Procedure undefined (U6) |
**Coverage %**: **100%** (24/24 requirements have associated tasks)
### User Story Coverage
| User Story | Priority | Tasks | Coverage Status |
|------------|----------|-------|-----------------|
| US1 - Core VM Infrastructure | P1 (MVP) | T018-T021, T022-T029 | β Fully covered (9 tasks) |
| US2 - Attach Additional Storage | P2 | T030-T031 | β Fully covered (2 tasks) |
| US3 - Connect to Secure File Share | P3 | T032-T038 | β Fully covered (7 tasks) |
| US4 - Secure Secret Management | P1 (MVP) | T013-T017 | β Fully covered (5 tasks) |
**User Story Coverage**: 100% (all 4 stories have complete task coverage)
---
## Constitution Alignment Issues
**Status**: β **ZERO VIOLATIONS** - All 5 constitution principles are fully satisfied
| Principle | Status | Evidence | Risk Level |
|-----------|--------|----------|------------|
| I. AVM-Only Modules | β PASS | Tasks T010-T041 reference only AVM modules from br/public:avm/... registry; zero direct resource declarations planned | None |
| II. IaC-First Approach | β PASS | Single main.bicep (T004), no custom scripts/CSE, ARM incremental mode, manual post-deployment file share mounting (T058) | None |
| III. Security & Reliability | β PASS | Private endpoints (T035), Key Vault (T014-T015), CanNotDelete locks (T017, T021, T029, T031, T037, T038), diagnostic logs (T016, T020, T027, T036), NSG (T012) | None |
| IV. Pre-Deployment Validation | β PASS | Tasks T054-T055 explicitly mandate `az deployment group validate` + ARM What-If review before deployment (T056) | None |
| V. Naming Convention & Regional Standards | β PASS | Naming via T009 (uniqueString suffix), location=westus3 (T006), zones 1-3 (T007), CAF abbreviations in all resource names | None |
**Constitution Compliance Score**: 100% (5/5 principles satisfied)
---
## Unmapped Tasks
**Status**: β **ZERO UNMAPPED TASKS**All 61 tasks map to at least one requirement, user story, or infrastructure prerequisite:
- **Setup tasks (T001-T003)**: Infrastructure initialization (required for all user stories)
- **Foundational tasks (T004-T012)**: Shared resources (Log Analytics, VNet, NSG) - prerequisite for all user stories
- **User story tasks (T013-T038)**: Direct mapping to US1, US2, US3, US4
- **Polish tasks (T039-T053)**: Cross-cutting concerns (alerts, outputs, parameters)
- **Validation tasks (T054-T061)**: Post-implementation verification
---
## Metrics
### Quantitative Analysis
- **Total Functional Requirements**: 24 (FR-001 through FR-024)
- **Total User Stories**: 4 (US1-P1, US2-P2, US3-P3, US4-P1)
- **Total Implementation Tasks**: 61 (T001 through T061)
- **Total Entities (Data Model)**: 12 Azure resources
- **Total Input Parameters**: 11 (3 required, 8 optional with defaults)
- **Total Output Values**: 10
### Coverage Metrics
- **Requirements Coverage**: 100% (24/24 requirements have β₯1 task)
- **User Story Coverage**: 100% (4/4 stories have complete task sets)
- **Constitution Compliance**: 100% (5/5 principles satisfied)
- **Task-to-Requirement Traceability**: 100% (all 61 tasks map to requirements or prerequisites)
### Quality Metrics
- **Ambiguity Count**: 5 findings (A1, A2, U1, U2, U8)
- **Duplication Count**: 1 finding (T2)
- **Underspecification Count**: 9 findings (A2, A3, A4, A5, U1, U4, U6, U7, U8)
- **Coverage Gaps**: 4 findings (A4, U3, U7, T3)
- **Inconsistencies**: 2 findings (U2, U5)
- **Terminology Drift**: 1 finding (T1)
### Severity Distribution
- **CRITICAL Issues**: 0 (deployment blockers)
- **HIGH Issues**: 5 (implementation ambiguity, missing technical specs)
- **MEDIUM Issues**: 8 (specification gaps, inconsistencies)
- **LOW Issues**: 3 (documentation polish, minor gaps)
- **Total Findings**: 16
---
## Dependency Analysis
### Critical Path Dependencies
```
Log Analytics (T010)
β
VNet + NSG (T011-T012) βββββ
β β
Key Vault + Password ββββββββ€
(T013-T017) β
β β
VM + Bastion ββββββββββββββββ
(T018-T029)
β
Data Disk (T030-T031)
β
Storage + Private Endpoint (T032-T038)
β
Alerts + Outputs (T039-T051)
β
Validation (T054-T061)
```### Parallelization Opportunities
**35 tasks marked [P]** can execute in parallel:
1.**Phase 2 - Foundational** (after Log Analytics + VNet):
- T005-T008 (Parameters) - 4 tasks in parallel
- T012 (NSG) can overlap with T010-T011
2.**Phase 3 - MVP** (after Key Vault complete):
- T018-T021 (Bastion) parallel with T022-T029 (VM) - both depend on VNet only
3.**Phase 4-5** (after Foundation):
- T030-T031 (Data Disk) parallel with T032-T038 (Storage + PE) - no mutual dependency
4.**Phase 6 - Polish**:
- T039-T041 (Alert Rules) - 3 tasks in parallel
- T042-T051 (Outputs) - 10 tasks in parallel
- T052-T053 (Parameters file) parallel with T039-T051
**Estimated Parallelization Benefit**: ~30% time reduction (from 8.5 hours to ~6 hours with optimal parallelization)
---
## Next Actions
### Before `/speckit.implement` (MANDATORY)
**1. RESOLVE HIGH SEVERITY ISSUES (A1-A5)**:
- **A1 - Standard HDD SKU Ambiguity**:
- Update spec.md FR-003: "Virtual machine MUST use Standard HDD storage tier (Standard_LRS SKU) for the OS disk"
- Update spec.md FR-008: "System MUST deploy an Azure Storage Account with HDD-backed file share (Standard_LRS SKU) with 1TB initial quota"
- Update tasks.md T025: "Configure VM OS disk with Standard_LRS storage SKU (Standard HDD)"
- Update tasks.md T030: "Configure VM data disks array with 500GB disk, Standard_LRS (Standard HDD)"
- Update tasks.md T033: "Configure Storage Account with Standard_LRS SKU"
- **A2 - Disk Utilization Alert Threshold**:
- Update spec.md FR-022: "System MUST configure critical alerts for VM stopped, OS disk used capacity >90% OR data disk used capacity >90%, and Key Vault access failures"
- Update tasks.md T040: "Add Metric Alert Rule for OS disk used capacity >90% AND data disk used capacity >90% with separate alert conditions"
- **A3 - NSG Rules Incomplete**:
- Update spec.md FR-020 to specify: "NSG MUST allow outbound traffic to AzureCloud service tag on port 443 (for Key Vault, Storage, Log Analytics); MUST allow inbound RDP (3389) from AzureBastionSubnet only; MUST deny all other inbound traffic from Internet"
- Update tasks.md T012: "Add Network Security Group module with rules: Priority 100 Allow RDP inbound from AzureBastionSubnet, Priority 110 Allow HTTPS outbound to AzureCloud tag, Priority 4096 Deny all inbound from Internet"
- **A4 - Password Complexity Validation**:
- Add assumption to spec.md Assumptions section: "Generated password formula '${uniqueString(resourceGroup().id)}${guid(subscription().id, resourceGroup().id)}A1!' produces compliant passwords meeting Azure VM requirements (12-123 characters, contains uppercase, lowercase, number, special character)"
- OR add validation task between T013-T014: Verify password generation meets Azure complexity rules
- **A5 - AVM Module Versioning**:
- Add research task to research.md: Query MCR tags for latest stable versions of all 10 AVM modules
- Add versioning strategy to plan.md Technical Context: "Use exact version pinning (e.g., 0.10.2) for production deployments to ensure reproducibility"
- Update all tasks T010-T041 to specify version format: `br/public:avm/res/<module>:0.x.x` (replace with actual versions)
### Recommended (MEDIUM Severity Issues - U1-U8)
These can be addressed during implementation but are recommended before finalizing:
- **U1**: Specify diagnostic log categories per resource type in research.md or assume defaults
- **U2**: Update spec.md US4 acceptance scenario 3 to replace "access policies" with "RBAC" for consistency
- **U3**: Add encryption-at-rest requirement or assumption (Azure default encryption assumed)
- **U4**: Add assumption to spec.md: "Alert notification actions (email, webhook, action groups) configured post-deployment"
- **U5**: Clarify in spec.md FR-016: "Availability zone MUST be user-selectable via parameter (values 1, 2, or 3)"
- **U6**: Document in quickstart.md: "Monitor file share usage via Azure Portal β Storage Account β File Shares β Properties β Quota"
- **U7**: Update tasks.md T028: "Enable VM boot diagnostics using managed storage (no separate storage account)"
- **U8**: Update tasks.md T009: "Create random suffix variable using substring(uniqueString(resourceGroup().id), 0, 6)"
### Optional (LOW Severity Issues - T1-T3)
Address during implementation or final polish:
- **T1**: Standardize terminology to "Storage Account" throughout all documents
- **T2**: Clarify in plan.md that environment parameter is for tagging only (resource group is deployment target)
- **T3**: Expand tasks.md T002 description: "Create infra/bicepconfig.json with AVM registry alias and analyzer rule use-recent-module-versions: warning"
---
## Deployment Readiness Assessment
### Overall Readiness: β οΈ **CONDITIONALLY READY**
**Recommendation**: β **SAFE TO PROCEED** with implementation **AFTER** resolving 5 HIGH severity issues (A1-A5)
**Justification**:
- β **Strengths**:
- Zero CRITICAL blockers
- 100% constitution compliance
- Complete requirements-to-task coverage
- Well-structured user story organization with clear MVP definition
- Comprehensive dependency analysis with parallelization opportunities
- No unmapped tasks or orphaned requirements
- β οΈ **Risks**:
- HIGH issues create implementation ambiguity (developer may choose wrong SKU, incomplete NSG rules)
- Missing AVM version specifications could lead to breaking changes or deployment failures
- Underspecified thresholds (disk utilization) may trigger false alerts or miss real issues
- β **Mitigation**:
- All HIGH issues are resolvable through specification updates (no architecture changes required)
- Estimated remediation time: 30-45 minutes
- No blocking dependencies or conflicting requirements detected
### Pre-Implementation Checklist
Before running `/speckit.implement`, ensure:
- [ ] All 5 HIGH severity issues (A1-A5) resolved in spec.md and tasks.md
- [ ] Constitution compliance maintained (currently 100%)
- [ ] AVM module versions researched and documented
- [ ] NSG rules fully specified with priorities and service tags
- [ ] Azure VM password complexity requirements validated or assumed
### Implementation Risk Level: **LOW-MEDIUM**
With HIGH issues resolved, implementation risk drops to LOW. Current specification provides sufficient clarity for experienced Bicep developer but requires technical gap-filling that could introduce inconsistencies if not addressed upfront.
---
## Remediation Options
**Would you like concrete remediation edits for the 5 HIGH severity issues (A1-A5)?**Options:
- **A. Yes, provide all edits** - Generate specific text replacements for spec.md, plan.md, tasks.md to resolve all HIGH issues
- **B. Only critical clarifications** - Provide edits for A1-A3 (SKU, alerts, NSG) only; defer A4-A5 for implementation phase
- **C. Manual remediation** - Keep analysis report as-is; I'll manually address issues based on recommendations
---
## Appendix: Document Statistics
### Specification Artifacts
| Document | Lines | Sections | Key Content |
|----------|-------|----------|-------------|
| constitution.md | 114 | 5 principles | Non-negotiable rules; 100% compliance |
| spec.md | 169 | 4 user stories, 24 FRs, 13 success criteria | Requirements definition; 2 clarifications |
| plan.md | 200 | Technical context, constitution checks, Phase 0-1 summary | Implementation blueprint; 6 design artifacts |
| data-model.md | 394 | 12 entities, ERD, deployment order | Resource definitions; dependency mapping |
| research.md | 236 | 8 research topics | AVM mapping, password strategy, network design |
| contracts/parameters.md | 317 | 11 parameters | Input contract; 3 required, 8 optional |
| contracts/outputs.md | 234 | 10 outputs | Output contract; administrative + operational |
| quickstart.md | ~300 | 7-step deployment guide | Deployment procedures; troubleshooting |
| tasks.md | 277 | 61 tasks across 7 phases | Implementation checklist; MVP + incremental delivery |
### Total Documentation Volume
- **Total Lines**: ~2,241 lines
- **Total Artifacts**: 9 files (+ checklists/implementation-readiness.md)
- **Estimated Reading Time**: 45-60 minutes
- **Estimated Implementation Time**: 8.5 hours (6 hours with parallelization)
---
**Report Generated**: 2026-01-26
**Next Action**: Resolve HIGH severity issues β Run `/speckit.implement` β Deploy to test environment
/speckit.analyze
β Expand to see the results
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
In the Copilot chat window, you should see something like this:
<!-- markdownlint-disable --># Specification Analysis Report
**Feature**: 001-my-legacy-workload
**Analysis Date**: 2026-02-18
**Analyzed Artifacts**: spec.md, plan.md, tasks.md, constitution.md
**Status**: β **CRITICAL/HIGH ISSUES RESOLVED** - Ready for Implementation
---
## Executive Summary
Analyzed 3 core artifacts (spec.md, plan.md, tasks.md) and constitution.md before implementation. Found **31 findings** across 6 detection categories.
**Critical Issues**: 2 (resolved)
**High Issues**: 4 (resolved)
**Medium Issues**: 15 (documented - not blocking)
**Low Issues**: 10 (documented - not blocking)
**Resolution Status**: All 6 CRITICAL/HIGH issues have been remediated. Implementation can proceed.
---
## Critical/High Issues - RESOLVED β
### COV1 - Task Count Discrepancy (CRITICAL) β FIXED
**Location**: tasks.md header
**Issue**: Header stated "Total Tasks: 78" but document contained 269 tasks (T001-T269)
**Resolution**: Updated header to "Total Tasks: 269" and added Phase 0 prerequisite note
**Impact**: Eliminated confusion about task scope
### A1 - Subnet CIDR Conflicts (HIGH) β FIXED
**Location**: spec.md IC-008 vs Clarifications section
**Issue**:
- IC-008: Bastion=10.0.0.32/26, PrivateEndpoint=10.0.0.96/28
- Clarifications: Bastion=10.0.0.64/26, PrivateEndpoint=10.0.0.128/27
**Resolution**: Made IC-008 AUTHORITATIVE - updated spec.md clarifications to reference IC-008 values, marked as "SUPERSEDED BY IC-008"
**Rationale**: IC-008 values match tasks.md implementation (T047-T050)
**Impact**: Eliminated deployment failures from incorrect CIDR allocations
### A2 - Disk Alert Threshold Conflict (HIGH) β FIXED
**Location**: spec.md SC-008 vs Clarifications
**Issue**:
- SC-008: ">90%"
- Clarifications: "85% full"
**Resolution**: Standardized to 90% throughout - updated SC-008 to "disk >90% capacity" and clarifications to "90% (aligns with SC-008)"
**Rationale**: 90% matches tasks.md T211 implementation
**Impact**: Consistent alert configuration
### I2 - Circular VMβKeyVault Dependency (HIGH) β FIXED
**Location**: tasks.md Phase 3 (VM) and Phase 4 (KeyVault)
**Issue**:
- Phase 3 deploys VM with placeholder password
- Phase 4 deploys KeyVault with real password
- Phase 4 updates VM to use KeyVault password
- **Problem**: VM needs password at creation time, but KeyVault doesn't exist yet
**Resolution**: Restructured phases - moved KeyVault deployment to Phase 2 (Foundational)
- **New Flow**:
1. Phase 2: Deploy KeyVault with random_password secret (tasks T039a-T039r)
2. Phase 3: Deploy VM referencing KeyVault secret directly (updated T094, T102)
3. Phase 4: Deploy Bastion only (removed KeyVault tasks T118-T138)
- Updated dependency flow documentation
- Added notes explaining architectural decision
**Impact**: Eliminated circular dependency, enables atomic deployments
### I1 - Alert Notification Conflict (HIGH) β FIXED
**Location**: spec.md Clarifications vs tasks.md T205
**Issue**:
- Clarifications: "Azure Portal notifications only"
- Tasks T205: Configure email_receiver with email address
**Resolution**: Updated clarifications to allow email notifications via Action Group with justification: "Azure Portal notifications insufficient for production alerting"
**Rationale**: Email notifications are standard practice for critical alerts in production systems
**Impact**: Aligns spec with implementation, enables proper alerting
### U4 - VM Password Deployment Flow Unclear (HIGH) β DOCUMENTED
**Location**: tasks.md T094, plan.md
**Issue**: Placeholder comment in T094 ("use placeholder for now") created ambiguity about VM deployment approach
**Resolution**:
- Removed placeholder comment from T094
- Updated T094 to directly reference KeyVault: "module.key_vault.secrets[var.vm_admin_secret_name].value from Phase 2"
- Updated T102 with explicit depends_on: [module.key_vault]
- Added architectural notes in Phase 2 and Phase 3 headers explaining KeyVault-first approach
**Impact**: Clear deployment flow documented, no ambiguity
---
## Medium/Low Issues - DOCUMENTED (Not Blocking)
### AzAPI Compliance (MEDIUM) - Resolved
**Finding C1**: Tasks T204-T218 originally used direct AzureRM resources for alerts instead of AVM modules or AzAPI
**Finding C2**: Tasks T084-T086 originally used direct AzureRM subnet associations
**Resolution**:
- C1: Use AzAPI `Microsoft.Insights/actionGroups` and `Microsoft.Insights/metricAlerts` resources.
- C2: Use the VNet module's subnet network security group input.
### Terminology Drift (MEDIUM) - Accepted
**Finding I3**: "NetBIOS name" (spec) vs "computer name" (tasks) used interchangeably
**Decision**: Both terms are technically accurate - "computer name" is primary, "NetBIOS name" used for context about 15-char limit
**Action**: No change required - terminology is clear in context
### Resource Group Naming (MEDIUM) β FIXED
**Finding I6**: IC-005 referenced "rg-my-legacy-workload-prod-wus3", tasks use "rg-avmlegacy-prod-wus3"
**Resolution**: Updated IC-005 to use "rg-avmlegacy-prod-wus3" with note about "workload short name"
**Rationale**: Shorter name, consistent with naming convention throughout
### Phase 0 Research Tasks (MEDIUM) - Documented
**Finding COV7**: Plan describes 8 Phase 0 research tasks but tasks.md starts at Phase 1
**Resolution**: Added note to tasks.md header: "Phase 0 research tasks (8 tasks from plan.md) are offline prerequisites"
**Rationale**: Phase 0 is research/discovery phase completed before code implementation begins
### Missing Coverage for FR-022 (MEDIUM) - Accepted
**Finding COV4**: FR-022 requires "rich comments" in Terraform files but no explicit task
**Decision**: Implicit in all "Implement" and "Configure" tasks - developers add comments during implementation
**Action**: No task added - standard development practice
### Duplication of Validation Tasks (LOW) - Accepted
**Findings D2, D3**: "terraform fmt" and "terraform validate" repeated in every phase
**Decision**: Intentional repetition for phase independence - each phase can be validated independently
**Action**: No change - accepted duplication for workflow clarity
### Ambiguous AVM Module Name (MEDIUM) - Documented
**Finding A3**: Plan states alerting module name is "TBD"
**Resolution**: Tasks T204-T218 use direct AzAPI action group and metric alert resources
**Action**: Phase 0 research should confirm no AVM module exists
### Ambiguous Bastion SKU Selection (MEDIUM) - Documented
**Finding A6**: T142 says "Basic or Standard based on Phase 0 research"
**Decision**: Acceptable - Phase 0 research will determine SKU based on cost/features
**Action**: No change - research task will resolve
---
## Metrics
- **Total Requirements**: 25 Functional + 14 Security + 10 Infrastructure = 49
- **Total Tasks**: 269 (including new Phase 2 KeyVault tasks T039a-T039r)
- **Coverage %**: 98% (48/49 requirements have tasks)
- **Constitution Violations**: 0 (2 documented exceptions with justifications)
- **Blocking Issues**: 0 (all resolved)
- **Ambiguity Count**: 6 (4 resolved, 2 documented as acceptable)
- **Critical Issues Resolved**: 2/2
- **High Issues Resolved**: 4/4
---
## Coverage Summary
| Requirement | Coverage | Tasks | Notes |
|-------------|----------|-------|-------|
| FR-001 through FR-021 | β Full | Multiple | All functional requirements covered |
| FR-022 (rich comments) | β οΈ Implicit | None | Standard practice during implementation |
| FR-023 through FR-025 | β Full | Multiple | All covered |
| SEC-001 through SEC-014 | β Full | Multiple | All security requirements covered |
| IC-001 through IC-010 | β Full | Multiple | All infrastructure constraints addressed |
**Weak Coverage**: FR-022 only (implicit in development tasks)
---
## Constitutional Alignment
### Principle I: Terraform-First β
All resources defined in Terraform. No violations.
### Principle II: AVM-First with AzAPI Fallback β
- Metric alerts (T204-T218) use AzAPI because no AVM metric alert module is available.
- NSG associations (T084-T086) use the VNet module interface.
### Principle III: Security & Reliability β
All security requirements met:
- Managed identities configured
- Secrets in KeyVault (Phase 2)
- NSGs with deny-by-default
- Diagnostic logging enabled
- Resource locks applied
- No hardcoded secrets
### Principle IV: Single-Template Pattern β
All resources in single root module. No violations.
### Principle V: Validation-First β
Validation gates enforced at every phase: fmt β validate β plan β review β apply
---
## Architectural Decisions
### Decision 1: KeyVault in Foundational Phase
**Rationale**: Eliminates circular dependency - VM requires password at creation time
**Impact**: Cleaner deployment flow, atomic infrastructure provisioning
**Trade-off**: KeyVault deployed before VM (minor cost if VM deployment fails)
**Benefit**: Simplified task sequencing, reduced error scenarios
### Decision 2: Direct AzAPI Resources for Alerts
**Rationale**: No AVM module available for metric alerts
**Impact**: Remains compliant without introducing AzureRM
**Validation**: Phase 0 research confirms no suitable AVM module
**Risk**: Minimal - metric alert resources are stable and well-documented
### Decision 3: Email Notifications for Production Alerts
**Rationale**: Portal-only notifications insufficient for production critical alerts
**Impact**: Updated spec clarifications to allow Action Group with email
**Best Practice**: Industry standard for production alerting
---
## Recommendations
### Before Implementation
1. β **COMPLETED**: Resolve all CRITICAL/HIGH issues
2. β **COMPLETED**: Document constitution exceptions
3. β **COMPLETED**: Clarify deployment flow for KeyVault and VM
4.**REQUIRED**: Complete Phase 0 research tasks (8 tasks from plan.md)
- Verify AVM module versions and interfaces
- Confirm no AVM module exists for alerts
- Verify VNet module NSG association capability
- Document findings in research.md
### During Implementation
1. Follow phase sequence: Phase 0 (offline) β Phase 1 β Phase 2 (with KeyVault) β Phase 3 β Phase 4 β Phase 5 β Phase 6 β Phase 7
2. Add rich comments to Terraform files (FR-022) during implementation
3. Validate between phases: fmt β validate β plan β review β apply
4. Run security scans (tfsec, checkov) before final deployment
### Post-Implementation
1. Verify all 13 success criteria (SC-001 through SC-013)
2. Document actual deployment time and cost
3. Test complete teardown and redeploy workflow
4. Archive analysis report with deployment artifacts
---
## Conclusion
**Status**: β **READY FOR IMPLEMENTATION**All blocking issues have been resolved:
- Task count corrected
- Subnet CIDR conflicts eliminated
- Alert threshold standardized
- Circular dependency removed via architectural restructuring
- Alert notifications aligned
- Deployment flow documented
The specification is internally consistent, fully traced to requirements, and compliant with constitution principles. Implementation can proceed through Phase 0 research followed by sequential phase execution.
**Estimated Implementation Time**: 20-30 hours
**Estimated Deployment Time**: ~30 minutes
**Estimated Monthly Cost**: <$200
---
## Appendix: All Findings
### Duplication (3 findings)
- D1: Secret name in FR-016 and SEC-002 (MEDIUM - accepted)
- D2: Repeated terraform fmt tasks (LOW - accepted for phase independence)
- D3: Repeated terraform validate tasks (LOW - accepted for phase independence)
### Ambiguity (6 findings)
- A1: Subnet CIDR conflict (HIGH - β FIXED)
- A2: Disk alert threshold conflict (HIGH - β FIXED)
- A3: AVM module name TBD (MEDIUM - resolved by using AzAPI)
- A4: Zone "-1" unclear (LOW - documentation wording improvement)
- A5: Storage account verification criteria missing (MEDIUM - accepted)
- A6: Bastion SKU selection unclear (MEDIUM - Phase 0 research will resolve)
### Underspecification (5 findings)
- U1: Deny-by-default not measurable (MEDIUM - tasks specify priority 4096 Deny rule)
- U2: Alert notification target unclear (MEDIUM - β FIXED via email config)
- U3: Placeholder password not specified (MEDIUM - β RESOLVED via Phase 2 KeyVault)
- U4: VM password deployment flow unclear (HIGH - β DOCUMENTED)
- U5: Phase 0 tasks in plan but not tasks.md (MEDIUM - documented as prerequisite)
### Constitution (2 findings)
- C1: Direct AzureRM for alerts (MEDIUM - resolved with AzAPI)
- C2: Direct AzureRM for NSG associations (LOW - resolved with the VNet module interface)
### Coverage (7 findings)
- COV1: Task count mismatch (CRITICAL - β FIXED)
- COV2: "At least 3 subnets" vs exactly 3 (MEDIUM - acceptable)
- COV3: NSG flow log verification missing (MEDIUM - manual verification acceptable)
- COV4: FR-022 no explicit task (MEDIUM - implicit in implementation)
- COV5: data-model.md creation not tasked (LOW - marked optional)
- COV6: quickstart.md creation not tasked (LOW - marked optional)
- COV7: research.md tasks not in tasks.md (LOW - documented as Phase 0 prerequisite)
### Inconsistency (7 findings)
- I1: Alert notification method conflict (HIGH - β FIXED)
- I2: Circular VMβKeyVault dependency (HIGH - β FIXED via restructure)
- I3: NetBIOS vs computer name terminology (MEDIUM - accepted)
- I4: terraform.tf vs versions.tf file naming (MEDIUM - acceptable variation)
- I5: random_string naming inconsistency (LOW - standardized in tasks)
- I6: Resource group naming mismatch (MEDIUM - β FIXED)
- I7: Phase 0 in plan but not tasks (MEDIUM - documented as prerequisite)
### Traceability (1 finding)
- T1: Missing requirement IDs on tasks (MEDIUM - User Story labels present, requirement IDs optional enhancement)
---
**Report Generated**: 2026-02-18
**Next Action**: Begin Phase 0 research (offline prerequisite tasks)
**Ready for**: `/speckit.implement` command after Phase 0 completion
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture your analysis report, with a comment of something like Analysis report generated.
8. Implement
Spec Kit uses /speckit.implement to generate the solution template file along with its parameters file. The prompt doesn’t require any specific inputs as it analyzes the existing plan and tasks to generate the implementation code.
Info
To learn more about the implement step, see the Implement chapter in the Spec Kit article.
Run the following prompt to generate the implementation for our example:
/speckit.implement
β Expand to see the results
During the Implement phase, Copilot acts based on the tasks.md file (checkboxes next to each completed task get marked with [X]). It validates all previously created checklists, such as the implementation-readiness.md, requirements.md files. As a result of this prompt execution, a number of files get generated, such as:main.bicep, main.bicepparam, bicepconfig.json, .gitignore
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
During the Implement phase, Copilot acts based on the tasks.md file (checkboxes next to each completed task get marked with [X]). It validates all previously created checklists, such as the implementation-readiness.md, requirements.md or plan-review.md files. As a result of this prompt execution, a number of files get generated, such as:main.tf, variables.tf, terraform.tf, terraform.tfvars, outputs.tf, .gitignore, .terraform.lock.hcl
Note: You may get different results, depending on a number of factors such as your inputs, LLM of choice, the current state of the Spec Kit, etc. This example is meant to give you an idea of what the outputs of this step typically look like.
Click through the tabs to see the details!
# =============================================================================
# main.tf β My Legacy Workload
#
# Provisions a single-VM Windows Server 2016 workload in West US 3 with:
# - Isolated network (VNet, 3 subnets, 3 NSGs, NAT gateway, Azure Bastion)
# - Key Vault (RBAC, no public access) storing the VM admin password
# - Windows VM (no public IP, write-only password via Terraform 1.10+)
# - Storage account (private endpoint via Azure Files, TLS 1.2)
# - Log Analytics workspace receiving all diagnostic logs/metrics
# - Three Azure Monitor alert rules (VM stopped, disk full, KV failures)
#
# All AVM modules use enable_telemetry = false per project policy.
# Contracts in specs/001-my-legacy-workload/contracts/ are authoritative for
# module versions and argument shapes.
# =============================================================================
# βββ Locals ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
locals { # CAF resource names β static (workload + env + region + instance suffix)
resource_group_name = "rg-${var.workload}-${var.environment}-westus3-001"vnet_name = "vnet-${var.workload}-${var.environment}-westus3-001"nsg_vm_name = "nsg-${var.workload}-vm-${var.environment}-westus3-001"nsg_bastion_name = "nsg-${var.workload}-bastion-${var.environment}-westus3-001"nsg_pe_name = "nsg-${var.workload}-pe-${var.environment}-westus3-001"nat_gateway_name = "ng-${var.workload}-${var.environment}-westus3-001"nat_gw_pip_name = "pip-ng-${var.workload}-${var.environment}-westus3-001"bastion_name = "bas-${var.workload}-${var.environment}-westus3-001"vm_name = "vm-${var.workload}-${var.environment}-westus3-001"vm_nic_name = "nic-${var.workload}-${var.environment}-westus3-001"vm_os_disk_name = "osdisk-${var.workload}-${var.environment}-westus3-001"vm_data_disk_name = "datadisk-${var.workload}-${var.environment}-westus3-001"log_analytics_name = "law-${var.workload}-${var.environment}-westus3-001"private_dns_zone_name = "privatelink.file.core.windows.net"pe_storage_name = "pep-${var.workload}-file-${var.environment}-westus3-001" # Alert names (no region suffix β alerts scope to resource, not region)
alert_vm_stopped_name = "alert-${var.workload}-vm-stopped-${var.environment}"alert_disk_full_name = "alert-${var.workload}-disk-full-${var.environment}"alert_kv_failures_name = "alert-${var.workload}-kv-failures-${var.environment}" # Globally-unique names (6-char random suffix appended)
# Key Vault: region token OMITTED to stay within the 24-character KV name limit
key_vault_name = "kv-${var.workload}-${var.environment}-${random_string.unique_suffix.result}"storage_account_name = "st${var.workload}${var.environment}${random_string.unique_suffix.result}" # Common tag map: base tags merged with mandatory workload/env/managedBy/region labels
common_tags = merge(var.tags, {
workload = var.workloadenvironment = var.environmentmanagedBy = "Terraform"region = var.location })
}# βββ Data Sources βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Required to obtain tenant_id for Key Vault RBAC authorization
data"azapi_client_config""current" {}# βββ Random Resources ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 6-char lowercase alphanumeric suffix to make storage and KV names globally unique
resource"random_string""unique_suffix" {
length = 6special = falseupper = false}# VM local admin password β 20 chars with mixed complexity.
# IMPORTANT: random_password.result IS stored in Terraform state (unavoidable
# for generated values). The value is ALSO written to Key Vault via the KV
# module secrets_value argument. The VM resource itself uses a write-only
# argument (Terraform 1.10+) so the password does NOT appear in the virtual
# machine resource state. See SC-003.
resource"random_password""vm_admin_password" {
length = 20special = trueoverride_special = "!@#$%^&*()"min_lower = 2min_upper = 2min_numeric = 2min_special = 2}# βββ Foundation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Single production resource group β all workload resources land here
module"resource_group" {
source = "Azure/avm-res-resources-resourcegroup/azurerm"version = "0.2.2"name = local.resource_group_namelocation = var.locationtags = local.common_tagsenable_telemetry = false}# Log Analytics workspace β MUST be created first; all diagnostic settings
# reference module.log_analytics_workspace.resource_id.
module"log_analytics_workspace" {
source = "Azure/avm-res-operationalinsights-workspace/azurerm"version = "0.5.1"name = local.log_analytics_namelocation = module.resource_group.locationresource_group_name = module.resource_group.namelog_analytics_workspace_sku = "PerGB2018"log_analytics_workspace_retention_in_days = var.log_analytics_retention_daystags = local.common_tagsenable_telemetry = falsedepends_on = [module.resource_group]
}# βββ Networking (US1) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# NSG for VM subnet β permits RDP only from Azure Bastion subnet CIDR (FR-003)
module"nsg_vm" {
source = "Azure/avm-res-network-networksecuritygroup/azurerm"version = "0.5.1"name = local.nsg_vm_namelocation = module.resource_group.locationresource_group_name = module.resource_group.namesecurity_rules = { # Allow RDP only from Bastion subnet β no direct RDP from internet
allow_rdp_from_bastion = {
name = "Allow-RDP-From-BastionSubnet"priority = 100direction = "Inbound"access = "Allow"protocol = "Tcp"source_address_prefix = var.subnet_bastion_cidrsource_port_range = "*"destination_address_prefix = "*"destination_port_range = "3389" }
deny_all_inbound = {
name = "Deny-All-Inbound"priority = 4096direction = "Inbound"access = "Deny"protocol = "*"source_address_prefix = "*"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "*" }
}
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = false}# NSG for Azure Bastion subnet β minimum required rules for Bastion Standard SKU
# See: https://learn.microsoft.com/azure/bastion/bastion-nsg
module"nsg_bastion" {
source = "Azure/avm-res-network-networksecuritygroup/azurerm"version = "0.5.1"name = local.nsg_bastion_namelocation = module.resource_group.locationresource_group_name = module.resource_group.namesecurity_rules = { # Inbound: HTTPS from Internet (portal connectivity)
allow_https_inbound = {
name = "Allow-HTTPS-Internet-Inbound"priority = 100direction = "Inbound"access = "Allow"protocol = "Tcp"source_address_prefix = "Internet"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "443" } # Inbound: Azure Gateway Manager control plane traffic
allow_gateway_manager = {
name = "Allow-GatewayManager-Inbound"priority = 110direction = "Inbound"access = "Allow"protocol = "Tcp"source_address_prefix = "GatewayManager"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "443" } # Inbound: Azure Load Balancer health probe
allow_azure_lb = {
name = "Allow-AzureLoadBalancer-Inbound"priority = 120direction = "Inbound"access = "Allow"protocol = "Tcp"source_address_prefix = "AzureLoadBalancer"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "443" } # Inbound: Bastion host-to-host communication (data plane)
allow_bastion_host_comm = {
name = "Allow-BastionHostComm-Inbound"priority = 130direction = "Inbound"access = "Allow"protocol = "*"source_address_prefix = "VirtualNetwork"source_port_range = "*"destination_address_prefix = "VirtualNetwork"destination_port_ranges = toset(["8080", "5701"])
}
deny_all_inbound = {
name = "Deny-All-Inbound"priority = 4096direction = "Inbound"access = "Deny"protocol = "*"source_address_prefix = "*"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "*" } # Outbound: SSH/RDP sessions to target VMs in the VNet
allow_ssh_rdp_outbound = {
name = "Allow-SSH-RDP-Outbound"priority = 100direction = "Outbound"access = "Allow"protocol = "*"source_address_prefix = "*"source_port_range = "*"destination_address_prefix = "VirtualNetwork"destination_port_ranges = toset(["22", "3389"])
} # Outbound: Azure Cloud endpoints (telemetry, diagnostics)
allow_azure_cloud_outbound = {
name = "Allow-AzureCloud-Outbound"priority = 110direction = "Outbound"access = "Allow"protocol = "Tcp"source_address_prefix = "*"source_port_range = "*"destination_address_prefix = "AzureCloud"destination_port_range = "443" } # Outbound: Bastion host-to-host communication (data plane)
allow_bastion_comm_outbound = {
name = "Allow-BastionComm-Outbound"priority = 120direction = "Outbound"access = "Allow"protocol = "*"source_address_prefix = "VirtualNetwork"source_port_range = "*"destination_address_prefix = "VirtualNetwork"destination_port_ranges = toset(["8080", "5701"])
} # Outbound: Session info retrieval (required by Bastion control plane)
allow_get_session_info_outbound = {
name = "Allow-GetSessionInfo-Outbound"priority = 130direction = "Outbound"access = "Allow"protocol = "*"source_address_prefix = "*"source_port_range = "*"destination_address_prefix = "Internet"destination_port_ranges = toset(["80", "443"])
}
}
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = false}# NSG for private-endpoint subnet β allows HTTPS from VNet only
module"nsg_pe" {
source = "Azure/avm-res-network-networksecuritygroup/azurerm"version = "0.5.1"name = local.nsg_pe_namelocation = module.resource_group.locationresource_group_name = module.resource_group.namesecurity_rules = {
allow_https_from_vnet = {
name = "Allow-HTTPS-From-VNet"priority = 100direction = "Inbound"access = "Allow"protocol = "Tcp"source_address_prefix = "VirtualNetwork"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "443" }
deny_all_inbound = {
name = "Deny-All-Inbound"priority = 4096direction = "Inbound"access = "Deny"protocol = "*"source_address_prefix = "*"source_port_range = "*"destination_address_prefix = "*"destination_port_range = "*" }
}
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = false}# NAT gateway β provides controlled outbound internet access for the VM subnet.
# The VM subnet has no public IP route other than this gateway (FR-011, FR-016).
# StandardV2 SKU required for zone-redundant public IP behaviour.
module"nat_gateway" {
source = "Azure/avm-res-network-natgateway/azurerm"version = "0.3.2"name = local.nat_gateway_namelocation = module.resource_group.locationparent_id = module.resource_group.resource_idsku_name = "StandardV2" # Allocate a static Standard public IP for outbound SNAT
public_ips = {
nat_gw_pip = {
name = local.nat_gw_pip_name }
} # StandardV2 SKU requires all 3 zones (module precondition enforces this)
public_ip_configuration = {
nat_gw_pip = {
allocation_method = "Static"sku = "StandardV2"idle_timeout_in_minutes = 4zones = ["1", "2", "3"]
}
} # NOTE: Diagnostic settings are NOT applied to the NAT gateway β the Azure
# Insights API for Microsoft.Network/natGateways diagnostic sub-resources does
# not respond in westus3, causing a perpetual timeout. NAT gateway byte/packet
# metrics remain viewable in Azure Monitor without an explicit diagnostic setting.
tags = local.common_tagsenable_telemetry = false}# Virtual network β three subnets, each bound to its own NSG.
# NOTE: module version 0.17.1 (contracts/virtual-network.md is authoritative).
# pe_subnet: private_endpoint_network_policies = "Enabled" is required for
# private endpoint policies to function correctly in this subnet.
module"virtual_network" {
source = "Azure/avm-res-network-virtualnetwork/azurerm"version = "0.17.1"name = local.vnet_namelocation = module.resource_group.locationparent_id = module.resource_group.resource_idaddress_space = var.vnet_address_spacesubnets = { # AzureBastionSubnet: name must be exactly "AzureBastionSubnet" (Azure requirement)
bastion_subnet = {
name = "AzureBastionSubnet"address_prefixes = [var.subnet_bastion_cidr]
network_security_group = {
id = module.nsg_bastion.resource_id }
} # VM subnet: outbound via NAT gateway only (no default outbound access)
vm_subnet = {
name = "snet-${var.workload}-vm-${var.environment}-westus3-001"address_prefixes = [var.subnet_vm_cidr]
network_security_group = {
id = module.nsg_vm.resource_id }
nat_gateway = {
id = module.nat_gateway.resource_id }
default_outbound_access_enabled = false } # Private-endpoint subnet: policies enabled so NSG rules apply to PE traffic
pe_subnet = {
name = "snet-${var.workload}-pe-${var.environment}-westus3-001"address_prefixes = [var.subnet_pe_cidr]
network_security_group = {
id = module.nsg_pe.resource_id }
private_endpoint_network_policies = "Enabled"default_outbound_access_enabled = false }
}
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = false}# Azure Bastion Standard SKU β Standard is required for NSG compatibility and
# tunneling support (FR-024). No file copy (disabled for security).
module"bastion" {
source = "Azure/avm-res-network-bastionhost/azurerm"version = "0.9.0"name = local.bastion_namelocation = module.resource_group.locationparent_id = module.resource_group.resource_idsku = "Standard"ip_configuration = {
name = "ipconfig-${local.bastion_name}"subnet_id = module.virtual_network.subnets["bastion_subnet"].resource_idcreate_public_ip = truepublic_ip_address_name = "pip-${local.bastion_name}" } # westus3 does not support Azure Bastion with Availability Zones
# (BastionRegionAzNotSupported) β override module default ["1","2","3"]
zones = [] # Standard SKU features β tunneling enables native client (SSH/RDP) connectivity
copy_paste_enabled = truetunneling_enabled = truefile_copy_enabled = false # File copy disabled for security hardening
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = falsedepends_on = [module.virtual_network]
}# βββ Key Vault + VM (US2) ββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Key Vault β RBAC authorization only (FR-019); legacy Access Policies disabled.
# Public network access is disabled; no private endpoint required for this
# workload (deployment agent accesses KV over service tags).
# The VM admin password is generated by random_password and written here via
# secrets_value. It is NOT read back from KV state β the VM write-only
# argument receives the value directly from random_password.result (SC-003).
module"key_vault" {
source = "Azure/avm-res-keyvault-vault/azurerm"version = "0.10.2"name = local.key_vault_namelocation = module.resource_group.locationresource_group_name = module.resource_group.nametenant_id = data.azapi_client_config.current.tenant_idsku_name = var.kv_sku # Enable public access so the deploy agent (local workstation) can write the
# KV secret via the data plane. Default action remains Deny β only the
# deployer IP is explicitly allowed. Private endpoints can be added later
# to lock this down further for steady-state operations.
public_network_access_enabled = true # Enforce deny-by-default network ACL; allow Azure services for diagnostics.
# ip_rules: CIDR block for the deployment workstation β required because
# 'public_network_access_enabled = false' would block ALL public traffic
# including the Terraform runner (ForbiddenByConnection).
network_acls = {
bypass = "AzureServices"default_action = "Deny"ip_rules = ["174.127.190.39/32"]
} # RBAC authorization is the default in this AVM module (legacy_access_policies_enabled
# defaults to false). Legacy Access Policies are explicitly prohibited (FR-019).
# Grant the deploying principal permission to manage secrets during deployment.
# Without this, Terraform cannot write the vm_admin_password secret (403 ForbiddenByRbac).
role_assignments = {
deploying_principal = {
role_definition_id_or_name = "Key Vault Secrets Officer"principal_id = data.azapi_client_config.current.object_id }
} # Soft-delete enabled with 7-day retention; purge protection off to allow
# clean teardown in non-prod (set true in regulated prod environments)
soft_delete_retention_days = 7purge_protection_enabled = false # Secret placeholder β value is supplied via secrets_value below
secrets = {
vm_admin_password = {
name = var.vm_admin_password_secret_name }
} # Sensitive value β random_password.result is stored in random_password state
# and forwarded to KV; it does NOT appear in key_vault resource state
secrets_value = {
vm_admin_password = random_password.vm_admin_password.result }
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = false}# Windows Server 2016 VM β no public IP assigned (FR-011, FR-013).
# Password is passed via write-only account_credentials argument (Terraform
# 1.10+ GA feature) β the value is applied to Azure but is NOT stored in the
# virtual machine resource state entry (SC-003).
module"virtual_machine" {
source = "Azure/avm-res-compute-virtualmachine/azurerm"version = "0.20.0"name = local.vm_namelocation = module.resource_group.locationresource_group_name = module.resource_group.nameos_type = "Windows"computer_name = var.vm_computer_name # NetBIOS name <= 15 chars per FR-013
sku_size = var.vm_sku_sizezone = tostring(var.vm_availability_zone) # zone must be string; var is number
# OS image β Windows Server 2016 Datacenter (FR-007)
source_image_reference = {
publisher = var.vm_image_publisheroffer = var.vm_image_offersku = var.vm_image_skuversion = "latest" } # Write-only credentials β password NOT stored in VM resource state (SC-003)
# generate_admin_password_or_ssh_key = false disables module auto-generation so
# the custom random_password is used instead (required when supplying a password)
account_credentials = {
admin_credentials = {
username = var.vm_admin_usernamepassword = random_password.vm_admin_password.resultgenerate_admin_password_or_ssh_key = false }
} # OS disk β Standard HDD (FR-008, FR-009)
os_disk = {
caching = "ReadWrite"storage_account_type = var.vm_os_disk_typename = local.vm_os_disk_name } # Data disk β 500 GB Standard HDD at LUN 0 (FR-009)
data_disk_managed_disks = {
data_disk_0 = {
name = local.vm_data_disk_namestorage_account_type = var.vm_data_disk_typedisk_size_gb = var.vm_data_disk_size_gblun = 0caching = "None" }
} # Single NIC β private IP only, no public IP assigned (FR-011, FR-013)
network_interfaces = {
nic_0 = {
name = local.vm_nic_nameip_configurations = {
ipconfig_0 = {
name = "ipconfig0"private_ip_subnet_resource_id = module.virtual_network.subnets["vm_subnet"].resource_idprivate_ip_allocation_method = "Dynamic" }
}
}
}
diagnostic_settings = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = falsedepends_on = [
module.key_vault,
module.virtual_network,
]
}# βββ Storage (US3) βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Private DNS zone for Azure Files private endpoints.
# Domain = "privatelink.file.core.windows.net" (canonical zone for Azure Files).
# Autoregistration is disabled β only the storage PE record is registered (FR-023).
module"private_dns_zone" {
source = "Azure/avm-res-network-privatednszone/azurerm"version = "0.5.0"domain_name = local.private_dns_zone_nameparent_id = module.resource_group.resource_idvirtual_network_links = {
workload_vnet_link = {
name = "link-${local.vnet_name}"virtual_network_id = module.virtual_network.resource_idautoregistration = false }
}
tags = local.common_tagsenable_telemetry = falsedepends_on = [module.virtual_network]
}# Storage account β Standard LRS, StorageV2, TLS 1.2, no public access (FR-020βFR-023).
# Access via private endpoint only; shared-key (SAS) access disabled.
# NOTE: shared_access_key_enabled = false requires Kerberos/AADKERB for SMB
# authentication from the VM. See quickstart.md Step 9 for mapping instructions.
module"storage_account" {
source = "Azure/avm-res-storage-storageaccount/azurerm"version = "0.6.7"name = local.storage_account_namelocation = module.resource_group.locationresource_group_name = module.resource_group.nameaccount_kind = "StorageV2"account_tier = "Standard" # Standard tier β FR-020
account_replication_type = "LRS" # Locally-redundant storage β FR-020
min_tls_version = "TLS1_2" # Minimum TLS 1.2 enforced β FR-020
# Disable all public network access β FR-021; access via private endpoint only
public_network_access_enabled = false # Network rules β deny all public traffic; allow Azure services for diagnostics
network_rules = {
bypass = ["AzureServices"]
default_action = "Deny" } # Shared key (SAS) access is disabled. See FR-020 and quickstart.md Step 9.
shared_access_key_enabled = false # Azure Files share β 100 GB quota (FR-022)
shares = {
workload_share = {
name = var.storage_file_share_namequota = var.storage_file_share_quota_gb }
} # Private endpoint for the "file" sub-resource only β FR-023
private_endpoints = {
file_pe = {
name = local.pe_storage_namesubnet_resource_id = module.virtual_network.subnets["pe_subnet"].resource_idsubresource_name = "file"private_dns_zone_resource_ids = toset([module.private_dns_zone.resource_id])
}
} # Storage accountβlevel diagnostics (metrics only β storage accounts
# do not support log categories at the account level)
diagnostic_settings_storage_account = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_idmetric_categories = ["AllMetrics"]
}
} # Azure Files serviceβlevel diagnostics (logs + metrics)
diagnostic_settings_file = {
to_law = {
name = "diag-to-law"workspace_resource_id = module.log_analytics_workspace.resource_id }
}
tags = local.common_tagsenable_telemetry = falsedepends_on = [module.private_dns_zone]
}# βββ Observability (US4) βββββββββββββββββββββββββββββββββββββββββββββββββββββ
# All diagnostic settings are declared inline with each module call above.
# This section contains only the three native AzAPI alert rule resources
# for which no AVM module exists (Constitution Principle II).
# βββ Alerts ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Alert 1: VM stopped / deallocated (FR-027)
# VmAvailabilityMetric = 1 when running, 0 when stopped. A platform metric β
# no Azure Monitor Agent required. Fires within alert_vm_metric_window_size
# of the VM transitioning to stopped/deallocated.
resource"azapi_resource""vm_stopped_metric_alert" {
type = "Microsoft.Insights/metricAlerts@2018-03-01"name = local.alert_vm_stopped_nameparent_id = module.resource_group.resource_idlocation = "global"tags = local.common_tagsbody = {
properties = {
description = "Alert fires when the VM is in a stopped/deallocated state."severity = 1enabled = truescopes = [module.virtual_machine.resource_id]
evaluationFrequency = "PT1M"windowSize = var.alert_vm_metric_window_sizecriteria = {
"odata.type"="Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria"allOf = [
{
name = "vm_availability"criterionType = "StaticThresholdCriterion"metricNamespace = "Microsoft.Compute/virtualMachines"metricName = "VmAvailabilityMetric"operator = "LessThan"threshold = 1timeAggregation = "Average" }
]
}
actions = []
}
}
response_export_values = []
}# Alert 2: Disk free space < threshold (FR-028)
# PREREQUISITE: Azure Monitor Agent (AMA) + Data Collection Rule (DCR) with
# "LogicalDisk % Free Space" counter must be deployed on the VM before this
# alert produces results (FR-030 exception β AMA is a manual post-deploy step,
# see quickstart.md Step 10).
resource"azapi_resource""disk_low_scheduled_query_alert" {
type = "Microsoft.Insights/scheduledQueryRules@2023-12-01"name = local.alert_disk_full_nameparent_id = module.resource_group.resource_idlocation = module.resource_group.locationtags = local.common_tagsbody = {
properties = {
displayName = local.alert_disk_full_namedescription = "Alert fires when VM disk free space drops below ${var.alert_disk_free_threshold_pct}%."severity = 2enabled = truescopes = [module.log_analytics_workspace.resource_id]
evaluationFrequency = var.alert_disk_query_windowwindowSize = var.alert_disk_query_windowcriteria = {
allOf = [
{
query = <<-QUERY Perf
| where ObjectName == "LogicalDisk"
and CounterName == "% Free Space"
and InstanceName != "_Total"
and InstanceName != "HarddiskVolume3"
| where CounterValue < ${var.alert_disk_free_threshold_pct}
| project TimeGenerated, Computer, InstanceName, CounterValue
QUERYtimeAggregation = "Count"threshold = 0operator = "GreaterThan"failingPeriods = {
minimumFailingPeriodsToAlert = 1numberOfEvaluationPeriods = 1 }
}
]
}
actions = {
actionGroups = []
}
}
}
response_export_values = []
}# Alert 3: Key Vault access failures (FR-029)
# Fires on any non-200 KV API response (auth failures, authorization denials,
# throttling). Requires KV audit diagnostic logs enabled (done inline above).
resource"azapi_resource""key_vault_access_failures_metric_alert" {
type = "Microsoft.Insights/metricAlerts@2018-03-01"name = local.alert_kv_failures_nameparent_id = module.resource_group.resource_idlocation = "global"tags = local.common_tagsbody = {
properties = {
description = "Alert fires when Key Vault API requests result in failure responses."severity = 2enabled = truescopes = [module.key_vault.resource_id]
evaluationFrequency = "PT5M"windowSize = var.alert_kv_metric_window_sizecriteria = {
"odata.type"="Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria"allOf = [
{
name = "key_vault_access_failures"criterionType = "StaticThresholdCriterion"metricNamespace = "Microsoft.KeyVault/vaults"metricName = "ServiceApiResult"operator = "GreaterThan"threshold = 0timeAggregation = "Count"dimensions = [
{
name = "StatusCode"operator = "Exclude"values = ["200"]
}
]
}
]
}
actions = []
}
}
response_export_values = []
}
# =============================================================================
# variables.tf β Input variable declarations for My Legacy Workload
#
# Workload : My Legacy Workload (001-my-legacy-workload)
# Variables are grouped by concern to match the section structure in
# terraform.tfvars. All defaults reflect the single production environment
# targeted by this configuration (westus3 / prod / legacy).
# =============================================================================
# βββ Global ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"location" {
type = stringdefault = "westus3"description = "Azure region for all resources in this workload."}
variable"environment" {
type = stringdefault = "prod"description = "Deployment environment label used in resource names and tags (e.g. prod, dev, staging)."}
variable"workload" {
type = stringdefault = "legacy"description = "Short workload identifier used in resource names and tags."}
variable"tags" {
type = map(string)
default = { environment = "prod", workload = "legacy" }
description = "Base tag map merged with workload/environment/managedBy/region tags for every resource."}# βββ Networking ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"vnet_address_space" {
type = list(string)
default = ["10.0.0.0/16"]
description = "CIDR address space assigned to the virtual network."}
variable"subnet_bastion_cidr" {
type = stringdefault = "10.0.0.0/26"description = "Address prefix for the AzureBastionSubnet. Must be /26 or larger to satisfy Azure Bastion requirements."}
variable"subnet_vm_cidr" {
type = stringdefault = "10.0.1.0/24"description = "Address prefix for the VM subnet. VMs are deployed here with NAT outbound only β no public IPs."}
variable"subnet_pe_cidr" {
type = stringdefault = "10.0.2.0/24"description = "Address prefix for the private-endpoint subnet. Private endpoints for storage are placed here."}# βββ Virtual Machine βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"vm_sku_size" {
type = stringdefault = "Standard_D2s_v3"description = "Azure VM SKU β must provide >= 2 vCPU and >= 8 GB RAM (FR-008)."}
variable"vm_admin_username" {
type = stringdefault = "vmadmin"description = "Local administrator username for the Windows VM."validation {
condition = length(var.vm_admin_username) >0error_message = "vm_admin_username must not be empty." }
}
variable"vm_image_publisher" {
type = stringdefault = "MicrosoftWindowsServer"description = "Publisher of the VM source image."}
variable"vm_image_offer" {
type = stringdefault = "WindowsServer"description = "Offer of the VM source image."}
variable"vm_image_sku" {
type = stringdefault = "2016-Datacenter"description = "SKU of the VM source image (FR-007: Windows Server 2016)."}
variable"vm_os_disk_type" {
type = stringdefault = "Standard_LRS"description = "Storage type for the OS disk (Standard_LRS = Standard HDD, FR-008)."}
variable"vm_data_disk_size_gb" {
type = numberdefault = 500description = "Size of the data disk in GB (FR-009: 500 GB)."validation {
condition = var.vm_data_disk_size_gb>=1error_message = "vm_data_disk_size_gb must be at least 1 GB." }
}
variable"vm_data_disk_type" {
type = stringdefault = "Standard_LRS"description = "Storage type for the data disk (Standard_LRS = Standard HDD, FR-009)."}
variable"vm_computer_name" {
type = stringdefault = "leg-prod-001"description = "Windows computer (NetBIOS) name for the VM. Must be <= 15 characters (FR-013). The Azure resource name is controlled by local.vm_name." # CHK032: computer name must fit in NetBIOS 15-char limit and follow DNS rules
validation {
condition = length(var.vm_computer_name) <=15&& can(regex("^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$", var.vm_computer_name))
error_message = "vm_computer_name must be 15 characters or fewer, contain only alphanumeric characters and hyphens, and must not start or end with a hyphen (FR-013, CHK032)." }
}
variable"vm_availability_zone" {
type = numberdefault = 1description = "Availability zone number (1, 2, or 3) for the VM and NAT gateway public IP (FR-014)." # CHK033: zone 0 and -1 are explicitly prohibited
validation {
condition = contains([1, 2, 3], var.vm_availability_zone)
error_message = "vm_availability_zone must be 1, 2, or 3. Values 0 and -1 are explicitly prohibited (FR-015, CHK033)." }
}# βββ Key Vault βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"kv_sku" {
type = stringdefault = "standard"description = "Key Vault SKU tier (standard or premium)."}
variable"vm_admin_password_secret_name" {
type = stringdefault = "vm-admin-password"description = "Name of the Key Vault secret that holds the VM administrator password (FR-018)."}# βββ Storage βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"storage_file_share_name" {
type = stringdefault = "share-legacy-prod"description = "Name of the Azure Files file share."}
variable"storage_file_share_quota_gb" {
type = numberdefault = 100description = "Quota of the file share in GB."}# βββ Log Analytics βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"log_analytics_retention_days" {
type = numberdefault = 30description = "Number of days to retain logs in the Log Analytics workspace (minimum 30 for compliance)."}# βββ Alert Thresholds ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
variable"alert_disk_free_threshold_pct" {
type = numberdefault = 10description = "Disk available percentage below which the disk-full alert fires (FR-028)."}
variable"alert_vm_metric_window_size" {
type = stringdefault = "PT5M"description = "ISO 8601 evaluation window for the VM availability metric alert (FR-027)."}
variable"alert_disk_query_window" {
type = stringdefault = "PT15M"description = "ISO 8601 evaluation frequency and window for the disk-space scheduled query alert (FR-028)."}
variable"alert_kv_metric_window_size" {
type = stringdefault = "PT15M"description = "ISO 8601 evaluation window for the Key Vault access-failure metric alert (FR-029)."}
# =============================================================================
# outputs.tf β Output declarations for My Legacy Workload
#
# Outputs expose the resource IDs and names that downstream consumers
# (pipelines, runbooks, or child modules) need. Credential values are never
# output β the VM password lives only in random_password state and in Key
# Vault; it is never surfaced here.
# =============================================================================
# βββ Resource Group ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"resource_group_id" {
description = "Resource ID of the workload resource group."value = module.resource_group.resource_id}# βββ Networking ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"virtual_network_id" {
description = "Resource ID of the virtual network."value = module.virtual_network.resource_id}
output"subnet_vm_id" {
description = "Resource ID of the VM subnet."value = module.virtual_network.subnets["vm_subnet"].resource_id}
output"subnet_bastion_id" {
description = "Resource ID of the Azure Bastion subnet."value = module.virtual_network.subnets["bastion_subnet"].resource_id}
output"subnet_pe_id" {
description = "Resource ID of the private-endpoint subnet."value = module.virtual_network.subnets["pe_subnet"].resource_id}# βββ Key Vault βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"key_vault_id" {
description = "Resource ID of the Key Vault (not a credential β safe to share downstream)."value = module.key_vault.resource_idsensitive = false}
output"key_vault_name" {
description = "Name of the Key Vault."value = local.key_vault_name}# βββ Storage βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"storage_account_id" {
description = "Resource ID of the storage account (not a credential β safe to share downstream)."value = module.storage_account.resource_idsensitive = false}
output"storage_account_name" {
description = "Name of the storage account."value = local.storage_account_name}# βββ Virtual Machine βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"vm_id" {
description = "Resource ID of the virtual machine."value = module.virtual_machine.resource_id}
output"vm_name" {
description = "Azure resource name of the virtual machine."value = local.vm_name}# βββ Observability βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"log_analytics_workspace_id" {
description = "Resource ID of the Log Analytics workspace."value = module.log_analytics_workspace.resource_id}# βββ Bastion βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
output"bastion_name" {
description = "Azure resource name of the Bastion host."value = local.bastion_name}
# =============================================================================
# terraform.tf β Provider and Terraform version requirements
#
# Workload : My Legacy Workload (001-my-legacy-workload)
# Region : West US 3 (westus3)
# This file declares the minimum Terraform version and every provider required
# by this configuration. AVM modules that use azapi or time internally will
# inherit these constraints automatically.
# =============================================================================
terraform {
required_version = ">= 1.10, < 2.0"required_providers {
azurerm = {
source = "hashicorp/azurerm"version = "~> 4.37" }
azapi = {
source = "Azure/azapi"version = "~> 2.12" }
random = {
source = "hashicorp/random"version = "~> 3.6" }
time = {
source = "hashicorp/time"version = ">= 0.9.0, < 1.0.0" }
}
}# -----------------------------------------------------------------------------
# Providers used by the solution.
# -----------------------------------------------------------------------------
provider"azapi" {
enable_preflight = true}
provider"azurerm" {
features {}
storage_use_azuread = true}
Review and approve all changes suggested by Copilot by clicking on the “Keep” button or tweak them as necessary!
It is recommended to make a commit now to capture your implementation results, with a comment of something like Implementation complete.
Next Steps
Congratulations! You’ve walked through a complete Spec Kit workflow for building Azure infrastructure using Azure Verified Modules. By following this structured approach, you’ve created a deployable IaC solution that is:
Well-documented: Every design decision is captured in the specification and plan.
Secure by default: The constitution enforces security baselines from the start.
Reproducible: The generated IaC template can be deployed consistently across environments.
Maintainable: Clear task breakdowns and checklists make future updates straightforward.
From here, you can ask Copilot to help you with the deployment and further enhancements, or you can manually take the following steps to deploy and manage your solution:
Validate with What-If: Run az deployment group what-if to preview changes before deployment.
Deploy to Azure: Use the Azure CLI or Bicep CLI to deploy your generated main.bicep to a subscription:
az deployment group create \
--resource-group <your-resource-group> \
--template-file main.bicep \
--parameters main.bicepparam
Integrate into CI/CD: Add the generated templates to your Azure DevOps or GitHub Actions pipelines.
Extend the solution: Iterate on the specification to add new capabilities while maintaining alignment with your constitution.
Initialize: Run terraform init to download the required providers and modules.
Validate with Plan: Run terraform plan to preview changes before deployment.
Deploy to Azure: Use the Terraform CLI to deploy your generated configuration to a subscription:
terraform apply
Integrate into CI/CD: Add the generated templates to your Azure DevOps or GitHub Actions pipelines.
Extend the solution: Iterate on the specification to add new capabilities while maintaining alignment with your constitution.
The content in this section represents experimental exploration of emerging technologies and innovative approaches. To learn more about our experimental content and its implications, please refer to the Experimental Section Overview.
Overview
Specification-Driven Development (SDD) is a development paradigm where the specification becomes the single source of truth, and code is generated, validated, and continuously regenerated from that specification. The key idea: you define intent upfront and unambiguously, and both humans and AI agents produce the implementation from it.
In this new model, specifications serve as a machine-enforceable contract between:
Solution builders who compose IaC solution templates for their workload’s requirements
AI assistants that generate code following these requirements
Governance teams who can trust that deployed infrastructure meets organizational requirements
This contract ensures that as requirements change, Azure evolves or best practices advance, updates to specifications automatically propagate through AI-assisted development, keeping all solutions aligned with current standards without requiring manual intervention across thousands of code repositories.
Core Principles
The Specification becomes the system: SDD flips the traditional hierarchy: instead of writing code and using specs as optional documentation, code now serves the specification, not the other way around. Specs no longer describe the system - they define it.
Architecture becomes executable: Architecture and requirements aren’t advisory; platforms can enforce them, regenerate code, and detect drift via continuous validation and schema checks.
Intent > Implementation: Human authority shifts “upward,” focusing on intent, policy, constraints, and ethics, while automation handles consistent implementation.
Parallelization and consistency: Because every team consumes the same precise blueprint, SDD eliminates ambiguity and reduces rework.
AI-native development workflow: AI coding agents (e.g., GitHub Copilot with Spec Kit) rely on specifications to generate architecture plans, tests, tasks, and code in a deterministic, repeatable way.
Paradigm Shift
Historically, infrastructure development has been an iterative process of trial and error - developers write code, test it, encounter issues, consult documentation, refine the approach, and repeat. This cycle is time-consuming and error-prone, with each developer potentially interpreting best practices differently, leading to inconsistent implementations across teams and projects.
Specification-driven development represents a fundamental shift in how we approach infrastructure coding. Rather than developers manually translating requirements into code while attempting to remember and apply countless best practices, this approach leverages comprehensive, machine-readable specifications that define exactly how infrastructure should be structured, configured, and implemented.
This paradigm shift elevates the developer’s role from code writer to solution architect. Instead of spending time ensuring compliance with specifications manually, developers can:
Design at a higher level: Focus on business requirements and architectural decisions
Compose solutions faster: Leverage pre-validated patterns and modules
Maintain quality effortlessly: Specifications are automatically applied through AI assistance
Scale best practices: Consistent, high-quality implementations across the entire organization
New Development Workflow
Specification-driven development enabled by AI transforms the traditional workflow into a systematic, compliance-first process:
flowchart LR
A[**Express intent**:<br/>Describe what you want to achieve in natural language] --> B[**AI interprets specifications**:<br/>Copilot consults specifications to understand the compliant implementation path]
B --> C[**Generate compliant code**:<br/>Produce IaC that adheres to all relevant standards and patterns]
C --> D[**Validate automatically**:<br/>Built-in awareness of specifications enables immediate validation against requirements]
D --> E[**Iterate with confidence**:<br/>Modifications and enhancements maintain compliance throughout the development lifecycle]
How Infrastructure-as-Code (IaC) Changes with SDD
When GitHub Copilot is equipped with specifications, AI doesn’t just suggest code - it becomes a compliance engine that understands and enforces the intricate rules, patterns, and best practices defined in the specifications. This carries several advantages.
1. IaC moves from code-first to specification-first
Today’s IaC flow often tries to encode architecture through Bicep/Terraform solution templates. In SDD:
The infrastructure specification sits above the IaC language.
Updating the infrastructure means updating the specification, and IaC regeneration ensures consistency. Code is “the last-mile expression” of the spec.
This reduces cognitive load as focus shifts from “How do I implement this correctly?” to “What do I want to accomplish?”
2. Eliminates drift between architecture documents and IaC
SDD enforces consistency through continuous schema validation, contract testing, and automated detection of spec-to-code mismatches.
This means no more documentation vs solution code mismatches: code is always aligned with the specification.
3. IaC solution templates become generated, not hand-coded
Your specification becomes the authoritative source (constraints, principles, etc.).
Bicep/Terraform solution templates are generated from specs, by referencing AVM modules - removing human variation.
Quality improves as every parameter, and configuration follows the same high-quality standards
Refactoring becomes updating specification, not rewriting code
Template structure, testing, and documentation become deterministic output.
Developers gain access to expert-level knowledge embedded in the specifications without needing to memorize hundreds of pages of requirements
4. Stronger governance built-in from day 1
Specs can encode: Well-Architected principles, compliance constraints, naming, tagging, and security baselines
IaC code is generated to comply automatically as SDD encodes governance in specifications, providing governance-first enforcement from the beginning.
5. AI agents can automate infra decisions reliably
“Ad-hoc” AI-generated IaC often lacks correctness or compliance; with SDD:
Correctness by design is embedded by design, as AI agents use the specifications as guardrails.
Generated templates follow a deterministic architecture plan, not LLM “best guesses.”
Changes are applied by updating the specification, not patching IaC manually.
This is transformative for large-scale infrastructure modernization.
6. Cross-organizational alignment becomes much easier IaC solution developers work with various teams, often in different organizations - everyone reads specifications differently. SDD solves this as specifications are versioned, reviewable, and auditable, with decisions and trade-offs stored in specifications. This means fewer misinterpretations, such as requirement mismatches or lifecycle ambiguities.
7. Infrastructure testing and validation become automated
Specifications become the basis for testing, including deployment validations, compliance checks, etc. IaC test automation becomes spec-driven and auto-generated.
The Future is Specification-Driven
As AI capabilities continue to advance, the value of comprehensive, well-defined specifications only increases. The combination of AVM’s rigorous specification framework, the principles of spec-driven development, and GitHub Copilot’s AI intelligence represents not just an incremental improvement, but a fundamental re-imagining of how cloud infrastructure development can and should work in the AI era.
AI-Assisted Module Development
Experimental Content
The content in this section represents experimental exploration of emerging technologies and innovative approaches. To learn more about our experimental content and its implications, please refer to the Experimental Section Overview.
For Module Owners
This section covers module development and maintenance scenarios and is primarily relevant for AVM module owners. If you are an end user looking to leverage AVM to develop complex solutions using AI, see AI-Assisted IaC Solution Development.
Overview
AVM module owners and members of the AVM core team can leverage GitHub Copilot and related AI capabilities to accelerate the development, maintenance, and validation of AVM Bicep modules. By embedding AVM-specific knowledge directly into the development environment, we reduce manual effort, improve consistency, and help ensure compliance with AVM specifications from the start.
The AVM core team is building a set of AI-powered assets that GitHub Copilot can use to provide AVM-aware assistance. These assets fall into several categories:
Custom Instructions: Markdown files that automatically guide GitHub Copilot’s behavior whenever it generates or reviews code, providing persistent context about the project’s baseline, such as coding standards and compliance requirements.
Custom Agents: Specialized AI personas that focus on a specific workflow (e.g., planning, implementing, or validating module changes), each with a defined scope, tools, and the ability to hand off work to other agents.
Prompt Files: Reusable, parameterized task templates that define a specific analysis or action for Copilot to perform, targeting specific modules or files.
Skills: Detailed, step-by-step workflow definitions that encode domain-specific expertise. Skill descriptions are included in the system prompt on every chat turn, but their full content is loaded into context on demand β only when the model determines relevance to the user’s request or the user explicitly invokes the skill.
The actual implementations of these assets may vary between Bicep and Terraform, and they will evolve over time as best practices emerge and capabilities mature. The AVM core team will continue adding documentation and examples as we make progress - both developing new assets from scratch and refining existing ones.
Coming Soon
Content for AI-assisted AVM Terraform module development is currently being developed and will be available soon. Stay tuned for updates!
Subsections of AI-Assisted Module Dev
AVM Bicep AI Assets
Experimental Content
The content in this section represents experimental exploration of emerging technologies and innovative approaches. To learn more about our experimental content and its implications, please refer to the Experimental Section Overview.
This page provides a catalog of all AI-assisted development assets available in the Bicep Registry Modules (BRM) repository. Each asset is linked to its source file for full details.
Custom Instructions
Custom instructions provide persistent, repository-wide context that shapes how GitHub Copilot generates and reviews code. They are automatically loaded by Copilot when working in the repository.
Global Instructions
Global instructions provide GitHub Copilot with an overview of the AVM Bicep repository structure, critical compliance requirements (including mandatory AVM specification adherence), tool usage guidance, module discovery methods (AVM module index, MCR, Azure Resource Reference), and schema/API version lookup procedures. This is the primary instruction file that ensures all AI-generated code aligns with AVM standards.
Skills encode complex, multi-step domain workflows into structured instructions that GitHub Copilot can follow precisely. They define prerequisites, rules, phases, and expected outputs. When the IDE starts, skill descriptions are indexed so that Copilot is aware of their existence and purpose. The full content of a skill is only loaded into the context when the user’s prompt references a topic that aligns with the skill’s described purpose.
Child Module Publishing
Source: .github/skills/avm-child-module-publishing/SKILL.md Description: Guides the end-to-end workflow for publishing a Bicep child module to the AVM public registry. Covers prerequisite verification, allowed-list registration, telemetry instrumentation, version file creation, changelog updates, parent module updates, and final validation. This skill implements the official Child Module Publishing workflow.
Note: in some cases, VS Code is not identifying the correct skill based on the above prompt. If this happens, you can try to use the follow prompt that explicitly triggers the correct skill:
Analyzes AVM Bicep modules for technical debt, including inconsistencies, documentation gaps, spelling mistakes, conflicting information, and quality issues across module files and examples. This is a read-only analysis β it does not modify any files.
Analyzes AVM Bicep modules to identify resources with outdated ARM API versions, compares them against the latest stable versions, and generates detailed implementation plans for required updates. This is a planning-only task β it does not modify any files.
/AVM-Update-module-to-latest-API-versions
AVM Terraform AI Assets
Coming Soon
Content for AI-assisted AVM Terraform module development is currently being developed and will be available soon. Stay tuned for updates!
Help & Support
Summary
This section provides information about AVM’s support.
This page provides guidance for members of the AVM Core Team on how to triage module proposals and generic issues filed in the AVM repository, as well as how to manage these GitHub issues throughout their lifecycle.
During the AVM Core Team Triage step, the following will be checked, completed and actioned by the AVM Core Team during their triage calls (which are currently twice per week).
Note
Every module needs a module proposal to be created in the AVM repository.
Tip
During the triage process, the AVM Core Team should also check the status of following queries:
Add the Β Status: In Triage πΒ label to indicate you’re in the process of triaging the issue.
Check module proposal issue/form:
Check the Bicep or Terraform module indexes for the proposed module to make sure it is not already available or being worked on.
Ensure the module’s details are correct as per specifications - naming, classification (resource/pattern) etc.
Check if the module is added to the “Proposed” column on the AVM - Modules Triage GitHub project board.
Check if the requestor is a Microsoft FTE.
If there’s any additional clarification needed, contact the requestor through comments (using their GH handle) or internal channels - for Microsoft FTEs only! You can look them up by their name or using the Microsoft Open Source Management Portal’s People finder: “Linked people across Microsoft organizations”. Make sure you capture any decisions regarding the module in the comments section.
Make adjustments to the module’s name/classification as needed.
Change the name of the issue to reflect the module’s name, i.e.,
After the “[Module Proposal]:” prefix, change the issues name to the module’s approved name between backticks, i.e., ` and `, e.g., avm/res/sql/managed-instance for a Bicep module, or avm-res-compute-virtualmachine for a Terraform module.
Example:
“[Module Proposal]: avm/res/sql/managed-instance”
“[Module Proposal]: avm-res-sql-managedinstance”
Check if the GitHub Policy Service Bot has correctly applied the module language label: Β Language: Bicep πͺΒ or Β Language: Terraform πΒ
As part of the triage of pattern modules, the following points need to be considered/clarified with the module requestor:
Shouldn’t this be a resource module? What makes it a pattern - e.g., does it deploy multiple resources?
What is it for? What problem does it fix or provides a solution for?
What is/isn’t part of it? Which resource and/or pattern modules are planned to be leveraged in it? Provide a list of resources that would be part of the planned module.
Where is it coming from/what’s backing it - e.g., Azure Architecture Center (AAC), community request, customer example. Provide an architectural diagram and related documentation if possible - or a pointer to these if they are publicly available.
Don’t let the module’s scope to grow too big, split it up to multiple smaller ones that are more maintainable - e.g., hub & spoke networking should should be split to a generic hub networking and multiple workload specific spoke networking patterns.
The module’s name should be as descriptive as possible.
Scenario 1: Requestor doesn’t want to / can’t be module owner
Note
If requestor is interested in becoming a module owner, but is not a Microsoft FTE, the AVM core team will try to find a Microsoft FTE to be the module owner whom the requestor can collaborate with.
If the requestor indicated they didn’t want to or can’t become a module owner (or is not a Microsoft FTE), make sure the Β Needs: Module Owner π£Β label is assigned to the issue. Note: the GitHub Policy Service Bot should automatically do this, based on how the issue author responded to the related question.
Move the issue to the “Looking for owners” column on the AVM - Modules Triage GitHub project board.
Add a comment on the issue with the #RFRC tag to indicate that the repository should be created. Keep the proposal issue available to the community and potential module owners.
Find module owners - if the requestor didn’t volunteer in the module proposal OR the requestor does not want or cannot be owner of the module:
Try to find an owner from the AVM communities or await a module owner to comment and propose themselves on the proposal issue.
When a new potential owner is identified, continue with the steps described as follows.
Scenario 2: Requestor wants to and can become module owner
If the requestor indicated they want to become the module owner, the GitHub Policy Service Bot will add the Β Status: Owners Identified π€Β label and will assign the issue to the requestor.
You MUST still confirm that the requestor is a Microsoft FTE and that they understand the implications of becoming the owner! If any of these conditions aren’t met, remove the Β Status: Owners Identified π€Β label and unassign the issue from the requestor.
Make sure the requestor is a Microsoft FTE. You can look them up by their name or using the Microsoft Open Source Management Portal’s People finder: “Linked people across Microsoft organizations”.
Clarify the roles and responsibilities of the module owner:
Clarify they understand and accept what “module ownership” means by replying in a comment to the requestor/proposed owner:
β Standard AVM Core Team Reply to Proposed Module Owners
<!-- markdownlint-disable -->Hi @avm_module_owner,
Thanks for requesting/proposing to be an AVM module owner!
We just want to confirm **you agree to the below pages** that define what module ownership means:
- [Team Definitions & RACI](https://azure.github.io/Azure-Verified-Modules/specs/shared/team-definitions)
- [Module Specifications](https://azure.github.io/Azure-Verified-Modules/specs/module-specs)
- [Module Support](https://azure.github.io/Azure-Verified-Modules/help-support/module-support)
Any questions or clarifications needed, let us know!
If you agree, please just **reply to this issue with the exact sentence below** (as this helps with our automation π):
"I CONFIRM I WISH TO OWN THIS AVM MODULE AND UNDERSTAND THE REQUIREMENTS AND DEFINITION OF A MODULE OWNER"
Thanks,
The AVM Core Team
#RR
<!-- markdownlint-restore -->
Once module owner identified has confirmed they understand and accept their roles and responsibilities as an AVM module owner
Make sure the issue is assigned to the confirmed module owner.
Move the issue into the “In development” column on the AVM - Modules Triage GitHub Project board.
Add a comment on the issue with the #RFRC tag to indicate that the repository should be created.
Make sure the Β Status: Owners Identified π€Β label is added to the issue.
If applied earlier, remove the Β Needs: Module Owner π£Β label from the issue.
Remove the labels of Β Needs: Triage πΒ and Β Status: In Triage πΒ to indicate you’re done with triaging the issue.
Keep the approved name, description, and owners in the proposal issue, then record the supported fields through a metadata pull request. Metadata may be created before the module source exists; the module stays Proposed until it is published.
Use the following text to approve module development
β Final Confirmation for Proposed Module Owners - Bicep
<!-- markdownlint-disable -->Hi @avm_module_owner,
Thanks for confirming that you wish to own this AVM module and understand the related requirements and responsibilities!
Before starting development, please ensure ALL the following requirements are met.
Every module owner must request and obtain approval for the [Azure Verified Modules (AVM) Module Contributors access package](https://aka.ms/avm/id/access-package/module-contributor), as outlined in [SNFR20](https://azure.github.io/Azure-Verified-Modules/spec/SNFR20#bicep).
**Use the module name and path approved in the proposal, and the assigned telemetry identifier.** The [module index](https://azure.github.io/Azure-Verified-Modules/indexes/) remains a published lookup reference:
- For your module:
-`ModuleName` - for naming your module
-`TelemetryIdPrefix` - for your module's [telemetry](https://azure.github.io/Azure-Verified-Modules/spec/SFR3)
- Folder path are defined in `RepoURL`.
Maintain module details and the assigned `telemetryIdPrefix` in `metadata.json` through the [metadata review process](https://azure.github.io/Azure-Verified-Modules/contributing/module-metadata/). If an approved value is missing or conflicts with the index, contact the AVM core team.
Check if this module exists in the other IaC language. If so, collaborate with the other owner for consistency. π
You can now start the development of this module! β Happy coding! π
**Please respond to this comment and request a review from the AVM core team once your module is ready to be published! Please include a link pointing to your PR, once available. π**Any further questions or clarifications needed, let us know!
Thanks,
The AVM Core Team
<!-- markdownlint-restore -->
β Final Confirmation for Proposed Module Owners - Terraform
<!-- markdownlint-disable -->Hi @avm_module_owner,
Thanks for confirming that you wish to own this AVM module and understand the related requirements and responsibilities!
Check if this module exists in the other IaC language. If so, collaborate with the other owner for consistency. π
Module owners must request and obtain approval for the [Azure Verified Modules (AVM) Module Contributors access package](https://aka.ms/avm/id/access-package/module-contributor), as outlined in [SNFR20](https://azure.github.io/Azure-Verified-Modules/spec/SNFR20#terraform). Per-module GitHub teams are no longer required.
You can now start the development of this module! β Happy coding! π
**Please respond to this comment and request a review from the AVM core team once your module is ready to be published! Please include a link pointing to your PR, once available. π**Any further questions or clarifications needed, let us know!
Thanks,
The AVM Core Team
<!-- markdownlint-restore -->
Important
Although, it’s not directly part of the module proposal triage process, to begin development, module owners and contributors might need additional help from the AVM core team, such as:
Update any Azure RBAC permissions for test tenants/subscription, if needed.
In case of Bicep modules only:
Confirm that every module owner has approved access through the AVM Module Contributors access package, as outlined in SNFR20. Per-module GitHub teams and parent-team assignments are no longer required. Root metadata.json determines reviewer notifications; BRM has no per-module CODEOWNERS entries.
Post-Development issue management
Once module is developed and v0.1.0 has been published to the relevant registry
Assign the Β Status: Module Available π’Β label to the issue.
Confirm that the module metadata and registry publication are correct. The four-hourly catalog sync then publishes the module index. Submit any metadata corrections to the module repository. For Bicep, verify that module list sync adds the new top-level module to the issue-template dropdown after catalog publication.
When all development actions are complete and confirmed
In case of Bicep modules - Close the module proposal issue with the following message:
β Closing remarks for the Owner(s) of a Published Bicep Module
- [x] Module published.
- [x] Module Contributors access package approved for all module owners.
- [x] Issue template file updated.
The AVM core team coordinates the module index through the [catalog sync](https://azure.github.io/Azure-Verified-Modules/contributing/module-metadata/#catalog-updates), which regenerates and publishes it automatically every four hours.
Thank you for your work @replace_with_author! I'm closing this issue now.
In case of Terraform modules - Close the issue.
Important
The Module Proposal issue MUST remain open until the module is fully developed, tested and published to the relevant registry.
Do NOT close the issue before the successful publication is confirmed!
Once the module is fully developed, tested and published to the relevant registry, and the Module Proposal issue was closed, it MUST remain closed.
Changing module owners
There can be several reasons why a module owner change is needed, e.g., the current owner is leaving the company, changing team, or is no longer able to maintain the module. In such cases, the module ownership needs to be transferred to a new owner. While in most cases the module needs to be marked as orphaned until it’s taken over by a new module owner, sometimes, the ownership can be transferred through a “hot swap”, where the current owner directly hands over ownership to another person without the module becoming orphaned first.
Note
The original Module Proposal issue related to the module in question MUST remain closed and intact.
Instead, a new Orphaned Module issue must be opened that MUST remain open until the ownership is fully confirmed!
Once the Orphaned Module issue was closed, it MUST remain closed. If the module will subsequently become orphaned again, a new Orphaned Module issue must be opened.
Adding or removing co-owners
Agree changes with the current owners and the AVM core team. Confirm each incoming owner’s eligibility, written acceptance of the role, and separate access approval. Submit the agreed handle changes to the owners array in the module’s rootmetadata.json, following the metadata review process. Use bare handles for individuals and qualified handles for approved existing teams. Keep every continuing individual or team owner; children inherit the root’s ownership.
If a module meets the criteria described in the “Orphaned Modules” chapter, the module is considered to be orphaned and the below steps must be performed.
Make sure the Β Needs: Triage πΒ , Β Needs: Module Owner π£Β , and the Β Status: Module Orphaned π‘Β labels are assigned to the issue and it is assigned to the “AVM - Module Triage” GitHub project.
Move the issue into the “Orphaned” column on the AVM - Modules Triage GitHub Project board.
Include the ownership change in a pull request to the module’s root metadata.json, linked to the orphaned module issue. Set "owners": [], removing all individual and team handles, following the metadata review process. Do not edit child ownership or set a status field. A published module with no owners is shown as Orphaned; see how module status is calculated.
Place an information notice as per the below guidelines:
In case of a Bicep module:
Place the information notice - with the text below - in an ORPHANED.md file, in the module’s root.
Run the utilities/tools/Set-AVMModule.ps1 utility with the module path as an input. This re-generates the module’s README.md file, so that the README.md file will also contain the same notice in its header.
Make sure the content of the ORPHANED.md file is displayed in the README.md in its header (right after the title).
In case of a Terraform module, place the information notice - with the text below - in the README.md file, in the module’s root.
Once the information notice is placed, submit a Pull Request.
Include the following text in the information notice:
β Orphaned module notice for module README file
β οΈTHIS MODULE IS CURRENTLY ORPHANED.β οΈ
- Only security and bug fixes are being handled by the AVM core team at present.
- If interested in becoming the module owner of this orphaned module (must be Microsoft FTE), please look for the related "orphaned module" GitHub issue [here](https://aka.ms/AVM/OrphanedModules)!
Try to find a new owner using the AVM communities or await a new module owner to comment and propose themselves on the issue.
When a new potential owner is identified, confirm they are a Microsoft FTE and clarify the roles and responsibilities of the module owner:
Clarify they understand and accept what “module ownership” means by replying in a comment to the requestor/proposed owner:
β Standard AVM Core Team Reply to New Owners of an Orphaned Module
<!-- markdownlint-disable -->Hi @avm_module_owner,
Thanks for requesting/proposing to be an AVM module owner!
We just want to confirm **you agree to the below pages** that define what module ownership means:
- [Team Definitions & RACI](https://azure.github.io/Azure-Verified-Modules/specs/shared/team-definitions)
- [Module Specifications](https://azure.github.io/Azure-Verified-Modules/specs/module-specs)
- [Module Support](https://azure.github.io/Azure-Verified-Modules/help-support/module-support)
Any questions or clarifications needed, let us know!
If you agree, please just **reply to this issue with the exact sentence below** (as this helps with our automation π):
"I CONFIRM I WISH TO OWN THIS AVM MODULE AND UNDERSTAND THE REQUIREMENTS AND DEFINITION OF A MODULE OWNER"
Thanks,
The AVM Core Team
#RR
<!-- markdownlint-restore -->
Once the new module owner candidate has confirmed they understand and accept their roles and responsibilities as an AVM module owner
Assign the issue to the confirmed module owner.
Remove the Β Status: Module Orphaned π‘Β and the Β Needs: Module Owner π£Β labels from the issue.
Add the Β Status: Module Available π’Β and Β Status: Owners Identified π€Β labels to the issue.
Move the issue into the “Done” column on the AVM - Modules Triage GitHub Project board.
Submit a pull request adding the approved incoming handles to the owners array in the module’s root metadata.json, linked to the orphaned module issue. Obtain approval from either metadata code-owner team and merge the change through the metadata review process.
Remove the information notice (i.e., the file that states that β οΈTHIS MODULE IS CURRENTLY ORPHANED.β οΈ, etc. ):
In case of a Bicep module:
Delete the ORPHANED.md file from the module’s root.
Run the utilities/tools/Set-AVMModule.ps1 utility with the module path as an input. This re-generates the module’s README.md file, so that it will no longer contain the orphaned module notice in its header.
Double check the previous steps was successful and the README.md file no longer has the information notice in its header (right after the title).
In case of a Terraform module, remove the information notice from the README.md file in the module’s root.
Once the information notice is removed, submit a Pull Request.
Use the following text to confirm the new ownership of an orphaned module:
β Final Confirmation for New Owners of an Orphaned Module
Hi @avm_module_owner,
Thanks for confirming that you wish to own this AVM module and understand the related requirements and responsibilities!
We just want to ask you to double check a few important things.
**Before taking ownership, confirm the following**:
- Every incoming owner must have approved access through the [Azure Verified Modules (AVM) Module Contributors access package](https://aka.ms/avm/id/access-package/module-contributor), as outlined in [SNFR20](https://azure.github.io/Azure-Verified-Modules/spec/SNFR20).
- Confirm every approved incoming owner is recorded in the root `metadata.json` through a merged [metadata pull request](https://azure.github.io/Azure-Verified-Modules/contributing/module-metadata/) linked to this issue. Metadata does not grant access or review permission.
- If applicable, remove the "Orphaned module" information notice from the module's `README.md` file as per [these instructions](https://azure.github.io/Azure-Verified-Modules/help-support/issue-triage/avm-issue-triage/#when-a-new-owner-is-identified) page.
- The [module index](https://azure.github.io/Azure-Verified-Modules/indexes/) is regenerated automatically every four hours. Check back to confirm your name appears once the metadata change is merged.
Once the required ownership and access steps are confirmed, you can start improving the module as its owner! β Happy coding! π
Any further questions or clarifications needed, let us know!
Thanks,
The AVM Core Team
Once the metadata change is reviewed and merged and all access and notice-removal actions above are complete, close the orphaned module issue with the following message. The module index updates automatically at the next four-hourly catalog sync.
β Closing remarks for the New Owner(s) of an Orphaned Module
- [x] Module Contributors access package approved for all incoming module owners.
- [x] Root metadata ownership change approved by either metadata code-owner team, merged, and linked to this issue through the [metadata review process](https://azure.github.io/Azure-Verified-Modules/contributing/module-metadata/).
- [x]`ORPHANED` file deleted, `README` file updated.
The module index is regenerated automatically every four hours, so the ownership change should appear shortly.
Thank you for your work @replace_with_author! I'm closing this issue now.
Hot swapping module owners
When the module owner needs to be changed without the module becoming orphaned, the overall process described in the Orphaned modules chapter needs to be followed, with a few differences.
Submit an “orphaned module” issue by using the “Orphaned AVM Module π‘” issue template while indicating the GitHub handle of the new owner.
Clarify the roles and responsibilities of the module owner by replying in a comment to the requestor/proposed owner:
β Standard AVM Core Team Reply to the New Owner(s) of an Orphaned Module
<!-- markdownlint-disable -->Hi @avm_module_owner,
Thanks for requesting/proposing to be an AVM module owner!
We just want to confirm **you agree to the below pages** that define what module ownership means:
- [Team Definitions & RACI](https://azure.github.io/Azure-Verified-Modules/specs/shared/team-definitions)
- [Module Specifications](https://azure.github.io/Azure-Verified-Modules/specs/module-specs)
- [Module Support](https://azure.github.io/Azure-Verified-Modules/help-support/module-support)
Any questions or clarifications needed, let us know!
If you agree, please just **reply to this issue with the exact sentence below** (as this helps with our automation π):
"I CONFIRM I WISH TO OWN THIS AVM MODULE AND UNDERSTAND THE REQUIREMENTS AND DEFINITION OF A MODULE OWNER"
Thanks,
The AVM Core Team
#RR
<!-- markdownlint-restore -->
Assign the issue to the new module owner.
Remove these labels:
Β Needs: Triage πΒ
Β Needs: Module Owner π£Β
Β Status: Module Orphaned π‘Β
Add these labels to the issue:
Β Status: In Triage πΒ
Β Status: Module Available π’Β
Β Status: Owners Identified π€Β labels to the issue.
Make sure the issue is assigned to the “AVM - Module Triage” GitHub project, but don’t move the issue to the “Orphaned” column of this board as it will be automatically moved to the “Done” column, once the issue is closed.
Once each incoming owner’s eligibility and written consent are confirmed, replace the departing handles with the approved incoming handles in the root owners array in the same metadata change, retaining every continuing individual or team owner. Remove team handles only if they no longer apply. Obtain approval from either metadata code-owner team and merge through the metadata review process. Confirm every incoming owner has approved access as described in SNFR20 before finalizing the handover.
Use the following text to finalize the new ownership transfer:
β Final Confirmation for the New Owner(s) of an Orphaned Module
Hi @avm_module_owner,
Thanks for confirming that you wish to own this AVM module and understand the related requirements and responsibilities!
We just want to ask you to double check a few important things.
**Before taking ownership, confirm the following**:
- Every incoming owner must have approved access through the [Azure Verified Modules (AVM) Module Contributors access package](https://aka.ms/avm/id/access-package/module-contributor), as outlined in [SNFR20](https://azure.github.io/Azure-Verified-Modules/spec/SNFR20).
- Confirm every approved incoming owner is recorded in the root `metadata.json` through a merged [metadata pull request](https://azure.github.io/Azure-Verified-Modules/contributing/module-metadata/) linked to this issue. Metadata does not grant access or review permission.
- If applicable, remove the "Orphaned module" information notice from the module's `README.md` file as per [these instructions](https://azure.github.io/Azure-Verified-Modules/help-support/issue-triage/avm-issue-triage/#when-a-new-owner-is-identified) page.
- The [module index](https://azure.github.io/Azure-Verified-Modules/indexes/) is regenerated automatically every four hours. Check back to confirm your name appears once the metadata change is merged.
Once the required ownership and access steps are confirmed, you can start improving the module as its owner! β Happy coding! π
Any further questions or clarifications needed, let us know!
Thanks,
The AVM Core Team
Once the metadata change is reviewed and merged and the handover and access requirements above are complete, close the orphaned module issue with the following message. The module index updates automatically at the next four-hourly catalog sync.
β Closing remarks for the New Owner(s) of an Orphaned Module
- [x] Module Contributors access package approved for all incoming module owners.
- [x] Root metadata ownership change approved by either metadata code-owner team, merged, and linked to this issue through the [metadata review process](https://azure.github.io/Azure-Verified-Modules/contributing/module-metadata/).
- [x]`ORPHANED` file deleted, `README` file updated.
The module index is regenerated automatically every four hours, so the ownership change should appear shortly.
Thank you for your work @replace_with_author! I'm closing this issue now.
Deprecated modules
When a module becomes deprecated
If a module meets the criteria described in the “Deprecated Modules” chapter, the module is considered to be deprecated and the below steps must be performed.
Make sure the Β Needs: Triage πΒ and the Β Status: Module Deprecated π΄Β labels are assigned to the issue and it is assigned to the “AVM - Module Triage” GitHub project.
Record the approved deprecation decision in the issue and complete the language-specific steps below. Do not clear owners to deprecate a module or add a lifecycle/status field to metadata.json.
Bicep specific steps
Update the module and connected files as per the below guidelines:
Place the information notice - with the text below - in an DEPRECATED.md file, in the module’s root.
Run the utilities/tools/Set-AVMModule.ps1 utility with the module path & -SkipBuild switch as an input. This re-generates the module’s README.md file, so that the README.md file will also contain the same notice in its header. For more instructions on how to use the script, please refer to the corresponding section in the Contribution Guide.
Make sure the content of the DEPRECATED.md file is displayed in the README.md in its header (right after the title).
Add the the notice NOTE: This is the last published version and the module has since been deprecated. to the top-most ### Changes section of the module’s CHANGELOG.md file
Remove the module workflow from the workflows folder.
Submit a Pull Request
For the AVM maintainers: Once the PR is merged, run the .Platform - Publish [moduleIndex.json] workflow with the regenIndexFromBRM flag set. This will de-list the module so that it won’t show up in the VS-Code Bicep extension going forward.
Deprecating a module does not require editing CODEOWNERS or deleting a GitHub team. BRM has no per-module code-owner entries; /avm/ intentionally has no owners, while metadata.json remains protected by its own code-owner rule.
Terraform specific steps
Place the information notice - with the text below - in the README.md file, in the module’s root.
Archive the module’s repository on GitHub.
Catalog publication
The catalog derives Deprecated from Bicep’s DEPRECATED.md or Terraform’s repository archived flag. Complete the retirement steps; the four-hourly catalog sync then publishes the change.
A Bicep marker applies to that module and all its descendants. A root marker therefore covers every child; a child marker leaves its parent and siblings unaffected. Terraform archival applies to all module entries in the repository.
A module deprecated before it was ever published to the registry is removed from the indexes rather than listed as Deprecated.
Catalog publication does not perform the required notices, Bicep workflow removal and registry-index update, or Terraform repository archival. After a top-level Bicep deprecation is published, verify that module list sync removes it from the issue-template dropdown instead of editing the list by hand.
Deprecation information notice (to be place in the module’s repository as described above)
β Deprecated module indicators
β οΈTHIS MODULE IS DEPRECATED.β οΈ
- It will no longer receive any updates.
- If the underlying Azure service is not deprecated/retired, this module may still be used as is (references to any existing versions will keep working), but it is not recommended for new deployments.
- It is recommended to migrate to a replacement/alternative version of the module, if available.
General feedback/question, documentation update and other standard issues
An issue is a “General Question/Feedback β” if it was opened through the “General Question/Feedback β” issue template, and has the labels of Β Type: Question/Feedback πββοΈΒ and Β Needs: Triage πΒ applied to it.
An issue is a “AVM Documentation Update π” if it was opened through the “AVM Documentation Update π” issue template, and has the labels of Β Type: Documentation πΒ and Β Needs: Triage πΒ applied to it.
An issue is considered to be a “standard issue” or “blank issue” if it was opened without using an issue template, and hence it does NOT have any labels assigned, OR only has the Β Needs: Triage πΒ label assigned.
When triaging the issue, consider adding one of the following labels as fits:
Β Type: Documentation πΒ
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
To see the full list of available labels, please refer to the GitHub Repo Labels section.
Note
If an intended module proposal was mistakenly opened as a “General Question/Feedback β” or other standard issue, and hence, it doesn’t have the Β Type: New Module Proposal π‘Β label associated to it, a new issue MUST be created using the “New AVM Module Proposal π” issue template. The mistakenly created “General Question/Feedback β” or other standard issue MUST be closed.
Azure Verified Modules GitHub App
Overview
The Azure Verified Modules GitHub App is represented as a GitHub App. This app automates various repository management tasks across the Azure Verified Modules program’s repositories, including issue triage, pull request labeling, team validation, and documentation updates.
The AVM repository’s team linter and AzAdvertizer workflows use the GitHub App credentials (TEAM_LINTER_APP_ID and TEAM_LINTER_PRIVATE_KEY). Retain these credentials when retiring the team linter: the active AzAdvertizer issue automation also uses them. Bicep repository maintenance workflows run from the AVM tools repository using separately scoped GitHub App tokens.
Warning
The team linter below still validates legacy per-module GitHub teams and requires separate cleanup. Do not recreate those teams to satisfy the automation; module owners must follow SNFR20 instead. Legacy CSV team columns remain for compatibility with existing shared-repository consumers.
Purpose: Validates GitHub team configurations against module ownership data from CSV indexes.
Description: This script compares the module indexes with existing GitHub Teams configuration to ensure proper team setup. It can validate Bicep parent team configurations, Terraform team permissions, and generate GitHub issues for any discrepancies found. The script supports filtering by module type (Resource/Pattern/Utility) and language (Bicep/Terraform), and can validate -owner- teams.
Key Functionality:
Compares module ownership data from CSV files with GitHub team configurations
Validates parent team configuration for Bicep module owner teams
Verifies correct repository permissions for Terraform teams
Creates GitHub issues for unmatched or misconfigured teams
Closes resolved GitHub issues when team configurations are corrected
Workflow: github-teams-check-existence.yml (currently disabled; when enabled, runs Monday-Friday at 15:00 UTC and on-demand). Update its legacy team checks before re-enabling it; unchanged, it would raise issues asking owners to recreate retired teams, not recreate the teams itself.
Purpose: Monitors AzAdvertizer data changes and creates tracking issues.
Description: This script creates GitHub issues when data in AzAdvertizer (including PSRule, APRL, and Advisor) changes compared to the last workflow run. It downloads artifacts from previous workflow runs, compares the data to identify changes, and automatically creates issues with detailed diff information when new policy rules, advisories, or recommendations are detected.
Key Functionality:
Downloads CSV artifacts from the latest workflow run
Compares current AzAdvertizer data with previous data to detect changes
Formats detected changes into readable GitHub issue format
Creates GitHub issues for new PSRule, APRL, or Azure Advisor data
Exports current data as artifacts for future comparisons
The AVM tools repository hosts the workflows for BRM. Owner routing uses the published module catalog and reads a module’s root metadata.json when the catalog has not yet caught up or the pull request changes that metadata. Child modules inherit root ownership. The CSV indexes show only the first two individual owners and are not the routing source; submit owner changes through the metadata review process.
Pull request reviewer routing requests the owners of affected modules (excluding the author), applies triage labels, and requests @Azure/azure-verified-modules-module-owners for ownerless modules. Review requests and labels do not impose a module-owner approval requirement for ordinary Bicep code changes.
Issue owner routing labels module issues by class, mentions their owners, and assigns individual owners while respecting manual assignment decisions. For orphaned modules it mentions the tooling contributors team instead of assigning a module owner.
Workflow failure issues tracks failed module and shared check/publish runs with issues, mentions the owners, assigns the first individual owner when available, and closes tracking issues when the latest completed run no longer reports failure. Orphaned-module and shared-workflow issues mention the tooling contributors team.
Module list sync compares the issue-template dropdown with top-level Available and Orphaned Bicep entries in the published catalog. When it changes, a verified bot-generated pull request updates the dropdown and is auto-merged rather than opening a drift-report issue.
These workflows support manual dispatch. Their schedules are enabled separately; the presence of a workflow alone does not mean periodic routing is running.
Summary
The AVM repository workflows and the tools-repository workflows support issue triage, reviewer notifications, and module maintenance. Review and merge requirements come from repository rules and the protected metadata CODEOWNERS rule, not from reviewer requests or triage labels.
BRM Issue Triage
Overview
This page provides guidance for Bicep module owners on how to triage AVM module issues and AVM question/feedback items filed in the BRM repository (Bicep Registry Modules repository - where all Bicep AVM modules are published), as well as how to manage these GitHub issues throughout their lifecycle.
As such, the following issues are to be filed in the BRM repository:
[AVM Module Issue]: Issues specifically related to an existing AVM module, such as feature requests, bug and security bug reports.
[AVM Question/Feedback]:Generic feedback and questions, related to existing AVM module, the overall framework, or its automation (CI environment).
Do NOT file the following types of issues in the BRM repository, as they MUST be tracked in the AVM repo:
[Orphaned Module]: Indicate that a module is orphaned (has no owner).
[Question/Feedback]: Generic questions/requests related to the AVM site or documentation.
Note
Every module needs a module proposal to be created in the AVM repository.
Module Owner Responsibilities
During the triage process, module owners are expected to check, complete and follow up on the items described in the sections below.
Module owners MUST meet the SLAs defined on the Module Support page! While there’s automation in place to support meeting these SLAs, module owners MUST check for new issues on a regular basis.
Important
The BRM repository includes other, non-AVM modules and related GitHub issues. As a module owner, make sure you’re only triaging, managing or otherwise working on issues that are related to AVM modules!
Tip
To look for items that need triaging, click on the following link to use this saved query β‘οΈ Β Needs: Triage πΒ β¬ οΈ.
To look for items that need attention, click on the following link to use this saved query β‘οΈ Β Needs: Attention πΒ β¬ οΈ.
Module issues can only be opened for existing AVM modules. Module issues MUST NOT be used to file a module proposal.
If the issue was opened as a misplaced module proposal, mention the @Azure/azure-verified-modules-tooling-contributors team in the comment section and ask them to move the issue to the AVM repository.
Triaging a Module Issue
Check the Module issue:
Make sure the issue has the Β Type: AVM π °οΈ βοΈ βοΈΒ applied to it.
Use the AVM module indexes to locate the module and its root metadata.json for the full owner list. Make sure the owners are assigned/mentioned/informed. Submit corrections through the metadata review process.
If the module is orphaned (has no owner), make sure there’s an orphaned module issue in the AVM repository.
Make sure the module’s details are captured correctly in the description - i.e., name, classification (resource/pattern), language (Bicep/Terraform), etc.
Make sure the issue is categorized using one of the following type labels:
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
Apply relevant labels for module classification (resource/pattern): Β Class: Resource Module π¦Β or Β Class: Pattern Module π¦Β
Communicate next steps to the requestor (issue author).
Remove the Β Needs: Triage πΒ label.
When more detailed plans are available, communicate expected timeline for the update/fix to the requestor (issue author).
Only close the issue, once the next version of the module was fully developed, tested and published.
Triaging a Module PR
Request knowledgeable review from module owners identified in the root metadata.json when available. An eligible BRM repository team member may approve and merge ordinary module code changes; a module owner’s approval is not mandatory. If the author is the sole owner, request another eligible reviewer rather than the author.
For metadata.json changes, obtain approval from an eligible member of either metadata code-owner team through the metadata review process.
Apply relevant labels
Categorize the PR using applicable labels, such as:
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
For module classification (resource/pattern): Β Class: Resource Module π¦Β or Β Class: Pattern Module π¦Β
If the module is orphaned (has no owner), make sure the related Orphaned module issue (in the AVM repository) is associated to the PR in a comment, so the new owner can easily identify all related issues and PRs when taking ownership.
Remove the Β Needs: Triage πΒ label.
Give your PR a meaningful title
Prefix: Start with one of the allowed keywords - fix: or feat: is the most common for module related changes.
Description: Add a few words, describing the nature of the change.
Module name: Add the module’s full name between backticks ( ` ) to make it pop.
Who needs to approve the PR?
For ordinary Bicep module code changes, any eligible repository team member may approve and merge under BRM rules. Reviewer routing requests module owners and applies triage labels, but does not impose a module-owner approval requirement. The metadata.json code-owner rule and other protected-path rules still apply.
General Question/Feedback and other standard issues
An issue is considered to be an “AVM Question/Feedback” if
An issue is considered to be a “standard issue” or “blank issue” if it was opened without using an issue template, and hence it does NOT have any labels assigned, OR only has the Β Needs: Triage πΒ label assigned.
Triaging a General Question/Feedback and other standard issues
When triaging the issue, consider adding one of the following labels as fits:
Β Type: Documentation πΒ
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
To see the full list of available labels, please refer to the GitHub Repo Labels section.
Add any (additional) labels that apply.
Communicate next steps to the requestor (issue author).
Remove the Β Needs: Triage πΒ label.
When more detailed plans are available, communicate expected timeline for the update/fix to the requestor (issue author).
Once the question/feedback/topic is fully addressed, close the issue.
Note
If an intended module proposal was mistakenly opened as a “AVM Question/Feedback β” or other standard issue, a new issue MUST be created in the AVM repo using the “New AVM Module Proposal π” issue template. The mistakenly created “AVM Question/Feedback β” or other standard issue MUST be closed.
Issue Triage Automation
This page details the automation that is in place to help with the triage of issues and PRs raised against the AVM modules.
Note
Some of these automation rules are currently disabled or reduced. A number of the comment-based automations β the recurring “chase” scheduled searches, and the per-issue/PR triage comment previously posted by ITA06 β have been disabled, or had their commenting removed, to avoid notification fatigue for everyone involved. In their current form they are too noisy, are largely filtered out and ignored by most, and are not having the desired impact. The AVM team plans to refine and re-enable these automations in the near future.
Schedule based automation
This section details all automation rules that are based on a schedule.
Note
When calculating the number of business days in the issue/triage automation, the built-in logic considers Monday-Friday as business days. The logic doesn’t consider any holidays.
ITA01BCP.1 & ITA01BCP.2
Warning
This rule is currently disabled in the BRM repository.
To avoid this rule being (re)triggered, the Β Needs: Triage πΒ must be removed as part of the triage process (when the issue is first responded to).
ITA01TF.1 & ITA01TF.2
Warning
This rule is currently disabled in the Terraform repositories.
To avoid this rule being (re)triggered, the Β Needs: Triage πΒ must be removed as part of the triage process (when the issue is first responded to).
ITA02BCP.1 & ITA02BCP.2
Warning
This rule is currently disabled in the BRM repository.
Add a reply, mentioning the Azure/terraform-avm team.
Add the Β Needs: Immediate Attention βΌοΈΒ label.
ITA04
Warning
This rule is currently disabled in all AVM repositories.
If an issue/PR has been labeled with Β Needs: Author Feedback πΒ and hasn’t had a response in 4 days, label with Β Status: No Recent Activity π€Β and add a comment.
Schedule:
Triggered every 3 hours.
Trigger criteria:
Is an open issue/PR.
Had no activity in the last 4 days.
Has the Β Needs: Author Feedback πΒ label added.
Does not have the Β Status: No Recent Activity π€Β label added.
Action(s):
Add the Β Status: No Recent Activity π€Β label.
Add a reply.
Tip
To prevent further actions to take effect, one of the following conditions must be met:
The author must respond in a comment within 3 days of the automatic comment left on the issue.
The Β Status: No Recent Activity π€Β label must be removed.
If applicable, the Β Status: Long Term β³Β or the Β Needs: Module Owner π£Β label must be added.
ITA05
Warning
This rule is currently disabled in the AVM Core and BRM repositories, and is not present in the Terraform repositories.
If an issue/PR has been labeled with Β Status: No Recent Activity π€Β and hasn’t had any update in 3 days from that point, automatically close it and comment, unless the issue/PR has a Β Status: Long Term β³Β - in which case, do not close it.
Schedule:
Triggered every 3 hours.
Trigger criteria:
Is an open issue.
Had no activity in the last 3 days.
Has the Β Needs: Author Feedback πΒ and the Β Status: No Recent Activity π€Β labels added.
Does not have the Β Needs: Module Owner π£Β or Β Status: Long Term β³Β labels added.
Action(s):
Add a reply.
Close the issue.
Tip
In case the issue needs to be reopened (e.g., the author responds after the issue was closed), the Β Status: No Recent Activity π€Β label must be removed.
ITA24
Warning
This rule is currently disabled in the AVM Core repository.
Remind module owner(s) to start or continue working on this module if there was no activity on the Module Proposal issue for more than 3 weeks. Add Β Needs: Attention πΒ label.
Schedule:
Triggered every 3 hours.
Trigger criteria:
Is an open issue.
Had no activity in the last 21 days.
Has the Β Type: New Module Proposal π‘Β and the Β Status: Owners Identified π€Β labels assigned.
Does not have the Β Status: Long Term β³Β label assigned.
Does not have the Β Needs: Attention πΒ label assigned.
Action(s):
Add a reply.
Add the Β Needs: Attention πΒ label.
Tip
To silence this notification, provide an update every 3 weeks on the Module Proposal issue, or add the Β Status: Long Term β³Β label.
Event based automation
This chapter details all automation rules that are based on an event.
ITA06
When a new issue or PR of any type is created add the Β Needs: Triage πΒ label.
Warning
The comment (reply) previously posted by this rule has been removed to reduce notification fatigue; the rule now only applies the label. See the note at the top of this page β the AVM team plans to refine and re-enable these automations in the near future.
Trigger criteria:
An issue or PR is opened.
Action(s):
Add the Β Needs: Triage πΒ label.
ITA08BCP
If AVM or “Azure Verified Modules” is mentioned in an uncategorized issue (i.e., one not using any template), apply the label of Β Type: AVM π °οΈ βοΈ βοΈΒ on the issue.
Trigger criteria:
An issue, issue comment, PR, or PR comment is opened, created or edited and the body or comment contains the strings of “AVM” or “Azure Verified Modules”.
Action(s):
Add the Β Type: AVM π °οΈ βοΈ βοΈΒ label.
ITA09
When #RR is used in an issue, add the label of Β Needs: Author Feedback πΒ .
Trigger criteria:
An issue comment or PR comment contains the string of “#RR”.
Action(s):
Add the Β Needs: Author Feedback πΒ label.
ITA10
When #wontfix is used in an issue, mark it by using the label of Β Status: Won’t Fix πΒ and close the issue.
Trigger criteria:
An issue comment or PR comment contains the string of “#RR”.
Action(s):
Add the Β Status: Won’t Fix πΒ label.
Close the issue.
ITA11
When the author replies, remove the Β Needs: Author Feedback πΒ label and label with Β Needs: Attention πΒ .
Trigger criteria:
Any action on an issue comment or PR comment except closing.
Has the Β Needs: Author Feedback πΒ label assigned.
The activity was initiated by the issue/PR author.
Action(s):
Remove the Β Needs: Author Feedback πΒ label.
Remove the Β Status: No Recent Activity π€Β label.
Add the Β Needs: Attention πΒ label.
ITA12
Clean up e-mail replies to GitHub Issues for readability.
Trigger criteria:
Any action on an issue comment.
Action(s):
Clean email reply. This is useful when someone directly responds to an email notification from GitHub, and the email signature is included in the comment.
ITA13
If the language is set to Bicep in the Module proposal, add the Β Language: Bicep πͺΒ label on the issue.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Bicep or Terraform?
Bicep
Action(s):
Add the Β Language: Bicep πͺΒ label.
ITA14
If the language is set to Terraform in the Module proposal, add the Β Language: Terraform πΒ label on the issue.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Bicep or Terraform?
Terraform
Action(s):
Add the Β Language: Terraform πΒ label.
ITA15
Remove the Β Needs: Triage πΒ label from a PR, if it already has a “Type: XYZΒ label added and is assigned to someone at the time of creating it.
Trigger criteria:
A PR is opened with any of the following labels added and is assigned to someone:
Β Type: Bug πΒ
Β Type: Documentation πΒ
Β Type: Duplicate π€²Β
Β Type: Feature Request βΒ
Β Type: Hygiene π§ΉΒ
Β Type: New Module Proposal π‘Β
Β Type: Question/Feedback πββοΈΒ
Β Type: Security Bug πΒ
Action(s):
Remove the Β Needs: Triage πΒ label.
ITA16
Add the Β Status: Owners Identified π€Β label when someone is assigned to a Module Proposal.
Trigger criteria:
Any action on an issue except closing.
Has the Β Type: New Module Proposal π‘Β added.
The issue is assigned to someone.
Action(s):
Add the Β Status: Owners Identified π€Β label.
ITA17
If the issue author says they want to be the module owner, assign the issue to the author and respond to them.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Do you want to be the owner of this module?
Yes
Action(s):
Assign the issue to the author.
Add the below reply and explain the action(s).
@${issueAuthor}, thanks for volunteering to be a module owner!
**Please don't start the development just yet!**The AVM core team will review this module proposal and respond to you first. Thank you!
ITA18
Send automatic response to the issue author if they don’t want to be module owner and don’t have any candidate in mind. Add the Β Needs: Module Owner π£Β label.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Do you want to be the owner of this module?
No
### Module Owner's GitHub Username (handle)
_No response_
Action(s):
Add the Β Needs: Module Owner π£Β label.
Add the below reply and explain the action(s).
@${issueAuthor}, thanks for submitting this module proposal!
The AVM core team will review it and will try to find a module owner.
ITA19
Send automatic response to the issue author if they don’t want to be module owner but have a candidate in mind. Add the Β Status: Owners Identified π€Β label.
Trigger criteria:
An issue is opened with its body matching the below pattern…
### Do you want to be the owner of this module?
No
@${issueAuthor}, thanks for submitting this module proposal with a module owner in mind!
**Please don't start the development just yet!**The AVM core team will review this module proposal and respond to you and/or the module owner first. Thank you!
ITA20
If the issue type is feature request, add the Β Type: Feature Request βΒ label on the issue.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Issue Type?
Feature Request
Action(s):
Add the Β Type: Feature Request βΒ label.
ITA21
If the issue type is bug, add the Β Type: Bug πΒ label on the issue.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Issue Type?
Bug
Action(s):
Add the Β Type: Bug πΒ label.
ITA22
If the issue type is security bug, add the Β Type: Security Bug πΒ label on the issue.
Trigger criteria:
An issue is opened with its body matching the below pattern.
### Issue Type?
Security Bug
Action(s):
Add the Β Type: Security Bug πΒ label.
ITA23
Remove the Β Status: In PR πΒ label from an issue when it’s closed.
Trigger criteria:
An issue is opened.
Action(s):
Remove the Β Status: In PR πΒ label.
ITA25
This legacy Bicep rule prompts a sole module owner to apply the Β Needs: Core Team π§Β label for triage visibility. The label does not require core-team approval: ordinary Bicep code changes may be approved by any eligible BRM repository team member other than the author. Changes to metadata.json still require metadata code-owner review.
Trigger criteria:
A PR is opened.
Action(s):
Prompt sole module owners to apply the Β Needs: Core Team π§Β label for triage visibility.
ITA26
Add a label for the AVM Core Team to query called Β Status: Ready For Repository Creation πΒ when a module owner adds a comment to the issue to tell them.
Trigger criteria:
A comment is added to an issue that contains the #RFRC tag.
Action(s):
Adds the Β Status: Ready For Repository Creation πΒ label to the Issue.
Where to apply these rules?
The below table details which repositories the above rules are applied to.
A check mark in brackets (e.g., [βοΈ]) indicates that the rule exists in that repository but is currently disabled. The following schedule-based rules are currently disabled: ITA01BCP, ITA01TF, ITA02BCP, ITA02TF, ITA03BCP, ITA03TF, and ITA04 (in all the repositories they apply to), ITA05 (in the AVM Core and BRM repositories), and ITA24 (in the AVM Core repository).
This page provides guidance for Terraform Module owners on how to triage AVM module issues and AVM question/feedback items filed in their Terraform Module Repo(s), as well as how to manage these GitHub issues throughout their lifecycle.
The following issues can be filed in a Terraform repository:
AVM Module Issue: Issues specifically related to an existing AVM module, such as feature requests, bug and security bug reports.
AVM Question/Feedback: Generic feedback and questions, related to existing AVM module, the overall framework, or its automation (CI environment).
Do NOT file the following types of issues in a Terraform repository, as they MUST be tracked in the AVM repo:
[Orphaned Module]: Indicate that a module is orphaned (has no owner).
[Question/Feedback]: Generic questions/requests related to the AVM site or documentation.
Note
Every module needs a module proposal to be created in the AVM repository.
Module Owner Responsibilities
During the triage process, module owners are expected to check, complete and follow up on the items described in the sections below.
Module owners MUST meet the SLAs defined on the Module Support page! While there’s automation in place to support meeting these SLAs, module owners MUST check for new issues on a regular basis.
Tip
To look for items that need triaging, look for issue labled with β‘οΈ Β Needs: Triage πΒ β¬ οΈ.
To look for items that need attention, look for issue labled with β‘οΈ Β Needs: Attention πΒ β¬ οΈ.
Module Issue
An issue is considered to be an “AVM module issue” if
it was opened through the AVM Module Issue template in the Terraform repository,
it has the label of Β Needs: Triage πΒ applied to it, and
Module issues can only be opened for existing AVM modules. Module issues MUST NOT be used to file a module proposal.
If the issue was opened as a misplaced module proposal, mention the @Azure/azure-verified-modules-engineering-owners team in the comment section and ask them to move the issue to the AVM repository.
Triaging a Module Issue
Check the Module issue:
Use the AVM module indexes to locate the module and its root metadata.json for the full owner list. Make sure the owners are assigned/mentioned/informed. Submit corrections through the metadata review process.
If the module is orphaned (has no owner), make sure there’s an orphaned module issue in the AVM repository.
Make sure the module’s details are captured correctly in the description - i.e., name, classification (resource/pattern), language (Bicep/Terraform), etc.
Make sure the issue is categorized using one of the following type labels:
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
Apply relevant labels for module classification (resource/pattern): Β Class: Resource Module π¦Β or Β Class: Pattern Module π¦Β
Communicate next steps to the requestor (issue author).
Remove the Β Needs: Triage πΒ label.
When more detailed plans are available, communicate expected timeline for the update/fix to the requestor (issue author).
Only close the issue, once the next version of the module was fully developed, tested and published.
Triaging a Module PR
PR approvals are enforced on all AVM Terraform module repositories. The following rules apply to who must approve:
Changes to metadata.json require approval from an eligible member of either @Azure/azure-verified-modules-engineering-owners or @Azure/azure-verified-modules-module-owners, as described in the metadata review process. Approval from both teams is not required, and being named in owners alone does not qualify a reviewer. The code-review requirements below apply to other changes in the same pull request.
If the PR is submitted by the module owner and the module is owned by a single person, another Terraform module owner must review and approve the PR (the module owner cannot approve their own PR).
If no owner is available, assign the @Azure/azure-verified-modules-engineering-owners GitHub team as a reviewer and apply the Β Needs: Core Team π§Β label so the AVM core team picks it up during triage.
If the PR is submitted by a contributor (other than the module owner), or the module is owned by at least 2 people, one of the module owners should review and approve the PR.
Apply relevant labels
Categorize the PR using applicable labels, such as:
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
For module classification (resource/pattern): Β Class: Resource Module π¦Β or Β Class: Pattern Module π¦Β
If the module is orphaned (has no owner), make sure the related Orphaned module issue (in the AVM repository) is associated to the PR in a comment, so the new owner can easily identify all related issues and PRs when taking ownership.
Remove the Β Needs: Triage πΒ label.
Give your PR a meaningful title
Prefix: Start with one of the allowed keywords - fix: or feat: is the most common for module related changes.
Description: Add a few words, describing the nature of the change.
General Question/Feedback and other standard issues
An issue is considered to be an “AVM Question/Feedback” if
it was opened through the AVM Question/Feedback template in your Terraform repository,
it has the labels of Β Needs: Triage πΒ and Β Type: Question/Feedback πββοΈΒ applied to it, and
Triaging a General Question/Feedback and other standard issues
When triaging the issue, consider adding one of the following labels as fits:
Β Type: Documentation πΒ
Β Type: Feature Request βΒ
Β Type: Bug πΒ
Β Type: Security Bug πΒ
To see the full list of available labels, please refer to the GitHub Repo Labels section.
Add any (additional) labels that apply.
Communicate next steps to the requestor (issue author).
Remove the Β Needs: Triage πΒ label.
When more detailed plans are available, communicate expected timeline for the update/fix to the requestor (issue author).
Once the question/feedback/topic is fully addressed, close the issue.
Note
If an intended module proposal was mistakenly opened as a “AVM Question/Feedback β” or other standard issue, a new issue MUST be created in the AVM repo using the “New AVM Module Proposal π” issue template. The mistakenly created “AVM Question/Feedback β” or other standard issue MUST be closed.
Known Issues
Unfortunately, there will be times where issues are out of the AVM core team and module owners/contributor’s control and the issue may be something that has to be lived with for a longer than ideal duration - for example, in case of changes that are due to the way the Azure platform, or a resource behaves, or because of an IaC language issue.
This page will detail any of the known issues that consumers may come across when using AVM modules and provide links to learn more about them and where to get involved in discussions on these known issues with the rest of the community.
Important
Issues related to an AVM module must be raised on the repo they are hosted on, not the AVM Central (Azure/Azure-Verified-Modules) repo!
Although, if you think a known issue is missing from this page please create an issue on the AVM Central Azure/Azure-Verified-Modules repo.
If you accidentally raise an issue in the wrong place, we will transfer it to its correct home. π
Bicep
Bicep what-if compatibility with modules
Bicep/ARM What-If has a known issue today where it short-circuits whenever a runtime function is used in a nested template. And due to the way Bicep modules work, all module declarations in a Bicep file end up as a resulting nested template deployment in the underlying generated ARM template, thereby invoking this known issue.
The ARM/Bicep Product Group has recently announced on the issue that they are making progress in this space and are aiming provide a closer ETA in the near future; see the comment here.
While this isn’t an AVM issue, we understand that consumers of AVM Bicep modules may want to use what-if and are running into this known issue. Please keep adding your support to the issue mentioned above (Azure/arm-template-whatif #157), as the Product Group are actively engaging in the discussion there. π
A well-known limitation of ARM, and in extension Bicep, is its compiled ARM template size constraint of 4MB. While there is not anything one can do to change this limit there are actions you can take to reduce your template’s size and make it less likely to run into this issue.
In the following we provide you with a list of options you should be aware of:
β Use loops for multi-instance deployments
If you deploy multiple instances of the same module (e.g., DNS entries, role assignments, etc.) you should invoke the module using a loop, as opposed to separate references to the same module. The reason comes down the way that ARM interprets these references: Each reference of a module is restored to its full ARM size. That means, if you invoke the same module 3 separate time, you will find that this module’s full template is added as a nested deployment 3 separate times. Using a loop instead, the reference is only added once and invoked as many times as your loop has entries.
For example, you should refactor the code
targetScope = 'subscription'@description('The principal to assign the roles to.')
param principalId string
module testDeployment1 'br/public:avm/res/authorization/role-assignment/sub-scope:0.1.0' = {
params: {
principalId: principalId
roleDefinitionIdOrName: 'Contributor' }
}
module testDeployment2 'br/public:avm/res/authorization/role-assignment/sub-scope:0.1.0' = {
params: {
principalId: principalId
roleDefinitionIdOrName: 'Role Based Access Control Administrator' }
}
to
targetScope = 'subscription'@description('The principal to assign the roles to.')
param principalId string
var rolesToAssign = [
'Contributor''Role Based Access Control Administrator']
module testDeployment 'br/public:avm/res/authorization/role-assignment/sub-scope:0.1.0' = [
for role in rolesToAssign: {
params: {
principalId: principalId
roleDefinitionIdOrName: role
}
}
]
For this example, the compiled JSON of first version has a size of 18kb, the second 10kb.
β Only use AVM if you benefit from its features
Using AVM modules can come with a lot of advantages compared to a native resource deployment. This can be as simple as being a ‘module’ deployment, enabling you to deploy to multiple scopes in the same template at once, all the way to encapsulating entire solution into a single invocation and hence drastically reducing the complexity of your own solution template.
However, they also come with certain limitations. For one, that you’re dependent on the module providing you all the features you need, but moreover, that the very same features are always part of the module, whether you use them or not, hence contributing to your solution template’s size.
With this in mind, our recommendation is to only use AVM modules if you use any of its features, hence justifying the added size.
Recommendations
Only use the br/public:avm/res/resources/resource-group resource if you deploy resource groups with role assignments
Only use the br/public/avm/res|ptn/authorization/(...) modules if you benefit from their scope flexibility
When facing challenges with the template size, start replacing individual module references with their native counter-part under consideration of the size-reduction (considering large modules like API-Management, Storage Account, etc.) and the complexity of re-implementing the required features yourself. The good news: For the latter you can cherry-pick the parts of the AVM template you need.
β Split the solution template
Probably the most uncomfortable option. If you cannot deploy your solution in one go, it may make sense to split it into logical chunks that you can deploy separately and optionally in sequence (e.g., in your workflow).
This approach comes with a few drawbacks such as the potentially longer deployment time and less intuitive resolution of interdependencies. In other words, if many of your module deployments use each other’s outputs and you split them into multiple templates, you’d need to create ’existing’ references in the later deployments to get the same outputs.
For example, splitting the following two resources
in two templates requires you to either add an output for the first resource’s identity to the first template and pass it to the second, or create an existing reference in the second template akin to
As mentioned on the Introduction page, we understand that long-term support from Microsoft in an initiative like AVM is critical to its adoption by consumers and therefore the success of AVM. Therefore we have aligned and provide the below support statement/process for AVM modules:
Support Statements
Info
Module owners do go on holiday or have periods of leave from time to time, during these times the AVM core team will attempt to triage issues based on the below on behalf of module owners. π
For bugs/security issues
5Β businessΒ days for a triage, meaningful response, and ETA to be provided for fix/resolution by module owner (which could be past the 5 days)
ForΒ issues that breach the 5 business days, the AVM core team will be notified and will attempt to respond to the issue within an additional 5 business days to assist in triage.
For security issues, the Bicep or Terraform Product Groups may step inΒ to resolve security issues, if unresolved, after a further additional 5 business days.
For feature requests
15 business days for a meaningful response and initial triage to understand the feature request. An ETA may be provided by the module owner if possible.
AVM is Open-Source
AVM is open-source, therefore, contributions are welcome via Pull Requests or comments in Issues from anyone in the world at any time on any Pull Request or Issues to assist AVM module ownersΒ π
All of this will be automated via the use of the Resource Management feature of the Microsoft GitHub Policy Service and GitHub Actions, where possible and appropriate.
Note
Please note that the durations stated above are for a reasonable and useful response toward resolution of the issue raised, if possible, and not for a fix within these durations; although if possible this will of course happen.
Tip
Issues that are likely related to an AVM module should be directly submitted on the module’s GitHub repository as an “AVM - Module Issue”. To identify the correct code repository, see the AVM module indexes.
If an issue is likely related to the Azure platform, its APIs or configuration, script or programming languages, etc., you need to raise a ticket with Microsoft CSS (Microsoft Customer Services & Support) where your ticket will be triaged for any platform issues. If deemed a platform issue, the ticket will be addressed accordingly. In case it’s deemed not a platform but a module issue, you will be redirected to submit a module issue on GitHub.
Orphaned Modules
Modules that have to have the AVM core team or Product Groups step in due to the module owners/contributors not responding, the AVM module will become “orphaned”; see Module Lifecycle for more info.
Info
If a module is orphaned, the AVM team will try to find a new owner by:
In more urgent or high priority cases, selectively identifying a new module owner from the pool of existing AVM module owners/contributors to take over the module.
To raise attention to an orphaned module and allow the AVM team to better prioritize actions, customers can leave a comment on the “orphaned module” issue, explaining their use case and why they would like to see the module supported. This will help the AVM team to prioritize the module for a new owner.
Telemetry
Microsoft uses the approach detailed in this section to identify the deployments of the AVM Modules. Microsoft collects this information to provide the best experiences with their products and to operate their business. Telemetry data is captured through the built-in mechanisms of the Azure platform; therefore, it never leaves the platform, providing only Microsoft with access. Deployments are identified through a specific GUID (Globally Unique ID), indicating that the code originated from AVM. The data is collected and governed by Microsoft’s privacy policies, located at the Trust Center.
Telemetry collected as described here does not provide Microsoft with insights into the resources deployed, their configuration or any customer data stored in or processed by Azure resources deployed by using code from AVM. Microsoft does not track the usage/consumption of individual resources using telemetry described here.
Note
While telemetry gathered as described here is only accessible by Microsoft. Bicep customers have access to the exact same deployment information on the Azure portal, under the Deployments section of the corresponding scope (Resource Group, Subscription, etc.). Terraform customers can view the information sent in the main.telemetry.tf file.
As detailed in SFR3 each AVM module contains a avmTelemetry deployment, which creates a deployment such as 46d3xbcp.res.compute-virtualmachine.1-2-3.eum3 (for Bicep) or 46d3xgtf.res.compute-virtualmachine.1-2-3.eum3 (for Terraform).
Opting Out
Albeit telemetry described in this section is optional, the implementation follows an opt-out logic, as most commercial software solutions, this project also requires continuously demonstrating evidence of usage, hence the AVM core team recommends leaving the telemetry setting on its default, enabled configuration.
This resource enables the AVM core team to query the number of deployments of a given module from Azure - and as such, get insights into its adoption.
To opt out you can set the parameters/variables listed below to false in the AVM module:
Bicep: enableTelemetry
Terraform: enable_telemetry
Telemetry vs Customer Usage Attribution
Though similar in principles, this approach is not to be confused and does not conflict with the usage of CUA IDs that are used to track Azure customer usage attribution of Azure marketplace solutions (partner solutions). The GUID-based telemetry approach described here can coexist and can be used side-by-side with CUA IDs. If you have any partner or customer scenarios that require the addition of CUA IDs, you can customize the AVM modules by adding the required CUA ID deployment while keeping the built-in telemetry solution.
Tip
If you’re a partner and want to build a solution that tracks customer usage attribution (using a CUA ID), we recommend implementing it on the consuming template’s level (i.e., the multi-module solution, such as workload/application) and apply the required naming format 'pid-' (without the suffix).
Resources
This page references additional resources available for Azure Verified Modules (AVM).
Note
Additional internal content available for Microsoft FTEs only, here.
Got an unanswered question? Create a GitHub Issue so we can get it answered and added here for everyone’s benefit π
Note
Microsoft FTEs only: check out the internal FAQ for additional information.
Tip
Check out the Contribution Q&A for more answers to common questions about the contribution process.
Timeline, history, plans
When will we have a library that has a “usable” stand? Not complete, but the most important resources?
Bicep: AVM evolved all modules of CARML (Common Azure Resource Module Library) for its Bicep resource module collection (see here). To initially populate AVM with Bicep resource modules, all existing CARML modules have been migrated to AVM. Resource modules can now be directly leveraged to support the IaC needs of a wide variety of Azure workloads. Pattern modules can also be developed building on these resource modules.
Terraform: In case of Terraform, there were significantly less modules available in TFVM (Terraform Verified Modules Library) compared to CARML, hence, most Terraform modules have been and are being built as people volunteer to be module owners. We’ve been prioritizing the development of the Terraform modules based on our learnings from former initiatives, as well as customer demand - i.e., which ones are the most frequently deployed modules.
What happened to existing initiatives like CARML and TFVM?
The AVM team worked/works closely with the teams behind the following initiatives:
All previously existing assets from these two libraries have been incorporated into AVM as resource or pattern modules.
All previously existing (non-AVM) modules that were published in the Public Bicep Registry (stored in the /modules folder of the BRM repository) have either been retired or transformed into an AVM module - while some are still being worked on.
CARML to AVM Evolution
CARML can be considered AVM’s predecessor. It was started by Industry Solutions Delivery (ISD) and the Customer Success Unit (CSU) and has been contributed to by many across Microsoft and has also had external contributions.
A lot of CARML’s principles and architecture decisions have formed the basis for AVM. Following a small number of changes to make them AVM compliant, all CARML modules have been transitioned to AVM as resource or pattern modules.
In summary, CARML evolved to and has been rebranded as the Bicep version of AVM. A notice has been placed on the CARML repo redirecting users and contributors to the AVM central repository.β
Terraform Timeline and Approach
As the AVM core team is not directly responsible for the development of the modules (that’s the responsibility of the module owners), there’s no specific timeline available for the publication of Terraform modules.
However, the AVM core team is focused on the following activities to facilitate and optimize the development process:
Leveraging customer demand, telemetry and learnings from former initiatives to prioritize the development of Terraform modules.
Providing automated tools and processes (CI environment and automated tests).
Accelerating the build-out of the Terraform module owners’ community.
Recruiting new volunteers to build and maintain Terraform modules.
Will existing Landing Zone Accelerators (Platform & Application) be migrated to become AVM pattern modules and/or built from AVM resource modules?
Not in the short/immediate term. Existing Landing Zone Accelerators (Platform & Application) will not be forced to convert their existing code bases, if available in either language, to AVM or to use AVM.
However, over time if new features or functionality are required by Landing Zone Accelerators, that team SHOULD consider migrating/refactoring that part of their code base to be constructed with the relevant AVM module if available. For example, the Bicep version of the “Sub Vending” solution is migrating to AVM shortly.
If the relevant AVM module isn’t available to use to assist the Landing Zone Accelerator, then a new AVM module proposal should be made, and if desired, the Landing Zone Accelerator team may decide to own this proposed module π
Does/will AVM cover other Microsoft cloud products such as Entra ID, Microsoft 365, GitHub, Azure DevOps, or Microsoft Fabric?
Today, the AVM program is scoped specifically to Azure cloud resources and does not produce standalone modules for other Microsoft cloud products such as Entra ID, Microsoft 365, GitHub, Azure DevOps, or Microsoft Fabric.
AVM’s core value is the standardization of Azure resource configurations via Bicep and Terraform, providing consistent interfaces for things like WAF alignment, RBAC, diagnostic settings, and private networking. We have investigated whether this standardization model can be applied to other Microsoft cloud products (for example, we have spoken to relevant product group teams on Entra ID) and, for today, we have concluded there is no meaningful impact to be had by creating standalone modules for objects such as an Entra ID group.
This is not a permanent decision. Generally speaking, the AVM team is open to any conversation about expanding scope to cover other Microsoft cloud products. If there are valid reasons to wrap these assets inside AVM modules and a recognized standardization surface can be defined (comparable to what AVM provides for Azure resources today), we are open to that conversation. We encourage the community to raise proposals via a GitHub Issue.
What about pattern modules? Assets/objects and their configuration from other Microsoft cloud products may still be included in pattern modules as native asset/object declarations (e.g., via a supported Terraform provider or Bicep extension), where they add meaningful value to the overall architecture pattern being described. Per the AVM specifications (PMNFR2), pattern modules may use native “resource” code where necessary. The restriction above applies specifically to standalone resource modules for these platforms.
Note
If you believe AVM should define a standardization layer for one of these platforms, please open a GitHub Issue with your proposal and rationale.
Will AVM also become a part of azd cli?
Yes, the AVM team is partnering with the AZD team and they are already using Bicep AVM modules from the public registry.
What is the difference between the Bicep Registry and AVM? (How) Do they come together?
The Public Bicep Registry (backed by the BRM repository) is Microsoft’s official Bicep Registry for 1st party-supported Bicep modules. It has existed for a while now and has seen quite some contributions.
As various teams inside Microsoft have come together to establish a “One Microsoft” IaC approach and library, we started the AVM initiative to bridge the gaps by defining specifications for both Bicep and Terraform modules.
In the BRM repo today, “vanilla modules” (non-AVM modules) can be found in the /modules folder, while AVM modules are located in the /avm folder. Both are being published to the same endpoint, the Public Bicep Registry. AVM Bicep modules are published in a dedicated namespace, using the avm/res & avm/ptn prefixes to make them distinguishable from the Public Registry’s “vanilla modules”.
Note
Going forward, AVM will become the single Microsoft standard for Bicep modules, published to the Public Bicep Registry, via the BRM repository.
In the upcoming period, existing “vanilla” modules will be retired or migrated to AVM, and new modules will be developed according to the AVM specifications.
How is AVM different from Bicep private registries and TemplateSpecs? Is AVM related to, or separate from Azure Radius?
AVM - with its modules published in the Public Bicep Registry (backed by the BRM repository) - represents the only standard from Microsoft for Bicep modules in the Public Registry.
Bicep private registries and TemplateSpecs are different ways of inner-sourcing, sharing and internally leveraging Bicep modules within an organization. We’re planning to provide guidance for theses scenarios in the future.
AVM has nothing to do with Radius (yet), but the AVM core team is constantly looking for additional synergies inside Microsoft.
At a high-level “WAF Aligned” means, where possible and appropriate, AVM Modules will align to recommendations and default input parameters/variables to values that align to high impact/priority/severity recommendations in the following frameworks and resources:
For security recommendations we will also utilize the following frameworks and resources; again only for high impact/priority/severity recommendations:
Will all AVM modules be 100% “WAF Aligned” out of the box and good to go?
Not quite, but they’ll certainly be on the right path. By default, modules will only have to set defaults for input parameters/variables to values that align to high impact/priority recommendations, as detailed above.
To understand this further you first must understand that some of the “WAF Aligned” recommendations, from the sources above are more than just setting a string or boolean value to something particular to meet the recommendation; some will require additional resources to be created and exist and then linked together to help satisfy the recommendation.
In these scenarios the AVM modules will not enforce the additional resources to be deployed and configured, but will provide sufficient flexibility via their input parameters/variables to be able to support the configuration, if so desired by the module consumer.
Tip
This is why we only enforce AVM module alignment to high impact/priority recommendations, as the the majority of recommendations that are not high impact/priority will require additional resources to be used together to be compliant, as the below example will show.
Some examples
Recommendation
Will Be Set By Default in AVM Modules?
TLS version should always be set the latest/highest version TLS 1.3
Yes, as string value
Key Vault should use RBAC instead of access policies for authorization
Yes, as string/boolean value
Container registries should use private link
No, as requires additional Private Endpoint and DNS configuration as well as, potentially, additional costs
API Management services should use a virtual network
No, as requires additional Virtual Network and Subnet configuration as well as, potentially, additional costs
Important
While every Well-Architected Framework pillar’s recommendations should equally be considered by the module owners/contributors, within AVM we are taking an approach to prioritize reliability and security over cost optimization. This provides consumers of the AVM modules, by default, more resilient and secure resources and patterns.
However, please note these defaulted values can be altered via input parameter/variables in each of the modules so that you can meet your specific requirements.
What is a “Primary Resource” in the context of AVM?
The definition of a Primary Resource is detailed in the glossary.
How does AVM align and assist with the Secure Future Initiative (SFI)?
AVM modules are continuously being improved with the security and reliability recommendations of the Well-Architected Framework (for more details, see what AVM means by “WAF-aligned”). The AVM team is continuously reviewing SFI recommendations and if required rolling out updates to the AVM initiative to remain SFI compliant as well as assisting module owners to ensure their modules help their consumers align to SFI where appropriate.
Contribution, module ownership
Can I be an AVM module owner if I’m not a Microsoft FTE?
Every module MUST have an owner who is responsible for module development and maintenance. One owner can own one or multiple modules. An owner can develop modules alone or lead a team that will develop a module.
Today, only Microsoft FTEs can be module owners. This is to ensure we can enforce and provide the long-term support required by this initiative.
How can I contribute to AVM without being a module owner?
Yes, you can contribute to a module without being its owner, but you’ll still need a module owner whom you can collaborate with. For context, see the answer to this question.
Tip
If you’re a Microsoft FTE, you should consider volunteering to be a module owner. You can propose a new module, or look for orphaned modules and volunteer to be the owner for any of them.
If you’re not a Microsoft FTE or don’t want to be a module owner, you can still contribute to AVM. You have multiple options:
You can propose a new module and provide as much context as possible under the “Module Details” section (e.g., why do you need the module, what’s the business impact of not having it, etc.). The AVM core team will try to find a Microsoft FTE to be the module owner whom you can collaborate with.
You can contact the current owner of any existing module and offer to contribute to it. You can find the current owners of all AVM modules in the module indexes.
You can look for orphaned modules and use the comment section to indicate that you’d be interested in contributing to this module, once a new owner is found.
Are there different ways to contribute to AVM?
Yes, there are multiple ways to contribute to AVM!
You can contribute to modules:
Become an owner (preferred):
Propose and develop a new module (Bicep or Terraform) or pick up a module someone else proposed.
Become the owner of an orphaned module (mainly Bicep) - look for “orphaned module” issues here or see the “Orphaned” swimlane here
Become an administrative owner and work with other contributors or co-owners on developing and maintaining modules.
Volunteer as a co-owner or module contributor to an existing module, and work along other contributors and the (administrative) module owner.
You can submit a PR with a small proposed change without officially becoming a module owner or contributor.
Or you can contribute to the AVM website/documentation, by following this guidance.
Note
New modules can’t be created and published without having a module owner assigned.
Where can I find modules I can contribute to?
You can find modules missing owners in the following places:
To indicate your interest in owning or contributing to a module, just leave a comment on the respective issue.
Note
If any of these queries don’t return any results, it means that no module in the selected category is looking for an owner or contributor at the moment.
I want to become the owner of XYZ modules, where can I indicate this, and what are the expected actions from me?
For a proposed module, comment on its open Module Proposal issue. For an existing module, follow the ownership-change process, using the orphaned module issue when adopting an orphaned module. Do not reopen a closed module proposal.
The AVM core team confirms eligibility and acceptance of the role. Add, remove, or transfer owners through a pull request to the root metadata.json using the metadata review process. Editing metadata does not grant access or review permission; follow SNFR20 separately.
Can I submit a PR with new features to an existing module? If so, is this a good way to contribute too?
Of course! As all modules are open source, anyone can submit a PR to an existing module. But we’d suggest opening an issue first to discuss the suggested changes with the module owner before investing time in the code.
Are there any videos on how to get started with contribution? E.g., how to set up a local environment for development, how to write a unit test etc.?
No videos on the technical details of contribution are available (yet), but a detailed, written guidance can be found for both Bicep and Terraform, here:
Is AVM a Microsoft official service/product/library or is this classified as an OSS backed by Microsoft?
AVM is an officially supported OSS project from Microsoft, across all organizations.
AVM is owned, developed & supported by Microsoft, you may raise a GitHub issue on this repository or the module’s repository directly to get support or log feature requests.
You can also log a support ticket and these will be redirected to the AVM team and the module owner(s).
Yes, and if they cannot resolve it (and/or it’s not related to a Microsoft service/platform/api/etc.) they will pass the ticket to the module owner(s) to resolve.
Module owners are tasked to do with two types of maintenance:
Proactive: keeping track of the modules’ underlying technology evolving, and keep modules up to date with the latest features and API versions.
Reactive: sometimes, mistakes are made that result in bugs and/or there might be features consumers ask for faster than module owners could proactively implement them. Consumers can request feature updates and bug fixes for existing modules here.
Can AVM modules be used in production before they are marked as v1.0?
The AVM framework continues to evolve, and several elements, such as Continuous Integration (CI) processes, module specifications and corresponding specificationβvalidation coverage, are not yet fully implemented. For this reason, modules are currently published as 0.x.y minor versions (e.g., 0.1.0, 0.1.1, 0.2.0, etc.).
However, a module does not need to be at version 1.0.0 to be considered production ready. Consumers can use these modules in any environment, including production. Consumers can also raise issues or feature requests as they learn from the usage of the module, and rely on the detailed changelog files (Bicep) and release notes (Terraform) when assessing whether to upgrade to a newer version. Once a module reaches v1.0, semantic versioning will apply fully: breaking changes will be avoided whenever possible, but if they become necessary, they will be introduced through a major version increment.
Why did the AVM team change the support statements and targets in June 2025?
The AVM team has updated the support statements and targets to better align with the current state of the AVM initiative and to ensure that module owners can provide meaningful responses and resolutions to issues raised by consumers. The changes were made to improve clarity, set realistic expectations, and enhance the overall support experience for AVM modules and their consumers.
Should pattern modules leverage resource modules? What if (some of) the required resource modules are not available?
The initial focus of development and migration from CARML/TFVM has solely been on resource modules. Now that the most important resource modules are published, pattern modules can leverage them as and where needed. This however doesn’t mean that the development of pattern modules is blocked in any way if a resource module is not available, since they may use native resources (“vanilla code”). If you’re about to develop a pattern module and would need a resource modules that doesn’t exist today, please consider building the resource module first, so that others can leverage it for their pattern modules as well.
Does AVM have same limitations as ARM (4 MB) size and 255 parameters only?
Yes, as AVM is just a collection of official Bicep/Terraform modules, it still has same Bicep/Terraform language or Azure platform limitations.
Does/will AVM support Managed Identity, and Microsoft Entra objects automation?
Managed Identities - Yes, they are supported in all resources today. Entra objects - May come as new modules if/when the Graph provider will be released which is still in private preview.
How does AVM ensure code quality?
AVM utilizes a number of validation pipelines for both Bicep and Terraform. These pipelines are run on every PR and ensure that the code is compliant with the AVM specifications and that the module is working as expected.
For example, in case of Bicep, as part of the PR process, we’re asking contributors to provide a workflow status badge as a proof of successful validation using our testing pipelines.
The validation includes 2 main stages run in sequence:
Static validation: to ensure that the module complies to AVM specifications.
Deployment validation: to ensure all test examples are working from a deployment perspective.
These same validations are also run in the BRM repository after merge. The new version of the contributed module is published to the Public Bicep Registry only if all validations are successful.
What’s the guidance on transitioning to new module versions?
AVM is not different compared to any other solution using semantic versioning.
Customer should consider updating to a newer version of a module if:
They need a new feature the new version has introduced.
It fixes a bug they were having.
They’d like ot use the latest and greatest version.
To do this they just change the version in their module declaration for either Terraform or Bicep and then run it through their pipelines to roll it out.
The high level steps are:
Check module documentation for any version-incompatibility notes.
Increase the version (point to the selected published version of the module).
Do a what-if (Bicep) or terraform plan (Terraform) & review the changes proposed.
If all good, proceed to deployment/apply.
If not, make required changes to make the plan/what-if as expected.
Using AVM
How can I use Bicep modules through the Public Registry?
Do I need to allow a specific URL to access the Public Registry?
In a regulated environment, network traffic might be limited, especially when using private build agents. The AVM Bicep templates are served from the Microsoft Container Registry. To access this container registry, the URL https://mcr.microsoft.com must be accessible from the network. So, if your network settings or firewall rules prevent access to this URL, you would need to allow it to ensure proper functioning.
Aren’t AVM resource modules too complex for people less skilled in IaC technologies?
TLDR: Resource modules have complexity inside, so they can be flexibly used from the outside.
Resource modules are written in a flexible way; therefore, you don’t need to modify them from project to project, use case to use case, as they aim to cover most of the functionality that a given resource type can provide, in a way that you can interact with any module just by using the required parameters - i.e., you don’t have to know how the template of the particular module works inside, just take a look at the README.md file of the given module to learn how to leverage it.
Resource modules are multi-purpose; therefore, they contain a lot of dynamic expressions (functions, variables, etc.), so there’s no need to maintain multiple instances for different use cases. They can be deployed in different configurations just by changing the input parameters. They should be perceived by the user as black boxes, where they don’t have to worry about the internal complexity of the code, as they only interact with them by their parameters.
Can I call a Bicep child module directly? E.g., can I update or add a secret in an existing Key Vault, or a route in an existing route table?
You can reference Bicep child modules that have been explicitly published to the public bicep registry.
Today, publishing child-modules separately from their parents does not happen by default, and follows an on-demand process. Only child modules explicitly allowed for publishing can be referenced from the registy. The process is currently in a pilot phase, and documented here.
If not directly, you can still reference child modules via their parents. You can reference e.g. a avm/res/key-vault/vault/key through its parent avm/res/key-vault/vault’s keys parameter. Alternatively, you can grab the module folder locally, although this is a workaround and not recommended.
If I use AVM modules in my solution, do I need to have the MIT license in my own repo also? Do I need to add or reference AVM’s license in my solution?
Microsoft is not in the position of providing legal guidance on what licensing model your product/solution/etc. (the “Software”) leveraging Azure Verified Modules can or should be under. Generally speaking, the MIT license is permissive and allows you to freely use, modify, and distribute the code and does not mandate you to have your entire Software under the MIT license, but you must follow the requirements for the MIT-licensed code that you carry. As stated in the AVM LICENSE reference here, the described “copyright notice and permission notice shall be included in all copies or substantial portions of the Software”.
Glossary
Terms, Abbreviations, and Acronyms
This page holds a table of all the terms, abbreviations, and acronyms that are used across this site.
“We are a family of individuals united by a single, shared mission. It’s our ability to work together that makes our dreams believable and, ultimately, achievable. We will build on the ideas of others and collaborate across boundaries to bring the best of Microsoft to our customers as one. We are proud to be part of team Microsoft.” See Microsoft cultural attributes