EcoMarket is already deployed on AWS: a VPC with per-zone subnets, PostgreSQL in private, an images bucket with versioning and encryption, a load balancer and an auto scaling group. This lesson deploys exactly the same platform on Azure, and its aim is not for you to memorise resource names: it is for you to confirm that what you learned was not AWS, it was infrastructure. The strategy will be to teach by equivalence — which concept is the same under another name — and, above all, to point precisely at the three or four things that are genuinely different and that force the code to be reorganised: the resource group, the identity model, the global uniqueness of certain names, and the soft delete that makes a destroy look as though it worked when it did not quite.
As in the previous lesson, each section states the approximate cost and what falls within the free tier, and at the end there is a guided destroy with the list of what survives. All identifiers are fictional: the domain is ecomarket.example.com and the subscription and tenant GUIDs are examples.
- The AWS ↔ Azure equivalence map
This table is the scaffolding for the whole lesson. Keep it to hand.
| Concept | AWS | Azure | Exact equivalence? |
|---|---|---|---|
| Billing and isolation boundary | Account | Subscription | Yes, conceptually |
| Identity boundary | Account (its own IAM) | Tenant (Entra ID), shared across subscriptions | No: one identity can operate in several subscriptions |
| Logical grouping of resources | Tags (and nothing else) | Resource group (mandatory) | Does not exist in AWS |
| Private network | VPC | Virtual network (VNet) | Yes |
| Subnet | Subnet (tied to a zone) | Subnet (regional, not zonal) | No: in Azure a subnet spans every zone |
| Instance firewall | Security group (stateful, allow-only) | Network security group (with priorities and deny rules) | Similar, not identical |
| Virtual machine | EC2 | Virtual machine | Yes |
| Scaling | Auto scaling group | Virtual machine scale set | Yes |
| Layer 7 load balancer | Application load balancer | Application Gateway | Yes |
| Layer 4 load balancer | Network load balancer | Load Balancer | Yes |
| PostgreSQL database | RDS | Azure Database for PostgreSQL Flexible Server | Yes |
| Object storage | S3 bucket | Storage account + container (two levels) | No: it is two resources, not one |
| Secret management | Secrets Manager | Key Vault | Yes, with soft delete |
| Machine identity | Role + instance profile | Managed identity | Yes, and simpler |
| Permissions | IAM policies (JSON, on the resource or the principal) | RBAC: a role assignment over a scope | No: a different model |
| System image | AMI (per region) | Image reference (publisher/offer/SKU) | Similar |
| Region | Region (eu-west-1) |
Location (westeurope, northeurope) |
Yes |
| Availability zone | AZ | Availability zone (1, 2, 3) | Yes, but assigned to the resource, not to the subnet |
The four rows in bold are the ones that force you to think differently, and the three most important are:
- The resource group changes how the entire codebase is organised: every resource belongs to one, and deleting it takes everything inside with it.
- Subnets are regional, not zonal. In AWS you created one subnet per zone; in Azure you create one subnet and assign the zone to each virtual machine. That simplifies the network and complicates reasoning about high availability.
- RBAC is not IAM. You do not write a JSON policy and attach it to a principal: you assign a built-in role (or a custom one) to an identity over a scope (subscription, resource group or specific resource). That is three conceptual resources, not two.
- The
azurerm provider: the mandatory features {} block
azurerm provider: the mandatory features {} block# infra/app/versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 4.0" # 4.x requires an explicit subscription_id
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
}# infra/app/providers.tf
provider "azurerm" {
# MANDATORY since version 2.0, even when empty.
features {}
# MANDATORY since version 4.0 (in 3.x it was inferred from the CLI).
subscription_id = var.subscription_id
}The features {} block is the first oddity everybody runs into. It is mandatory even if you configure nothing inside it, and if you leave it out the init fails:
╷
│ Error: Insufficient features blocks
│
│ on providers.tf line 1, in provider "azurerm":
│ 1: provider "azurerm" {
│
│ At least 1 "features" blocks are required.
╵It exists because Azure has destructive behaviours that HashiCorp did not want to decide for you. They are configured inside it, and some are essential for destroy to work at all:
provider "azurerm" {
subscription_id = var.subscription_id
features {
resource_group {
# false (default): the destroy FAILS if unmanaged resources remain inside.
# true: deletes the resource group along with whatever it holds. DANGEROUS.
prevent_deletion_if_contains_resources = var.environment == "prod"
}
key_vault {
# With soft delete on, a destroy leaves the vault "deleted but recoverable".
purge_soft_delete_on_destroy = var.environment != "prod"
recover_soft_deleted_key_vaults = true
}
virtual_machine {
delete_os_disk_on_deletion = true
graceful_shutdown = false
skip_shutdown_and_force_delete = false
}
postgresql_flexible_server {
restart_server_on_configuration_value_change = true
}
}
}This block is the most important piece of the lesson for a practice environment, and we will explain it twice: here, and in section 13, when soft delete bites.
| Option | Effect if false |
Effect if true |
Recommendation |
|---|---|---|---|
prevent_deletion_if_contains_resources |
The destroy deletes the group along with whatever is inside |
The destroy fails if there is anything unmanaged |
true in prod, false in a lab |
purge_soft_delete_on_destroy |
The vault is left deleted but recoverable, and its name stays taken | It is genuinely purged and the name is released | true in dev, false in prod |
recover_soft_deleted_key_vaults |
Creating a vault with a soft-deleted name fails | It recovers it instead of failing | true |
delete_os_disk_on_deletion |
The OS disk outlives the VM and keeps billing | It is deleted with the VM | true unless there is an explicit reason |
That second virtual_machine row is what generates Azure's most common phantom bill: managed disks orphaned from machines that no longer exist.
- Authentication: CLI, service principal and managed identity
As in AWS, the rule does not change: no secrets in a .tf. The routes, from least to most mature:
| Method | Variables / commands | When |
|---|---|---|
| Azure CLI | az login, and the provider uses the session |
One person's local development. Recommended for this course |
| Service principal with a secret | ARM_CLIENT_ID, ARM_CLIENT_SECRET, ARM_TENANT_ID, ARM_SUBSCRIPTION_ID |
Legacy automation. The secret has to be rotated |
| Service principal with a certificate | ARM_CLIENT_CERTIFICATE_PATH |
Better than a secret, but there is still material to guard |
| Managed identity | ARM_USE_MSI=true |
Terraform running on an Azure VM or container |
| Federated OIDC | ARM_USE_OIDC=true + a federated credential in Entra ID |
Production. No long-lived secrets. Detailed in module 8 |
Verification before you start, the equivalent of aws sts get-caller-identity:
# Sign in and pick a subscription
az login
az account set --subscription "11111111-2222-3333-4444-555555555555"
# Who am I and where am I?
az account show --query "{subscription:name, id:id, tenant:tenantId, user:user.name}" -o table
# Which locations are available to me?
az account list-locations --query "[?metadata.regionCategory=='Recommended'].name" -o tsv | sort
# How many vCPUs can I use in westeurope? (the quota that runs out first)
az vm list-usage --location westeurope -o table | head -20And the equivalent data sources inside the code:
# infra/app/account-data.tf
data "azurerm_client_config" "current" {}
data "azurerm_subscription" "current" {}
locals {
tenant_id = data.azurerm_client_config.current.tenant_id
current_object = data.azurerm_client_config.current.object_id
subscription_id = data.azurerm_subscription.current.subscription_id
}
check "correct_subscription" {
assert {
condition = data.azurerm_subscription.current.subscription_id == var.expected_subscription
error_message = "Connected to subscription ${data.azurerm_subscription.current.display_name}, a different one was expected. Check 'az account set'."
}
}data.azurerm_client_config.current.object_id will show up several times: it is the identifier of the principal running Terraform, and it is needed to grant yourself permissions on the key vault.
- The resource group: the concept that does not exist in AWS
In AWS, a resource belongs to an account and a region, and that is that. In Azure every resource belongs, compulsorily, to a resource group, which is a folder with three very specific properties:
| Resource group property | Practical consequence |
|---|---|
| It is mandatory and stated on every resource | Every resource carries resource_group_name and location |
| Deleting it deletes everything it contains | Destroying the group is the ultimate cleanup… and the ultimate accident |
| It is the natural scope for RBAC and for tags | "Give the data team access" = one role assignment over their group |
| It has its own location | That is where the metadata lives, not necessarily where the resources are |
| Resource names are unique within the group | Two environments can have resources with the same name in different groups |
That last row changes EcoMarket's naming design. In AWS, local.prefix was essential to tell ecomarket-dev-vpc apart from ecomarket-prod-vpc. In Azure, with one group per environment, you could call both of them ecomarket-vnet. EcoMarket keeps the prefix anyway, for three reasons: names appear in dashboards and alerts without the group's context, some resources (the storage account, the key vault) need globally unique names in any case, and consistency across clouds is worth more than saving fifteen characters.
EcoMarket's grouping strategy:
flowchart TB
SUS["Subscription<br/>ecomarket-platform"]
subgraph RGD["rg-ecomarket-dev"]
VN1["VNet + subnets"]
VM1["Scale set"]
BD1[("PostgreSQL")]
ST1["Storage account"]
KV1["Key Vault"]
end
subgraph RGS["rg-ecomarket-staging"]
X1["(the same)"]
end
subgraph RGP["rg-ecomarket-prod"]
X2["(the same)"]
end
subgraph RGC["rg-ecomarket-shared"]
DNS["DNS zone<br/>ecomarket.example.com"]
ACR["Container registry"]
TFS["State<br/>storage"]
end
SUS --> RGD
SUS --> RGS
SUS --> RGP
SUS --> RGC
style RGP fill:#fee2e2,stroke:#dc2626
style RGC fill:#f3f4f6,stroke:#6b7280
One resource group per environment, plus a shared one for whatever outlives every environment. This decision has a direct and very useful consequence: destroying a practice environment becomes deleting its group, and there is no way to leave orphans behind inside it.
resource "azurerm_resource_group" "main" {
name = "rg-${local.prefix}" # rg-ecomarket-dev
location = var.location # westeurope
tags = local.common_tags
lifecycle {
prevent_destroy = false # true in prod
}
}And here comes the warning it deserves:
Warning.
azurerm_resource_groupis the most dangerous resource in Azure. Aterraform destroyon it deletes everything it contains, including whatever other teams created by hand, and that does not show up in Terraform's plan because Terraform does not know about it. Inprod,prevent_destroy = trueon the group andprevent_deletion_if_contains_resources = trueon the provider, plus an Azure-level management lock (azurerm_management_lock) that no tool can bypass without removing it first.
resource "azurerm_management_lock" "production" {
count = var.environment == "prod" ? 1 : 0
name = "do-not-delete-${local.prefix}"
scope = azurerm_resource_group.main.id
lock_level = "CanNotDelete"
notes = "EcoMarket production protection. Contact: [email protected]"
}That lock is a barrier on the Azure side, the conceptual equivalent of RDS's deletion_protection: it also stops deletions from the portal and from the CLI.
- Networking: virtual network, subnets and delegations
resource "azurerm_virtual_network" "main" {
name = "${local.prefix}-vnet"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
address_space = [var.cidr] # ["10.20.0.0/16"] — it is a LIST, not a string
tags = local.tags
}First syntactic difference: address_space is a list. A virtual network can have several address spaces from the outset, something that in AWS requires additional CIDR associations.
Subnets are regional, so EcoMarket does not need one per zone: it needs one per function.
locals {
subnets = {
# The web lives here. No delegation: these are ordinary virtual machines.
web = {
cidr = cidrsubnet(var.cidr, 8, 0) # 10.20.0.0/24
delegation = null
services = ["Microsoft.Storage", "Microsoft.KeyVault"]
}
# PostgreSQL Flexible Server with private networking integration REQUIRES
# a delegated subnet EMPTY of everything else.
data = {
cidr = cidrsubnet(var.cidr, 8, 1) # 10.20.1.0/24
delegation = "Microsoft.DBforPostgreSQL/flexibleServers"
services = []
}
# The Application Gateway also requires its own exclusive subnet.
gateway = {
cidr = cidrsubnet(var.cidr, 8, 2) # 10.20.2.0/24
delegation = null
services = []
}
}
}
resource "azurerm_subnet" "main" {
for_each = local.subnets
name = "${local.prefix}-snet-${each.key}"
resource_group_name = azurerm_resource_group.main.name
virtual_network_name = azurerm_virtual_network.main.name
address_prefixes = [each.value.cidr]
service_endpoints = each.value.services
dynamic "delegation" {
for_each = each.value.delegation != null ? [each.value.delegation] : []
content {
name = "delegation"
service_delegation {
name = delegation.value
actions = [
"Microsoft.Network/virtualNetworks/subnets/join/action",
]
}
}
}
}Delegations are a concept with no AWS equivalent and they have to be understood. Delegating a subnet means handing its management over to an Azure service: that service injects its own network resources into it and nothing else can live in that subnet. PostgreSQL Flexible Server with private networking requires it. If you try to put a virtual machine in a delegated subnet:
╷ │ Error: creating Linux Virtual Machine: Subnet 'ecomarket-dev-snet-data' │ is delegated to 'Microsoft.DBforPostgreSQL/flexibleServers' and cannot │ be used by resources of type 'Microsoft.Network/networkInterfaces'. ╵
service_endpoints are another useful quirk: they make traffic towards that Azure service (storage, key vault) leave via Azure's backbone instead of the Internet, at no extra cost. It is the cheap equivalent of AWS's VPC endpoints; the full version, azurerm_private_endpoint, gives you a private IP inside the virtual network and does cost money (~$7/month each).
- Network security groups and their association
A network security group resembles an AWS security group, but it has three differences that matter:
| AWS security group | Azure network security group | |
|---|---|---|
| Deny rules | Do not exist: everything is "allow", whatever is not allowed is denied | They do exist: there are explicit Allow and Deny |
| Ordering | Irrelevant: rules are a set | Numeric priority from 100 to 4096; the lowest wins |
| Association | To the instance's network interface | To a subnet or to an interface (or both, and both apply) |
| Default rules | Deny inbound, allow outbound | Implicit rules that allow traffic within the virtual network and from the load balancer |
| Referencing another group | referenced_security_group_id |
source_application_security_group_ids (application security groups) |
The numeric priority is what confuses arrivals from AWS the most: order matters, and a Deny rule with priority 100 beats an Allow with priority 200.
resource "azurerm_network_security_group" "web" {
name = "${local.prefix}-nsg-web"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
tags = local.tags
}
resource "azurerm_network_security_rule" "web_https_from_gateway" {
name = "allow-https-from-gateway"
resource_group_name = azurerm_resource_group.main.name
network_security_group_name = azurerm_network_security_group.web.name
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_address_prefix = local.subnets.gateway.cidr
source_port_range = "*"
destination_address_prefix = local.subnets.web.cidr
destination_port_range = "8080"
}
resource "azurerm_network_security_rule" "deny_ssh_from_internet" {
name = "deny-ssh-internet"
resource_group_name = azurerm_resource_group.main.name
network_security_group_name = azurerm_network_security_group.web.name
priority = 200
direction = "Inbound"
access = "Deny"
protocol = "Tcp"
source_address_prefix = "Internet" # a service tag, not a CIDR
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "22"
}
resource "azurerm_subnet_network_security_group_association" "web" {
subnet_id = azurerm_subnet.main["web"].id
network_security_group_id = azurerm_network_security_group.web.id
}Two elements with no direct AWS equivalent that are very practical:
- Service tags (
Internet,VirtualNetwork,AzureLoadBalancer,Storage,Sql) replace lists of CIDRs that change over time. Microsoft keeps them up to date. Using"Internet"instead of"0.0.0.0/0"is more expressive and more correct. - The association is a separate resource. Just like AWS security group rules in their modern form, this lets one module create the group and another associate it.
Security warning. Azure creates default rules that allow all traffic within the virtual network. That means that, without additional rules, the gateway subnet can talk to the data subnet. Real segmentation requires explicit
Denyrules with a low priority between subnets that must not communicate. It is a shift in mental model compared with AWS, where nothing is allowed by default, and it is the kind of decision the security team must review resource by resource.
- Internet egress: public IP and NAT gateway
In Azure, a virtual machine in a subnet with no public IP has Internet egress by default through an implicit address translation. That sounds convenient and it is a bad idea: the outbound address changes without notice, it cannot be allow-listed, and Microsoft has announced its retirement. The right way is an explicit NAT gateway.
resource "azurerm_public_ip" "nat" {
count = var.create_nat ? 1 : 0
name = "${local.prefix}-pip-nat"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
allocation_method = "Static" # mandatory with the Standard SKU
sku = "Standard" # mandatory for a NAT gateway
zones = ["1", "2", "3"]
tags = local.tags
}
resource "azurerm_nat_gateway" "egress" {
count = var.create_nat ? 1 : 0
name = "${local.prefix}-natgw"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
sku_name = "Standard"
idle_timeout_in_minutes = 10
tags = local.tags
}
resource "azurerm_nat_gateway_public_ip_association" "egress" {
count = var.create_nat ? 1 : 0
nat_gateway_id = azurerm_nat_gateway.egress[0].id
public_ip_address_id = azurerm_public_ip.nat[0].id
}
resource "azurerm_subnet_nat_gateway_association" "web" {
count = var.create_nat ? 1 : 0
subnet_id = azurerm_subnet.main["web"].id
nat_gateway_id = azurerm_nat_gateway.egress[0].id
}Cost warning. An Azure NAT gateway costs ~$0.045/hour (~$33/month) plus ~$0.045/GB processed, practically the same as in AWS, and it has no free tier either. The Standard public IP adds ~$0.005/hour (~$3.6/month). In
dev, EcoMarket usescreate_nat = falseand accepts the default egress or, better, needs no egress at all. A FinOps review is mandatory before enabling it in more than one environment.
One structural difference from AWS worth nailing down: Azure's NAT gateway is regional and covers every zone, so you need one, not one per zone. Where AWS charged you for three gateways to have high availability across three zones, Azure charges for one. That is the pay-off of subnets being regional.
- Compute (I): virtual machine and network interface
In Azure, the network interface is always a separate resource. There is no subnet_id inside the virtual machine.
resource "azurerm_network_interface" "web" {
count = var.fixed_instances
name = "${local.prefix}-nic-web-${count.index}"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.main["web"].id
private_ip_address_allocation = "Dynamic"
# No public_ip_address_id: the machine is not reachable from the Internet.
}
tags = local.tags
}
resource "azurerm_linux_virtual_machine" "web" {
count = var.fixed_instances
name = "${local.prefix}-vm-web-${count.index}"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
size = var.vm_size # Standard_B1s: free tier 750 h/month (12 months)
zone = tostring((count.index % 3) + 1) # the zone is assigned to the VM, not the subnet
network_interface_ids = [azurerm_network_interface.web[count.index].id]
# Administrator user: no password, public key only.
admin_username = var.admin_user
disable_password_authentication = true
admin_ssh_key {
username = var.admin_user
public_key = var.ssh_public_key # the PUBLIC one. Never the private one
}
os_disk {
caching = "ReadWrite"
storage_account_type = "StandardSSD_LRS" # Premium_LRS is faster and dearer
disk_size_gb = 30
}
source_image_reference {
publisher = "Canonical"
offer = "ubuntu-24_04-lts"
sku = "server"
version = "latest"
}
# Managed identity: the equivalent of AWS's instance role.
identity {
type = "SystemAssigned"
}
# Startup script. Covered in depth in 05-05.
custom_data = base64encode(templatefile("${path.module}/templates/startup.sh.tftpl", {
db_endpoint = var.db_endpoint
container = var.images_container
environment = var.environment
}))
tags = local.tags
lifecycle {
ignore_changes = [
# "latest" changes when Canonical publishes: avoids surprise replacements.
source_image_reference,
custom_data,
]
}
}Four differences from AWS worth underlining:
source_image_referenceis a four-field tuple (publisher, offer, SKU, version) instead of a unique AMI identifier. The advantage: the same block works in any region, with nodatasource to look anything up. The drawback:version = "latest"has the same trap asmost_recent, and the fix is the same (ignore_changesor a pinned version).- The zone is assigned to the machine, not to the subnet, because the subnet is regional. Spreading across zones is a compute decision.
disable_password_authentication = trueis correct and is not the default on every path. A Linux machine on Azure with password authentication enabled and port 22 reachable is a target within minutes.identity { type = "SystemAssigned" }replaces AWS's whole role-and-instance-profile apparatus. It is one line, and Azure creates a principal in Entra ID tied to the machine's lifecycle. It is genuinely simpler.
Security warning.
var.ssh_public_keyis the public key. It sounds obvious and yet the confusion happens: pasting a private key into a Terraform variable leaves it in the state and in the repository history. If a private key leaks, rotate it immediately. And the best option is not to use SSH at all: Azure Bastion or the AAD extension for SSH avoid opening the port.
- Compute (II): scale set and load balancer
The equivalent of AWS's auto scaling group, with the advantage that the template lives inside the resource instead of being a separate one:
resource "azurerm_linux_virtual_machine_scale_set" "web" {
name = "${local.prefix}-vmss-web"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
sku = var.vm_size
instances = var.instances.desired
zones = ["1", "2", "3"] # automatic spread across zones
# Upgrade mode: Automatic applies changes to existing instances.
upgrade_mode = "Rolling"
rolling_upgrade_policy {
max_batch_instance_percent = 50
max_unhealthy_instance_percent = 50
max_unhealthy_upgraded_instance_percent = 20
pause_time_between_batches = "PT2M" # ISO 8601 format
}
# Required for Rolling: Azure must know whether an instance is healthy.
health_probe_id = azurerm_lb_probe.web.id
admin_username = var.admin_user
disable_password_authentication = true
admin_ssh_key {
username = var.admin_user
public_key = var.ssh_public_key
}
source_image_reference {
publisher = "Canonical"
offer = "ubuntu-24_04-lts"
sku = "server"
version = "latest"
}
os_disk {
caching = "ReadWrite"
storage_account_type = "StandardSSD_LRS"
}
network_interface {
name = "internal"
primary = true
ip_configuration {
name = "internal"
primary = true
subnet_id = azurerm_subnet.main["web"].id
load_balancer_backend_address_pool_ids = [
azurerm_lb_backend_address_pool.web.id,
]
}
}
identity {
type = "SystemAssigned"
}
custom_data = base64encode(templatefile("${path.module}/templates/startup.sh.tftpl", {
db_endpoint = var.db_endpoint
container = var.images_container
environment = var.environment
}))
tags = local.tags
lifecycle {
ignore_changes = [instances] # auto scaling governs it
}
}And the layer 4 load balancer, which is four resources:
resource "azurerm_public_ip" "load_balancer" {
name = "${local.prefix}-pip-lb"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
allocation_method = "Static"
sku = "Standard"
zones = ["1", "2", "3"]
# DNS label: gives a stable name ecomarket-dev.westeurope.cloudapp.azure.com
domain_name_label = "${local.prefix}-${var.suffix}"
tags = local.tags
}
resource "azurerm_lb" "web" {
name = "${local.prefix}-lb"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
sku = "Standard"
frontend_ip_configuration {
name = "public"
public_ip_address_id = azurerm_public_ip.load_balancer.id
}
tags = local.tags
}
resource "azurerm_lb_backend_address_pool" "web" {
name = "${local.prefix}-backend"
loadbalancer_id = azurerm_lb.web.id
}
resource "azurerm_lb_probe" "web" {
name = "health-http"
loadbalancer_id = azurerm_lb.web.id
protocol = "Http"
port = 8080
request_path = "/health"
interval_in_seconds = 15
number_of_probes = 2
}
resource "azurerm_lb_rule" "https" {
name = "https"
loadbalancer_id = azurerm_lb.web.id
frontend_ip_configuration_name = "public"
protocol = "Tcp"
frontend_port = 443
backend_port = 8080
backend_address_pool_ids = [azurerm_lb_backend_address_pool.web.id]
probe_id = azurerm_lb_probe.web.id
disable_outbound_snat = true
}Load Balancer or Application Gateway. The first is layer 4 (TCP) and the second layer 7 (HTTP), and the choice is not a matter of taste:
| Load Balancer (Standard) | Application Gateway (v2) | |
|---|---|---|
| Layer | 4 (TCP/UDP) | 7 (HTTP/HTTPS) |
| TLS termination | No | Yes, with a certificate in Key Vault |
| Routing by path or header | No | Yes |
| Web application firewall | No | Yes (WAF SKU) |
| Approximate cost | ~$18/month + rules | ~$180-250/month with WAF, ~$125/month without it |
| AWS equivalent | Network Load Balancer | Application Load Balancer |
The cost difference is why this lesson uses Load Balancer: Application Gateway is ten times dearer than an AWS application load balancer and is not acceptable in a practice environment. EcoMarket in prod would use Application Gateway with WAF; in dev, Load Balancer or nothing.
- Data: PostgreSQL Flexible Server with private networking
# Private DNS zone: without this, the server name does not resolve inside the network.
resource "azurerm_private_dns_zone" "postgres" {
name = "${local.prefix}.postgres.database.azure.com"
resource_group_name = azurerm_resource_group.main.name
tags = local.tags
}
resource "azurerm_private_dns_zone_virtual_network_link" "postgres" {
name = "${local.prefix}-link-postgres"
resource_group_name = azurerm_resource_group.main.name
private_dns_zone_name = azurerm_private_dns_zone.postgres.name
virtual_network_id = azurerm_virtual_network.main.id
registration_enabled = false
}
resource "azurerm_postgresql_flexible_server" "main" {
name = "${local.prefix}-psql-${var.suffix}" # unique within Azure's domain
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
version = "16"
sku_name = var.db_sku # B_Standard_B1ms: the cheapest one
storage_mb = var.storage_mb # 32768 = 32 GB, the minimum
administrator_login = var.db_user
administrator_password = var.db_password # sensitive, from TF_VAR_db_password
# Private networking integration: the DELEGATED subnet from section 5.
delegated_subnet_id = azurerm_subnet.main["data"].id
private_dns_zone_id = azurerm_private_dns_zone.postgres.id
public_network_access_enabled = false
zone = "1"
backup_retention_days = var.retention_days
geo_redundant_backup_enabled = var.environment == "prod"
dynamic "high_availability" {
for_each = var.high_availability ? [1] : []
content {
mode = "ZoneRedundant"
standby_availability_zone = "2"
}
}
tags = local.tags
depends_on = [azurerm_private_dns_zone_virtual_network_link.postgres]
lifecycle {
ignore_changes = [
administrator_password, # rotated outside Terraform
zone, # Azure may move it during a failover
]
}
}
resource "azurerm_postgresql_flexible_server_database" "ecomarket" {
name = "ecomarket"
server_id = azurerm_postgresql_flexible_server.main.id
collation = "en_US.utf8"
charset = "utf8"
lifecycle {
prevent_destroy = false # true in prod
}
}
# Server parameters: the equivalent of an RDS parameter group.
resource "azurerm_postgresql_flexible_server_configuration" "slow_log" {
name = "log_min_duration_statement"
server_id = azurerm_postgresql_flexible_server.main.id
value = "1000" # logs queries taking more than 1 second
}Five things that set this apart from RDS and cause most first-attempt failures:
- The private DNS zone is mandatory with private networking, and it has to be linked to the virtual network. Without it, the server exists but its name does not resolve — exactly the same symptom as forgetting
enable_dns_hostnamesin AWS. - The
depends_onon the DNS zone link is real. Without it, server creation fails intermittently: it is a dependency that no reference implies. - The delegated subnet can only contain the server. Size it generously (a
/24is plenty) and put nothing else in it. public_network_access_enabled = falseand private networking are mutually exclusive with firewall rules. Azure offers two modes — public access with firewall rules, or private access with a virtual network — and you cannot switch from one to the other without recreating the server. Choosing badly at the start costs a migration.- Changing the access type, the major version or the subnet forces replacement. Same principle as in AWS: always look for
# forces replacement.
The firewall mode, which is the one used for quick tests without a virtual network:
# ONLY for a lab, and with public_network_access_enabled = true.
resource "azurerm_postgresql_flexible_server_firewall_rule" "my_ip" {
name = "development-access"
server_id = azurerm_postgresql_flexible_server.main.id
start_ip_address = var.my_public_ip
end_ip_address = var.my_public_ip
}Security warning. Never use
0.0.0.0to255.255.255.255in a PostgreSQL firewall rule, nor the "allow Azure services" checkbox in production: that last one opens the server to any Azure subscription in the world, not just yours. It is a widespread misconfiguration with serious consequences. Any database firewall rule must be reviewed by the security team.
Cost warning.
B_Standard_B1mswith 32 GB runs at around $13-15/month. The Azure free account includes 750 hours of B1ms and 32 GB for 12 months.GP_Standard_D2s_v3goes up to ~$120/month, andhigh_availabilitydoubles the server's cost. Geo-redundant backups add a per-GB charge.
- Storage: storage account and container
Here is the most visible structural difference from S3: in Azure there are two levels. The storage account is the billable resource with a global name; the container is the top-level folder inside it.
resource "azurerm_storage_account" "images" {
# GLOBALLY unique name, 3-24 characters, ONLY lower case and digits.
# No hyphens. Hence the replace().
name = substr(replace("${local.prefix}img${var.suffix}", "-", ""), 0, 24)
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
account_tier = "Standard"
account_replication_type = var.replication # LRS, ZRS, GRS...
account_kind = "StorageV2"
access_tier = "Hot"
# Security: the four that must never be missing.
https_traffic_only_enabled = true
min_tls_version = "TLS1_2"
allow_nested_items_to_be_public = false
shared_access_key_enabled = var.environment != "prod" # in prod, Entra ID only
blob_properties {
versioning_enabled = true
delete_retention_policy {
days = 7 # blob soft delete: recoverable for 7 days
}
container_delete_retention_policy {
days = 7
}
}
network_rules {
default_action = "Deny" # deny by default, allow explicitly
bypass = ["AzureServices"]
virtual_network_subnet_ids = [
azurerm_subnet.main["web"].id, # only the web gets in
]
ip_rules = var.admin_ips # your IP, so you can upload from your laptop
}
tags = local.tags
}
resource "azurerm_storage_container" "images" {
name = "images"
storage_account_id = azurerm_storage_account.images.id
container_access_type = "private" # NEVER "blob" or "container"
}
# Lifecycle rules: the equivalent of aws_s3_bucket_lifecycle_configuration.
resource "azurerm_storage_management_policy" "images" {
storage_account_id = azurerm_storage_account.images.id
rule {
name = "archive-old-images"
enabled = true
filters {
prefix_match = ["images/"]
blob_types = ["blockBlob"]
}
actions {
base_blob {
tier_to_cool_after_days_since_modification_greater_than = 90
tier_to_archive_after_days_since_modification_greater_than = 365
}
version {
delete_after_days_since_creation = 30
}
}
}
}The replication levels in a table, because it is the most frequent cost-and-resilience decision in Azure:
| Type | What it does | Survives | Relative cost | When |
|---|---|---|---|---|
| LRS | 3 copies in a single data centre | A disk or rack failure | 1.0× (baseline) | dev, regenerable data |
| ZRS | 3 copies across 3 zones in the region | The loss of a whole zone | ~1.25× | A single region's prod |
| GRS | LRS + asynchronous replica in the paired region | The loss of the entire region | ~2.0× | Critical data, disaster recovery |
| GZRS | ZRS + replica in the paired region | Zone and region | ~2.5× | Maximum resilience |
| RA-GRS / RA-GZRS | The same, with the replica readable | The same, and it allows reads from the secondary | +~0.25× over its baseline | Global reads or querying during an incident |
EcoMarket uses LRS in dev and staging and GZRS in prod for the images container, which is original supplier content and cannot be regenerated. The general rule: if losing it means asking a human for the data again, do not use LRS.
Two warnings specific to the name:
- Lower case and digits only, 3 to 24 characters, unique across all of Azure.
ecomarket-dev-imagesis invalid because of the hyphens and the length. Hence thereplace()and thesubstr(). - The name is global, so
ecomarketimagesis almost certainly taken. The randomrandom_petsuffix EcoMarket has been carrying since module 4 solves this, just as it solved the S3 bucket name.
Cost warning. Hot storage with LRS costs ~$0.018/GB/month in West Europe, plus ~$0.05 per 10,000 write operations. The free account includes 5 GB for 12 months. As in AWS, an empty account costs nothing: it is the safest resource to practise with. The archive tier is ten times cheaper to store and expensive and slow to retrieve (hours), so do not use it for anything you might need soon.
- Identity and secrets: managed identity and key vault
This is where the deepest model shift shows. In AWS: you created a role, wrote a JSON policy, attached it and wrapped the lot in an instance profile. In Azure: the machine already has an identity (one line), and you assign it a role over a scope.
flowchart LR
VM["Scale set<br/><code>identity { SystemAssigned }</code>"]
PR["Principal in Entra ID<br/><i>created by Azure,<br/>tied to the VM</i>"]
subgraph ASIG["azurerm_role_assignment"]
direction TB
A1["scope: the CONTAINER<br/>role: Storage Blob Data Contributor"]
A2["scope: the KEY VAULT<br/>role: Key Vault Secrets User"]
end
CT[("Container<br/>images")]
KV[("Key Vault<br/>password-postgres")]
VM -->|"one line"| PR
PR --> A1 --> CT
PR --> A2 --> KV
VM -.->|"token from the metadata,<br/><b>no credentials</b>"| CT
VM -.-> KV
style PR fill:#fef3c7,stroke:#d97706
style ASIG fill:#dbeafe,stroke:#2563eb
Compare it with the equivalent diagram in 05-02: there, five resources sat between the instance and the permission (role, policy document, policy, attachment and instance profile); here there is one line on the machine and one assignment per permission. In exchange, the scope is expressed through Azure's hierarchy instead of wildcards and conditions on an ARN, which is less fine-grained.
# The identity already exists: identity { type = "SystemAssigned" } on the VM/VMSS.
# Now it gets permissions.
resource "azurerm_role_assignment" "web_reads_images" {
# SCOPE: over what. Here, only this container. Not the whole account.
scope = azurerm_storage_container.images.resource_manager_id
# ROLE: what it can do. Built in by Azure.
role_definition_name = "Storage Blob Data Contributor"
# PRINCIPAL: who.
principal_id = azurerm_linux_virtual_machine_scale_set.web.identity[0].principal_id
}Three fields: scope, role and principal. That is the whole assignment. Compared with IAM:
| AWS IAM | Azure RBAC | |
|---|---|---|
| Where the permission is defined | A JSON policy you write | A role built in by Azure (over 400) or a custom one |
| Where it is attached | To the principal, or to the resource (bucket policy) | An assignment joining principal + role + scope |
| Scope granularity | An ARN with wildcards | Hierarchical: subscription → resource group → resource |
| Inheritance | None | Yes: a role on the subscription is inherited by everything inside |
| Denials | Effect: Deny in the policy |
Deny assignments, rarely used; not assigning is preferred |
| Propagation | Seconds | Up to 5 minutes, and a real cause of apply failures |
Inheritance is the most important practical difference and the most common trap: assigning Contributor over the subscription grants access to everything, forever, and it is what a lot of people do out of convenience. Least privilege in Azure translates to always assigning at the narrowest possible scope, which here is the container, not the storage account and certainly not the resource group.
The key vault, holding the PostgreSQL password:
resource "azurerm_key_vault" "main" {
name = substr(replace("${local.prefix}-kv-${var.suffix}", "_", "-"), 0, 24)
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "standard"
# Permission model: RBAC, not the legacy access policies.
enable_rbac_authorization = true
# Soft delete: it CANNOT be disabled since the 2021 release.
soft_delete_retention_days = var.environment == "prod" ? 90 : 7
# Purge protection: prevents permanent deletion. In prod, true.
purge_protection_enabled = var.environment == "prod"
network_acls {
default_action = "Deny"
bypass = "AzureServices"
virtual_network_subnet_ids = [azurerm_subnet.main["web"].id]
ip_rules = var.admin_ips
}
tags = local.tags
}
# Whoever runs Terraform needs permission to write secrets.
resource "azurerm_role_assignment" "terraform_writes_secrets" {
scope = azurerm_key_vault.main.id
role_definition_name = "Key Vault Secrets Officer"
principal_id = data.azurerm_client_config.current.object_id
}
resource "random_password" "db" {
length = 32
special = true
override_special = "!#$%&*()-_=+[]{}"
}
resource "azurerm_key_vault_secret" "db_password" {
name = "password-postgres"
value = random_password.db.result
key_vault_id = azurerm_key_vault.main.id
content_type = "text/plain"
expiration_date = timeadd(timestamp(), "8760h") # one year
tags = local.tags
# Without this, the first apply fails: the role assignment has not propagated yet.
depends_on = [azurerm_role_assignment.terraform_writes_secrets]
lifecycle {
ignore_changes = [expiration_date] # timestamp() changes on every plan
}
}
# And the machine can READ that secret, nothing more.
resource "azurerm_role_assignment" "web_reads_secrets" {
scope = azurerm_key_vault.main.id
role_definition_name = "Key Vault Secrets User" # read-only
principal_id = azurerm_linux_virtual_machine_scale_set.web.identity[0].principal_id
}The depends_on on the role assignment is necessary and still insufficient: RBAC propagation can take minutes, and an apply can fail with Forbidden even when the order is correct. It is the perfect example of the eventual consistency 05-01 talked about. If it happens reproducibly:
resource "time_sleep" "rbac_propagation" {
depends_on = [azurerm_role_assignment.terraform_writes_secrets]
create_duration = "60s"
}And always with a comment explaining why it exists, so the next person to read it does not delete it.
- Soft delete: the
destroy surprise
destroy surpriseThis section deserves one of its own because it is the Azure quirk that baffles people the most, and it shows up just when you think you have finished.
The key vault has mandatory soft delete that cannot be turned off. When you run terraform destroy:
- Terraform deletes the vault. The
destroysays it went fine. - Azure moves it into a "deleted but recoverable" state for 7 to 90 days.
- The name stays taken.
- The next day you apply the same configuration again and:
╷ │ Error: creating Key Vault: (Name "ecomarket-dev-kv-brave" / Resource Group │ "rg-ecomarket-dev"): keyvault.VaultsClient#CreateOrUpdate: Failure sending │ request: StatusCode=409 -- Original Error: Code="ConflictError" │ Message="Exist soft deleted vault with the same name." ╵
The three ways out:
# Option A (recommended in a lab): genuinely purge on destroy.
provider "azurerm" {
features {
key_vault {
purge_soft_delete_on_destroy = true
recover_soft_deleted_key_vaults = true
}
}
}# Option B: purge by hand whatever was left over from a previous run.
az keyvault list-deleted --query "[].{name:name, purge:properties.scheduledPurgeDate}" -o table
az keyvault purge --name ecomarket-dev-kv-brave --location westeurope# Option C: make sure the name is never repeated. The random suffix from module 4.
name = "${local.prefix}-kv-${random_pet.suffix.id}"In production, purge_soft_delete_on_destroy must be false and purge_protection_enabled must be true. Soft delete exists precisely so that an accidental destroy does not remove the keys that encrypt your data: without them, encrypted backups are unreadable forever. Turning it off in production turns a protection into a risk.
And it is not the only resource with this behaviour:
| Resource | Soft delete behaviour | Consequence |
|---|---|---|
| Key Vault | 7-90 days, cannot be disabled | The name stays taken. It costs ~$0 in the meantime |
| Secrets, keys and certificates inside it | They inherit the vault's | A secret recreated with the same name can fail |
| Blobs and containers | According to delete_retention_policy |
They keep occupying space and billing during retention |
| Storage account | It has no soft delete of its own | It is genuinely deleted |
| Resource group | It has none | It drags everything inside with it |
The third row is the one that costs money: blob versions and soft-deleted blobs bill until the policy expires. If you have uploaded 50 GB of test data, deleting it does not reduce the bill until the retention days have passed.
- Azure quirks that break expectations
A summary of everything that surprises arrivals from AWS, in a single reference table:
| Quirk | What happens | How to handle it |
|---|---|---|
| Globally unique names | Storage account, Key Vault and PostgreSQL server compete with all of Azure | A random suffix (random_pet), already in the design since module 4 |
| Strict format constraints | The storage account: 3-24 characters, lower case and digits only | replace() + substr(), and validate it with validation on the variable |
| RBAC propagation | Forbidden on a resource created right after assigning the role |
depends_on and, if it persists, a commented time_sleep |
| Soft delete | The name stays taken after a destroy |
purge_soft_delete_on_destroy in dev, a unique suffix always |
| The resource group drags everything | Deleting it removes what others created | prevent_destroy, azurerm_management_lock, and the provider option |
| Regional subnets | There is no subnet per zone: the zone is assigned to the resource | One subnet per function, not per zone |
| Delegated subnets | Nothing else can live in them | A subnet exclusively for PostgreSQL |
| Permissive default rules | All traffic within the virtual network is allowed | Explicit Deny rules between subnets |
features {} mandatory |
The init fails without it |
Always copy it, and configure the four options that matter |
| Quotas per region and per vCPU family | QuotaExceeded on a specific family even with total vCPUs to spare |
az vm list-usage before choosing a size; request an increase in advance |
version = "latest" on the image |
Replacements when a new image is published | ignore_changes or a pinned version |
| Orphaned disks | They outlive the VM if delete_os_disk_on_deletion = false |
Set it to true and hunt for orphans when cleaning up |
az and the provider can disagree about the subscription |
You apply in the wrong subscription | An explicit subscription_id and a check block |
The quota row deserves a note: Azure limits vCPUs per size family, not just in total. You can have 20 free vCPUs and still be unable to create a Standard_D2s_v3 because the DSv3 family is at zero in that region. The error message says so, but only if you read it in full.
- Cost of what was deployed and a guided
destroy
destroyA monthly estimate for an EcoMarket dev in westeurope. Indicative figures; verify with the official calculator.
| Resource | Approx. monthly cost | Free tier? |
|---|---|---|
| Resource group, virtual network, subnets, network security groups | $0 | Always free |
Service endpoints (service_endpoints) |
$0 | Always free |
| NAT gateway + public IP | ~$33 + ~$3.6 + data | No |
| Standard public IP (load balancer) | ~$3.6 | No |
| Standard Load Balancer | ~$18 + rules | No |
| Application Gateway v2 (if used) | ~$125-250 | No. Avoid it in practice |
Standard_B1s VM |
~$8 | Yes: 750 h/month, 12 months |
| 30 GB StandardSSD disk | ~$2.4 | Yes: 2 disks of 64 GB, 12 months |
PostgreSQL B_Standard_B1ms + 32 GB |
~$13-15 | Yes: 750 h/month, 12 months |
| Storage account (2 GB, LRS) | ~$0.04 | Yes: 5 GB, 12 months |
| Key Vault (secrets) | ~$0.03 ($0.03/10,000 operations) | Practically free |
| Azure Monitor logs | ~$2.3/GB ingested | 5 GB/month free |
dev TOTAL with NAT and load balancer |
~$55-75/month | |
dev TOTAL without NAT or load balancer |
~$1-3/month (with the free tier) |
The conclusion is identical to the AWS one, which is why it is worth underlining: Internet egress and load balancing are almost the entire cost. Key Vault, on the other hand, is ten times cheaper than AWS Secrets Manager ($0.03 per 10,000 operations versus $0.40 per secret per month).
The guided destroy:
# 1. See what is going to be destroyed
terraform plan -destroy -var-file=dev.tfvars -out=destroy.tfplan
terraform show destroy.tfplan | grep -c "will be destroyed"
# 2. Run it (8-20 min, dominated by PostgreSQL and the load balancer)
terraform apply destroy.tfplan
# 3. Check that the resource group is gone
az group exists --name rg-ecomarket-dev # should say false
# 4. THE IMPORTANT BIT: what survives
az keyvault list-deleted -o table # vaults in soft delete
az disk list --query "[?managedBy==null].{Name:name,GB:diskSizeGb}" -o table # orphaned disks
az network public-ip list --query "[?ipConfiguration==null].name" -o table # dangling IPs
az postgres flexible-server list -o table # servers that did not go
az storage account list --query "[].name" -o table
# 5. Purge the key vault if it was left in soft delete
az keyvault purge --name <name> --location westeuropeSurvives the destroy |
Why | Cost |
|---|---|---|
| Key Vault in soft delete | Mandatory, 7-90 days | ~$0, but it blocks the name |
| Orphaned managed disks | delete_os_disk_on_deletion = false |
~$2.4/month per 30 GB |
| Unassociated public IPs | Terraform deletes its own; ones created by hand survive | ~$3.6/month each |
| Blobs and versions in soft delete | delete_retention_policy |
The same as the original blob |
| Disk snapshots | Never managed if they were created by hand | ~$0.05/GB/month |
| PostgreSQL backups | Deleted with the server, except exported ones | Variable |
FinOps warning. The orphaned-disk check (
managedBy == null) is the most profitable one of all in Azure: it is the number one source of phantom spend in development subscriptions. Run it after every practice session and set up a budget in Cost Management with an alert at €10.
Common Mistakes and Tips
Forgetting the features {} block. The init fails with a clear message, but it gets forgotten constantly when copying old code. It is mandatory even when empty.
Not configuring purge_soft_delete_on_destroy in a lab. The day's second apply fails because the key vault's name is still taken. In dev, true; in prod, never.
Leaving delete_os_disk_on_deletion = false. Orphaned disks billing indefinitely. It is Azure's most common phantom spend.
Putting a virtual machine in PostgreSQL's delegated subnet. It fails with an explicit message. A delegated subnet is exclusive to its service.
Forgetting the private DNS zone or its link to the virtual network. The server exists, but the name does not resolve from the application. Same symptom as forgetting enable_dns_hostnames in AWS.
Choosing the wrong PostgreSQL access mode. Public with firewall rules and private with a virtual network are not interchangeable: switching from one to the other means recreating the server and migrating the data. Decide at the start.
Ticking "allow Azure services" in the database firewall. It opens the server to any Azure subscription on the planet, not just yours.
Assigning Contributor over the subscription "so that it works". It is inherited downwards and grants access to everything. Always assign at the narrowest scope: the container, not the account; the resource, not the group.
Not allowing for RBAC propagation. An apply that fails with Forbidden and works on retry is propagation, not a misconfigured permission. depends_on first; a commented time_sleep only if it persists.
Putting hyphens or capitals in the storage account name. 3-24 characters, lower case and digits. Validate it on the variable with validation so the error surfaces at plan.
Assuming a network security group's default rules deny. They allow all traffic within the virtual network. Segmentation requires explicit Deny rules.
Using Application Gateway in a practice environment. It costs between $125 and $250/month. For learning, Load Balancer or nothing.
Getting rule priority backwards. The lowest number wins. A Deny rule with priority 100 overrides an Allow with priority 200, however more specific the latter looks.
Tip: one resource group per environment. It simplifies the destroy, permission assignment, cost allocation and reasoning. And in prod, with a management lock.
Tip: enable Azure Policy for whatever is non-negotiable. Mandatory encryption, allowed locations, mandatory tags. It is the equivalent of AWS service control policies and it works even when somebody deploys from the portal. It connects with 07-04.
Tip: any change to role assignments, network rules or the database's access mode is reviewed with security; any hourly-cost resource, with FinOps. The resource group and the management lock are joint decisions of both.
Exercises
Exercise 1: EcoMarket's network on Azure (cost ~$0)
Deploy only the network, with no NAT and no load balancer:
- Write
versions.tfwithazurerm ~> 4.0andproviders.tfwithfeatures {}and an explicitsubscription_id. - Create the resource group
rg-ecomarket-devinwesteuropewith the common tags. - Create the
10.20.0.0/16virtual network and three subnets withfor_each:web,data(delegated to PostgreSQL Flexible Server) andgateway. - Add service endpoints for
Microsoft.StorageandMicrosoft.KeyVaulton thewebsubnet. - Create a network security group with two rules — allow 8080 from the gateway subnet at priority 100, deny SSH from
Internetat priority 200 — and associate it with thewebsubnet. - Add a
checkblock that verifies the subscription. - Apply, verify with
az network vnet subnet list, and destroy.
Note the timings and compare them with the equivalent AWS exercise.
Exercise 2: translating the data module from AWS to Azure
Without deploying, write the complete translation table for EcoMarket's data module, resource by resource, from the AWS code in 05-02:
- A table with three columns: AWS resource, equivalent Azure resource, and whether the equivalence is exact or partial, with a sentence explaining the difference when it is partial.
- For the images bucket, state how many resources were needed in AWS and how many in Azure, and what is gained or lost in each model.
- Identify three things that exist in the Azure version and have no equivalent at all in AWS.
- Identify two things from the AWS version that cannot be reproduced the same way in Azure and explain how you would solve them.
- Answer this: does the
datamodule's interface (itsvariables and itsoutputs) change when it is ported to Azure? Justify your answer.
Exercise 3: the soft delete lab
This exercise is cheap (a few cents) and teaches Azure's most baffling quirk:
- Create a resource group and a key vault with a fixed name (no random suffix) and
purge_soft_delete_on_destroy = false. - Add a secret with
azurerm_key_vault_secret. - Apply and verify the secret exists with
az keyvault secret show. - Run
terraform destroy. Check that it reports success. - Run
az keyvault list-deleted. What do you find? - Run
terraform applyagain with the same configuration. Copy the error. - Solve it in two different ways and explain which you would use in
devand which inprod. - Clean up completely and verify that
az keyvault list-deletedreturns nothing.
Solution 1
# versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
azurerm = { source = "hashicorp/azurerm", version = "~> 4.0" }
}
}
# providers.tf
provider "azurerm" {
features {}
subscription_id = var.subscription_id
}
data "azurerm_subscription" "current" {}
check "correct_subscription" {
assert {
condition = data.azurerm_subscription.current.subscription_id == var.subscription_id
error_message = "Active subscription: ${data.azurerm_subscription.current.display_name}. Check 'az account set'."
}
}# main.tf
locals {
prefix = "ecomarket-${var.environment}"
tags = {
Project = "ecomarket"
Environment = var.environment
ManagedBy = "terraform"
}
subnets = {
web = {
cidr = cidrsubnet(var.cidr, 8, 0)
delegation = null
services = ["Microsoft.Storage", "Microsoft.KeyVault"]
}
data = {
cidr = cidrsubnet(var.cidr, 8, 1)
delegation = "Microsoft.DBforPostgreSQL/flexibleServers"
services = []
}
gateway = {
cidr = cidrsubnet(var.cidr, 8, 2)
delegation = null
services = []
}
}
}
resource "azurerm_resource_group" "main" {
name = "rg-${local.prefix}"
location = var.location
tags = local.tags
}
resource "azurerm_virtual_network" "main" {
name = "${local.prefix}-vnet"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
address_space = [var.cidr]
tags = local.tags
}
resource "azurerm_subnet" "main" {
for_each = local.subnets
name = "${local.prefix}-snet-${each.key}"
resource_group_name = azurerm_resource_group.main.name
virtual_network_name = azurerm_virtual_network.main.name
address_prefixes = [each.value.cidr]
service_endpoints = each.value.services
dynamic "delegation" {
for_each = each.value.delegation != null ? [each.value.delegation] : []
content {
name = "delegation"
service_delegation {
name = delegation.value
actions = ["Microsoft.Network/virtualNetworks/subnets/join/action"]
}
}
}
}
resource "azurerm_network_security_group" "web" {
name = "${local.prefix}-nsg-web"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
tags = local.tags
}
resource "azurerm_network_security_rule" "allow_app" {
name = "allow-8080-from-gateway"
resource_group_name = azurerm_resource_group.main.name
network_security_group_name = azurerm_network_security_group.web.name
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_address_prefix = local.subnets.gateway.cidr
source_port_range = "*"
destination_address_prefix = local.subnets.web.cidr
destination_port_range = "8080"
}
resource "azurerm_network_security_rule" "deny_ssh" {
name = "deny-ssh-internet"
resource_group_name = azurerm_resource_group.main.name
network_security_group_name = azurerm_network_security_group.web.name
priority = 200
direction = "Inbound"
access = "Deny"
protocol = "Tcp"
source_address_prefix = "Internet"
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "22"
}
resource "azurerm_subnet_network_security_group_association" "web" {
subnet_id = azurerm_subnet.main["web"].id
network_security_group_id = azurerm_network_security_group.web.id
}Verification and cleanup:
terraform init && terraform apply -auto-approve
az network vnet subnet list \
--resource-group rg-ecomarket-dev \
--vnet-name ecomarket-dev-vnet \
--query "[].{Name:name, CIDR:addressPrefix, Delegation:delegations[0].serviceName}" -o table
terraform destroy -auto-approve
az group exists --name rg-ecomarket-dev # falseExpected timings: apply between 60 and 120 seconds (the resource group and the virtual network are quick; the associations add a few seconds); destroy between 90 and 180 seconds. It is somewhat slower than the AWS equivalent, which was around 30-60 seconds, mainly because Azure creates the resource group first and the associations are separate resources. Cost: $0.
Solution 2
1. Translation table for the data module:
| AWS resource | Azure resource | Exact? |
|---|---|---|
aws_db_subnet_group |
(does not exist) | No: replaced by delegated_subnet_id directly on the server. Azure has no concept of a subnet group |
aws_db_instance |
azurerm_postgresql_flexible_server |
Partial: the logical database is a separate resource in Azure |
(included in db_name) |
azurerm_postgresql_flexible_server_database |
No: in AWS it is an attribute; in Azure, a resource |
aws_db_parameter_group |
azurerm_postgresql_flexible_server_configuration |
Partial: in Azure there is one resource per parameter, not a group |
| (implicit in the VPC) | azurerm_private_dns_zone + _virtual_network_link |
No: AWS resolves with enable_dns_hostnames; Azure requires two explicit resources |
aws_security_group + rules |
azurerm_network_security_group + rules |
Partial: Azure has priorities and Deny rules |
aws_s3_bucket |
azurerm_storage_account + azurerm_storage_container |
No: two levels versus one |
aws_s3_bucket_versioning |
blob_properties { versioning_enabled } |
Partial: in Azure it is a block, not a resource |
aws_s3_bucket_server_side_encryption_configuration |
(implicit) | No: Azure always encrypts by default; only the customer-managed key is configured |
aws_s3_bucket_public_access_block |
allow_nested_items_to_be_public = false + network_rules |
Partial: an attribute versus a resource |
aws_s3_bucket_lifecycle_configuration |
azurerm_storage_management_policy |
Yes |
aws_s3_bucket_policy |
network_rules + role assignments |
No: Azure has no JSON resource policies; it uses RBAC and network rules |
aws_secretsmanager_secret + _version |
azurerm_key_vault + azurerm_key_vault_secret |
Partial: Key Vault is the container and the secret goes inside it; it has mandatory soft delete |
2. Resource counts for the images storage:
- AWS: seven resources (
aws_s3_bucket,_public_access_block,_versioning,_server_side_encryption_configuration,_ownership_controls,_lifecycle_configuration,_policy). - Azure: three resources (
azurerm_storage_accountwith nested blocks,azurerm_storage_container,azurerm_storage_management_policy).
What Azure gains: fewer resources and a more compact configuration. What it loses: two teams cannot manage different aspects of the same storage account without treading on each other, which is exactly the problem the AWS provider solved by splitting out the satellite resources in version 4. AWS's model is more verbose and better for large organisations; Azure's is more convenient for a single team.
3. Three things that exist in Azure and not in AWS:
- The resource group: mandatory, drags everything along when deleted, and is the natural scope for permissions and costs.
- The explicit private DNS zone with its virtual network link: in AWS it is a boolean attribute on the VPC.
- Subnet delegation: handing a subnet over to a managed service, which has no analogue in AWS (RDS simply uses the group's subnets).
To which a fourth could be added: the key vault's mandatory soft delete, which has no equivalent in Secrets Manager (there it is configurable and can be set to zero).
4. Two things from AWS that cannot be reproduced the same way:
- The JSON bucket policy (
aws_s3_bucket_policydenying non-TLS traffic). Azure has no equivalent resource policies. It is solved withhttps_traffic_only_enabled = trueandmin_tls_version = "TLS1_2"on the account, which achieve the same effect by another route, plusnetwork_rulesto restrict the source. - The
s3:prefixcondition that limited listing to one prefix. In Azure, the narrowest RBAC scope is the container, not a prefix inside it. It is solved by creating one container per use case (images,invoices,exports) instead of prefixes inside a single one. That is a design change, not a translation.
5. Does the module's interface change? Almost not at all, and that is the lesson. The variables base_name, suffix, retention_days, high_availability, protect_deletion, db_password and tags all still apply. So do the outputs endpoint, bucket_id (renameable to container_id) and secret_arn (renameable to secret_id).
Three things change: resource_group_name and location appear as new variables — the resource group has no equivalent and has to be passed in — subnets (a map of zone to identifier) becomes a single delegated subnet_id because subnets are regional, and db_class changes its values (db.t3.micro → B_Standard_B1ms), which is why sizing values must live in var.environments and not inside the module. The module's shape survives the change of cloud; its concrete values do not. That is exactly what 04-02 predicted.
Solution 3
Points 1-3: configuration with a fixed name and purging disabled:
provider "azurerm" {
features {
key_vault {
purge_soft_delete_on_destroy = false # ← on purpose, to see the problem
recover_soft_deleted_key_vaults = false
}
}
subscription_id = var.subscription_id
}
data "azurerm_client_config" "current" {}
resource "azurerm_resource_group" "lab" {
name = "rg-ecomarket-lab-kv"
location = "westeurope"
}
resource "azurerm_key_vault" "lab" {
name = "ecomarket-lab-kv-01" # FIXED, no suffix
resource_group_name = azurerm_resource_group.lab.name
location = azurerm_resource_group.lab.location
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "standard"
enable_rbac_authorization = true
soft_delete_retention_days = 7
purge_protection_enabled = false
}
resource "azurerm_role_assignment" "me" {
scope = azurerm_key_vault.lab.id
role_definition_name = "Key Vault Secrets Officer"
principal_id = data.azurerm_client_config.current.object_id
}
resource "azurerm_key_vault_secret" "test" {
name = "password-test"
value = "test-value-not-real"
key_vault_id = azurerm_key_vault.lab.id
depends_on = [azurerm_role_assignment.me]
}terraform apply -auto-approve
az keyvault secret show --vault-name ecomarket-lab-kv-01 --name password-test --query value -o tsvPoints 4-5: after terraform destroy, the state is empty and Terraform reports success. But:
Name Purge --------------------- -------------------------- ecomarket-lab-kv-01 2026-09-29T10:14:22+00:00
The vault exists in a deleted-but-recoverable state for 7 days, and its name is still reserved across all of Azure.
Point 6: the apply fails again with:
╷ │ Error: creating Key Vault "ecomarket-lab-kv-01" (Resource Group "rg-ecomarket-lab-kv"): │ StatusCode=409 -- Code="ConflictError" Message="Exist soft deleted vault with the same name." ╵
Point 7: two solutions.
Solution A — purge and recover automatically (for dev):
provider "azurerm" {
features {
key_vault {
purge_soft_delete_on_destroy = true # genuinely purges on destroy
recover_soft_deleted_key_vaults = true # recovers instead of failing
}
}
}Solution B — an unrepeatable name (valid in any environment):
resource "random_pet" "suffix" {
length = 2
}
resource "azurerm_key_vault" "lab" {
name = substr("ecomarket-lab-kv-${random_pet.suffix.id}", 0, 24)
# ...
}Which to use where. In dev, both: A so you can iterate without friction, B because EcoMarket has been carrying the suffix since module 4 and it eliminates the whole class of problem. In prod, only B, and additionally:
soft_delete_retention_days = 90
purge_protection_enabled = true # prevents purging even by an administratorThe reason matters and is worth understanding fully: in production, soft delete and purge protection are a safeguard, not an inconvenience. If an accidental destroy removes the vault holding the keys that encrypted the disks and the backups, those backups become unreadable forever. With purge_protection_enabled = true, not even an administrator can remove them within the retention window. Setting purge_soft_delete_on_destroy = true in production turns a protection designed to save you into a mechanism that executes the irreversible loss without asking.
Point 8: complete cleanup.
terraform destroy -auto-approve
az keyvault purge --name ecomarket-lab-kv-01 --location westeurope
az keyvault list-deleted -o table # should be empty
az group exists --name rg-ecomarket-lab-kv # falseTotal cost of the exercise: a few cents. The key vault has no fixed cost (only per operation) and the resource group is free.
Conclusion
EcoMarket runs on Azure with the same architecture as on AWS, and the exercise has demonstrated what matters: the course's modules survive a change of cloud in their shape, not in their values.
- The equivalence map covers most of it — subscription for account, virtual network for VPC, scale set for auto scaling group, Flexible Server for RDS — and the real differences are few but deep.
- The resource group does not exist in AWS and reorganises the entire codebase: every resource carries
resource_group_nameandlocation, it is the natural scope for permissions and costs, and deleting it drags along everything it contains, including what Terraform knows nothing about. Inprod,prevent_destroyplusazurerm_management_lock. - The
features {}block is mandatory even when empty, and its four important options decide whether thedestroyworks, whether it leaves orphaned disks and whether the key vault's name stays blocked. - Subnets are regional, not zonal. You create one subnet per function, not per zone, and the zone is assigned to the compute resource. The pleasant consequence: a single NAT gateway covers every zone, versus one per zone in AWS.
- Delegated subnets are exclusive to their service: PostgreSQL Flexible Server with private networking requires an empty, delegated subnet, plus a private DNS zone linked to the virtual network and a
depends_onthat no reference implies. - Network security groups have priorities and
Denyrules, and their default rules allow all traffic within the virtual network. Segmentation is opt-in, the reverse of AWS. - RBAC is not IAM: three fields — scope, built-in role and principal — with downward inheritance, propagation of up to five minutes and no JSON to write. Managed identity replaces role plus instance profile in a single line.
- Storage has two levels: account (global name, 3-24 characters, lower case and digits only) and container. The narrowest permission scope is the container, so AWS's prefix-based segmentation translates into several containers.
- The five replication levels (LRS, ZRS, GRS, GZRS and the read-access variants) are the most frequent resilience decision, with the practical rule: if losing the data means asking a human for it again, do not use LRS.
- Soft delete is the
destroysurprise. The key vault is left recoverable and its name reserved; deleted blobs keep billing through the retention period. Indev, automatic purging and a random suffix; inprod, purge protection enabled, because losing the keys means losing the backups. - Cost follows the same pattern as in AWS: the network is free, and Internet egress plus load balancing are almost the entire bill. Application Gateway, at $125-250/month, is ten times an AWS application load balancer and has no place in a lab.
- What survives the
destroyis orphaned disks (Azure's number one phantom spend), dangling public IPs, vaults in soft delete and blobs in retention. ThemanagedBy == nullcheck on disks is the most profitable thing you can automate.
One cloud remains, and it is the one that departs furthest from the mental model you are carrying. In Provisioning GCP Resources, EcoMarket is deployed on Google Cloud, where the fundamental unit is neither the account nor the subscription but the project; where the virtual network is global and the subnets regional — a conceptual difference that changes the design of a multi-region platform; where firewall rules live on the network and apply by tag rather than by group; where you have to enable each API before you can use it, with the classic error that causes; and where a global HTTP(S) load balancer is five chained resources instead of three, for reasons that become very clear once you understand what each one does.
