ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bicep Resource Loops with Dynamic Naming

Bicep

Goal -- WPM

Ready
Exercise Algorithm Area
1param vmNamePrefix string
2param location string = deployment().location
3param numberOfVms int
4
5// Validate that the number of VMs is at least 1.
6@minValue(1)
7param validatedNumberOfVms int = numberOfVms
8
9// Helper function to generate a unique name for each VM.
10// This function takes a prefix and an index, and concatenates them.
11// Example: vmNamePrefix='myVM', index=0 -> 'myVM-0'
12func generateVmName(prefix string, index int) string {
13return '${prefix}-${index}'
14}
15
16// Deploy multiple Virtual Machines using a for loop.
17// The loop iterates from 0 up to (but not including) validatedNumberOfVms.
18// For each iteration, a new VM resource is created.
19resource virtualMachines 'Microsoft.Compute/virtualMachines@2021-07-01' = [for i in range(0, validatedNumberOfVms) {
20name: generateVmName(vmNamePrefix, i) // Dynamically generate the VM name
21location: location
22properties: {
23// Basic VM properties:
24hardwareProfile: {
25vmSize: 'Standard_B1s'
26}
27storageProfile: {
28imageReference: {
29publisher: 'Canonical'
30offer: '0001-com-ubuntu-server-jammy'
31version: '22.04.202307190'
32sku: '22_04-lts'
33}
34osDisk: {
35createOption: 'FromImage'
36managedDisk: {
37storageAccountType: 'Standard_LRS'
38}
39}
40}
41osProfile: {
42computerName: generateVmName(vmNamePrefix, i) // Also set the computer name inside the VM
43adminUsername: 'azureuser'
44adminPassword: 'Password123!' // In production, use secure parameters or Azure Key Vault
45}
46networkProfile: {
47networkInterfaces: [
48// Placeholder for network interface configuration.
49// In a real scenario, this would reference a NIC resource.
50]
51}
52}
53}]
54
55// Output the names of the deployed virtual machines.
56// This array will contain the dynamically generated names.
57output deployedVmNames array = [for i in range(0, validatedNumberOfVms) {
58name: virtualMachines[i].name
59}]
60
61// --- Additional Helper Functions for Robustness ---
62
63// Function to generate a unique resource group name based on a prefix and environment.
64// This is a common pattern for ensuring resource uniqueness across deployments.
65func generateResourceGroupName(prefix string, env string) string {
66return '${prefix}-rg-${env}'
67}
68
69// Example of using the additional helper function (conceptual)
70// This demonstrates how naming conventions can be standardized for other resources.
71// The actual VM names are generated by generateVmName.
72var exampleResourceGroupName = generateResourceGroupName('myApp', 'dev')
73
74// Output the example resource group name for verification (conceptual)
75output conceptualResourceGroupName string = exampleResourceGroupName
Algorithm description viewbox

Bicep Resource Loops with Dynamic Naming

Algorithm description:

This Bicep module demonstrates the use of `for` loops to deploy multiple identical resources, specifically virtual machines. It takes a `vmNamePrefix` and `numberOfVms` as input, dynamically generating a unique name for each VM by appending its loop index to the prefix. A validation ensures that at least one VM is requested. This pattern is highly useful for provisioning groups of similar resources, such as web servers or worker nodes, where consistent naming conventions are important for management and automation.

Algorithm explanation:

The module utilizes Bicep's `for` loop construct combined with the `range` function to iterate a specified number of times (`validatedNumberOfVms`). In each iteration, a `Microsoft.Compute/virtualMachines` resource is declared. The `generateVmName` helper function is used to create a unique `name` and `properties.osProfile.computerName` for each VM by concatenating the `vmNamePrefix` with the current loop index `i`. The `@minValue(1)` decorator on `validatedNumberOfVms` ensures that at least one VM is always deployed, handling the edge case of zero VMs requested. The time complexity is linear with respect to `numberOfVms`, as each VM resource is provisioned independently. Space complexity is also linear, proportional to the number of VMs and their configurations. The primary edge case handled is ensuring a positive number of VMs, and the dynamic naming prevents conflicts when deploying multiple instances.

Pseudocode:

Define input parameters: VM name prefix, location, number of VMs.
Validate that the number of VMs is at least 1.
Create a helper function to generate a VM name by combining the prefix and the loop index.
Use a `for` loop to iterate from 0 up to the number of VMs:
  For each iteration, create a virtual machine resource.
  Set the VM's name using the generated VM name from the helper function.
  Configure basic VM properties (size, image, OS disk, OS profile, network profile).
Output an array containing the names of all deployed virtual machines.