Building a cloud lab should be easy, but sometimes the cloud has other plans (looking at you, Quota limits!). After a few rounds of troubleshooting, I successfully deployed a Virtual Network and an Ubuntu VM running Nginx in Azure—all from the Cloud Shell.
Here is the full step-by-step guide and the code to make it happen.
1. Setting the Stage (Variables)
Instead of hardcoding names, we use variables. This makes the script reusable.
$rgName = "my-automated-rg"
$location = "eastus2" # Pivot to East US 2 for better availability
$vnetName = "shared-vnet"
$vmSize = "Standard_D2s_v3" # A reliable size with available quota
2. Create the Resource Group and Network
First, we need a "folder" for our resources (Resource Group) and a private network (VNet) with a specific subnet.
# Create Resource Group
New-AzResourceGroup -Name $rgName -Location $location
# Define Subnet
$subConfig = New-AzVirtualNetworkSubnetConfig -Name "calab-subnet" -AddressPrefix "10.0.1.0/24"
# Create VNet
New-AzVirtualNetwork -ResourceGroupName $rgName -Location $location -Name $vnetName `
-AddressPrefix "10.0.0.0/16" -Subnet $subConfig
3. The Public IP (Static)
Modern Azure Standard SKUs require a Static IP.
$pip = New-AzPublicIpAddress -ResourceGroupName $rgName -Location $location `
-Name "test-vm-pip" -AllocationMethod Static -Sku Standard
4. Deploying the VM
We use Get-Credential to set our login once and then deploy. Note that we open port 22 immediately for SSH access.
# Set credentials (if not already set in session)
$myCred = Get-Credential -UserName "azureuser"
# Deploy Ubuntu VM
New-AzVm `
-ResourceGroupName $rgName `
-Name "TestVM" `
-Location $location `
-VirtualNetworkName $vnetName `
-SubnetName "calab-subnet" `
-PublicIpAddressName "test-vm-pip" `
-Credential $myCred `
-OpenPorts 22 `
-Image "Canonical:0001-com-ubuntu-server-jammy:22_04-lts:latest" `
-Size $vmSize
5. Installing Nginx and Opening the Firewall
Now we install the web server without even logging into the machine and open port 80 in the Network Security Group.
# Install Nginx via RunCommand
Invoke-AzVMRunCommand -ResourceGroupName $rgName -VMName "TestVM" -CommandId "RunShellScript" `
-ScriptString "apt-get update && apt-get install -y nginx && systemctl start nginx"
# Open Port 80
Get-AzNetworkSecurityGroup -ResourceGroupName $rgName |
Add-AzNetworkSecurityRuleConfig -Name "AllowHTTP" -Access Allow -Protocol Tcp -Direction Inbound `
-Priority 1001 -SourceAddressPrefix * -SourcePortRange * `
-DestinationAddressPrefix * -DestinationPortRange 80 |
Set-AzNetworkSecurityGroup
6. Verification
Grab your IP and visit it in your browser!
(Get-AzPublicIpAddress -ResourceGroupName $rgName -Name "test-vm-pip").IpAddress
Pro-Tip: Don't forget to Clean Up!
Cloud resources cost money. When you're done, nuke it all with one command:
Remove-AzResourceGroup -Name "my-automated-rg" -Force -AsJob
Top comments (0)