Showing posts with label CloudComputing. Show all posts
Showing posts with label CloudComputing. Show all posts

Sunday, July 12, 2026

Azure Managed Identity: From Beginner to Advanced

Azure Managed Identity: From Beginner to Advanced

Managing secrets is one of the most painful parts of building cloud applications. Connection strings in config files, client secrets that expire at 2 AM, certificates someone forgot to renew — we have all been there. Azure Managed Identity solves this problem by removing credentials from your code entirely.

This post takes you from the basics all the way to production best practices, with everything verified against the latest Microsoft Learn documentation.


Part 1: The Basics (Beginner)

What is a Managed Identity?

A managed identity is an automatically managed identity in Microsoft Entra ID that Azure resources can use to authenticate to any service that supports Microsoft Entra authentication — without you storing any credentials in code, config, or Key Vault.

Key points:

  • Azure creates and manages the credentials behind the scenes. You never see them, rotate them, or store them.
  • Managed identities are free — there is no extra cost with Microsoft Entra ID.
  • The feature was formerly called Managed Service Identity (MSI) — you will still see "MSI" in older docs, blogs, and even some parameter names.

The Two Types

Property System-assigned User-assigned
Creation Created as part of an Azure resource (VM, App Service, Function App, etc.) Created as a standalone Azure resource
Lifecycle Tied to the parent resource — deleted when the resource is deleted Independent — must be explicitly deleted
Sharing Cannot be shared; belongs to exactly one resource Can be assigned to multiple resources
Common use cases Workloads contained in a single resource that need an independent identity Workloads spanning multiple resources; pre-authorization scenarios; resources that get recycled frequently but need consistent permissions

Microsoft's current recommendation: User-assigned managed identities are the recommended type for most scenarios, because they can be provisioned independently of compute, pre-authorized before deployment, and shared across resources.

Three Core Concepts

Every managed identity is backed by a special service principal in Microsoft Entra ID. Three IDs matter:

  1. Client ID — a unique identifier tied to the identity's application registration. Used when your code needs to pick a specific user-assigned identity.
  2. Principal ID (Object ID) — the object ID of the service principal. Used when assigning RBAC roles.
  3. Service Principal — the Entra ID object that represents the identity in your tenant.

How Authentication Works (The Mental Model)

  1. You enable a managed identity on a resource (say, a VM).
  2. Azure creates a service principal in your Entra tenant.
  3. You grant that identity an RBAC role on a target resource (e.g., Storage Blob Data Reader on a storage account).
  4. Your code asks a local, non-routable endpoint for a token — no secrets involved.
  5. Azure returns a Microsoft Entra access token (JWT).
  6. Your code presents that token to the target service.

The magic is in step 4: the token endpoint is only reachable from inside the resource itself.


Part 2: Hands-On (Getting Started)

Enable a System-Assigned Identity

Azure portal: Resource → Identity blade → System assigned tab → set Status to On → Save.

Azure CLI:

# On a VM
az vm identity assign --name MyVM --resource-group MyRG

# On a Web App
az webapp identity assign --name MyWebApp --resource-group MyRG

PowerShell:

# On a VM
$vm = Get-AzVM -ResourceGroupName "MyRG" -Name "MyVM"
Update-AzVM -ResourceGroupName "MyRG" -VM $vm -IdentityType SystemAssigned

Create and Assign a User-Assigned Identity

# 1. Create the identity
az identity create --name MyUAMI --resource-group MyRG

# 2. Assign it to a VM
az vm identity assign --name MyVM --resource-group MyRG \
  --identities /subscriptions/<sub-id>/resourcegroups/MyRG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/MyUAMI

Grant Permissions with RBAC

The identity is useless until it has permissions. Assign a role scoped as narrowly as possible:

az role assignment create \
  --assignee <principal-id-of-managed-identity> \
  --role "Storage Blob Data Reader" \
  --scope /subscriptions/<sub-id>/resourceGroups/MyRG/providers/Microsoft.Storage/storageAccounts/mystorageacct

See It Work: Request a Token Manually

From inside an Azure VM, call the Azure Instance Metadata Service (IMDS) endpoint:

curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' \
  -H "Metadata: true" -s

What each piece means:

  • 169.254.169.254 — the IMDS endpoint, a well-known non-routable IP reachable only from inside the VM.
  • api-version=2018-02-01 — use this version or later.
  • resource — the audience of the token (here, Azure Resource Manager). Note the trailing slash — the value must exactly match what Entra ID expects.
  • Metadata: true header — mandatory; it mitigates server-side request forgery (SSRF) attacks.

If the VM has multiple user-assigned identities, add client_id=<client-id> (or object_id / msi_res_id) to specify which identity to use.


Part 3: Using Managed Identity in Code (Intermediate)

You should almost never call IMDS directly in real applications. Use the Azure Identity client library instead — it handles endpoint discovery, caching, and retries across all Azure hosting environments (VM, App Service, Functions, AKS, Container Apps, Arc).

C# (.NET)

using Azure.Identity;
using Azure.Storage.Blobs;

// System-assigned identity
var credential = new ManagedIdentityCredential();

// User-assigned identity (specify the client ID)
var uamiCredential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<client-id>"));

var blobClient = new BlobServiceClient(
    new Uri("https://<storage-account>.blob.core.windows.net"),
    credential);

Python

from azure.identity import ManagedIdentityCredential
from azure.storage.blob import BlobServiceClient

# System-assigned
credential = ManagedIdentityCredential()

# User-assigned
credential = ManagedIdentityCredential(client_id="<client-id>")

blob_client = BlobServiceClient(
    account_url="https://<storage-account>.blob.core.windows.net",
    credential=credential
)

PowerShell (e.g., in Azure Automation or an Azure VM)

# Connect to Azure using the managed identity
Connect-AzAccount -Identity

# Connect using a specific user-assigned identity
Connect-AzAccount -Identity -AccountId "<client-id>"

# Get a token for a specific resource
$token = Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com"

DefaultAzureCredential: Convenient, But Know the Trade-offs

DefaultAzureCredential tries a chain of authentication methods and picks whichever works at runtime. Locally it uses your Visual Studio / Azure CLI / Azure PowerShell login; in Azure it discovers the managed identity — no code changes between environments.

var credential = new DefaultAzureCredential(); // great for getting started

This is fantastic for the dev inner loop, but it has real production drawbacks (covered in Part 5).


Part 4: Advanced Scenarios

The Token Endpoint Varies by Host

Different Azure services expose the managed identity endpoint differently — another reason to use the SDK rather than raw HTTP:

Host Endpoint
Azure VMs, VM Scale Sets, AKS/ACI containers http://169.254.169.254/metadata/identity/oauth2/token (IMDS)
App Service / Functions / Container Apps IDENTITY_ENDPOINT + IDENTITY_HEADER environment variables
Azure Arc-enabled servers http://localhost:40342/metadata/identity/oauth2/token (Hybrid IMDS), with an extra challenge-token step
Service Fabric IDENTITY_ENDPOINT + IDENTITY_HEADER + IDENTITY_SERVER_THUMBPRINT

Azure Arc: Managed Identity Beyond Azure

Arc-enabled servers (on-premises or other clouds) get a managed identity too, via the Hybrid Instance Metadata Service (HIMDS). The token flow is multi-step: request a challenge token file (readable only by privileged users), then exchange it for the access token. This design ensures only higher-privileged processes on the machine can obtain tokens.

AKS: Workload Identity, Not Pod IMDS Access

On AKS, cluster-level managed identities cover the cluster-to-Azure scenario (the control plane and kubelet acting on Azure). For pod-to-Azure authentication, the modern approach is Microsoft Entra Workload ID — pods get short-lived federated tokens instead of hitting IMDS.

Related hardening: AKS now supports blocking pod access to IMDS for non-host-network pods (preview). Once enabled, pods can no longer grab node-level managed identity tokens — a real security win, since any pod reaching IMDS could otherwise obtain tokens for the node's identity.

Managed Identity as a Federated Identity Credential (Cross-Tenant)

Managed identities only work within the tenant that hosts the subscription. For cross-tenant access, configure the managed identity as a federated identity credential (FIC) on an Entra app registration. Your workload uses its managed identity token as proof to acquire tokens as the multi-tenant app — completely certificateless. Microsoft.Identity.Web calls this pattern "certificateless credentials" and recommends it as the best option for production workloads on Azure.

Token Caching

The managed identity subsystem caches tokens at the platform level, and the Azure Identity SDKs cache in-memory via MSAL. Still:

  • Reuse credential instances across clients. High-volume apps that create new credentials per request can hit HTTP 429 throttling from Entra ID.
  • Handle the case where a target service rejects a token as expired.

Important Boundaries to Remember

  • Managed identities are tenant-specific. Moving a subscription to another directory means recreating and reconfiguring identities.
  • A resource can have one system-assigned identity but multiple user-assigned identities.
  • When you switch an existing resource's identity type (e.g., system-assigned → user-assigned on AKS), components keep using the old identity until its token expires — the switchover can take hours.

Part 5: Production Best Practices

This is where the "it works on my machine" story becomes "it works reliably at 3 AM."

1. Prefer User-Assigned Identities

Microsoft's guidance is clear: user-assigned identities are more efficient in a broader range of scenarios.

  • Identities and role assignments can be created before the resources that use them, so infrastructure deployments do not fail because the deployer lacks role-assignment rights.
  • One identity can serve many resources — fewer identities and role assignments to govern.
  • Lifecycle is decoupled: recycle compute freely without losing permissions.

Use system-assigned only when a resource genuinely needs its own unique identity that should die with it.

2. Use Deterministic Credentials in Production

DefaultAzureCredential is great for development but risky in production:

  • Unpredictable behavior: the chain checks environment variables and installed tools; someone running az login on a production VM can silently change which credential your app uses — potentially elevating or reducing privileges.
  • Debugging pain: when auth fails, you must dig through logs to find which credential in the chain failed.
  • Performance overhead: sequentially trying credentials adds latency.
  • Permission mismatches: the first credential that gets a token wins, even if it has the wrong permissions.

Production pattern — pick the credential explicitly:

TokenCredential credential = builder.Environment.IsProduction()
    ? new ManagedIdentityCredential(ManagedIdentityId.FromUserAssignedClientId(clientId))
    : new DefaultAzureCredential();

3. Understand the Retry Strategy

The Azure Identity library behaves differently depending on how you use managed identity:

  • Fail-fast mode (default DefaultAzureCredential behavior): no retries on token failure. Good for the dev loop, bad for production.
  • Resilient mode: up to five retries with exponential backoff starting at 0.8 seconds. Activated by using ManagedIdentityCredential directly, using ChainedTokenCredential containing it, or setting AZURE_TOKEN_CREDENTIALS=ManagedIdentityCredential (requires Azure.Identity 1.16.0+ for the environment-variable approach).

One more reason to use ManagedIdentityCredential directly in production.

4. Apply Least Privilege — Ruthlessly

  • Grant the narrowest role at the narrowest scope (resource > resource group > subscription).
  • Prefer data-plane roles (e.g., Storage Blob Data Reader) over broad control-plane roles like Contributor.
  • Audit role assignments regularly and revoke what is unused.

5. Separate Identities per Environment

Use different managed identities for dev, staging, and production. If an identity is ever compromised or misconfigured, the blast radius stays contained to one environment.

6. Monitor and Audit

  • Managed identity CRUD operations show up in Azure Activity logs.
  • Sign-in activity appears in Microsoft Entra sign-in logs — filter by service principal sign-ins to watch your identities in action.
  • Enable SDK diagnostic logging to catch credential-chain issues early.
  • Document which permissions each identity has and why.

7. Reuse Credential Instances

Create one credential object per application and share it across all SDK clients. This maximizes the MSAL token cache and avoids Entra ID throttling.

8. Eliminate the Last Secrets

A production maturity checklist:

  • [ ] No connection strings with keys — use Entra auth for Storage, SQL, Service Bus, Cosmos DB, etc.
  • [ ] No client secrets in app registrations for Azure-hosted workloads — use managed identity + federated identity credentials instead.
  • [ ] Key Vault accessed via managed identity (RBAC), not access policies with secrets.
  • [ ] CI/CD pipelines using OIDC / workload identity federation instead of service principal secrets.
  • [ ] AKS pods using Workload ID; IMDS restriction enabled where possible.

Quick Troubleshooting Guide

Symptom Likely cause Fix
400 Bad Request from IMDS with multiple identities Multiple user-assigned identities but no client_id specified Pass client_id, object_id, or msi_res_id
Token acquired but target service returns 403 RBAC role missing, wrong scope, or role propagation delay Verify role assignment; allow a few minutes for propagation
Auth works locally, fails in Azure Local credential (CLI/VS) has broader permissions than the managed identity Grant the managed identity the required role; use deterministic credentials
Old permissions still in effect after role change Platform/SDK token cache Tokens reflect changes only after refresh — wait for expiry or restart
DefaultAzureCredential slow or flaky in production Chain probing + fail-fast mode Switch to ManagedIdentityCredential directly

Wrap-Up

Managed identity is one of those rare features that improves security and reduces operational work at the same time. The learning curve is short:

  1. Beginner: enable an identity, assign a role, watch a token flow.
  2. Intermediate: wire up the Azure Identity SDK, understand system vs. user-assigned.
  3. Advanced: federated credentials, Arc/HIMDS, AKS workload identity, cross-tenant patterns.
  4. Production: user-assigned by default, deterministic credentials, least privilege, per-environment identities, monitoring.

If your Azure workloads still hold a client secret or storage key anywhere, that is your next refactoring target.


References (Microsoft Learn)


Sunday, May 17, 2026

Microsoft Azure Solutions Architect Expert (AZ-305) Complete Guide

Microsoft Azure Solutions Architect Expert (AZ-305) — Complete Guide

Well-Architected Framework · Identity & Governance · Data Storage · Infrastructure · Business Continuity · Landing Zones · Scenarios · Cheat Sheet

Top Hashtags: #AZ305, #AzureSolutionsArchitect, #MicrosoftAzure, #CloudArchitecture, #AzureArchitect, #WellArchitectedFramework, #CloudAdoptionFramework, #AzureDesign, #MicrosoftCertified, #CloudComputing


Table of Contents

  1. Exam Overview & Architect Mindset
  2. Design Identity, Governance & Monitoring (25–30%)
  3. Design Data Storage Solutions (25–30%)
  4. Design Infrastructure Solutions (30–35%)
  5. Design Business Continuity Solutions (10–15%)
  6. Azure Well-Architected Framework & Landing Zones
  7. Scenario-Based Questions
  8. Cheat Sheet — Quick Reference

1. Exam Overview & Architect Mindset

AZ-305 Exam at a Glance

The AZ-305 exam validates expertise in designing cloud and hybrid solutions — translating business requirements into Azure architectures aligned with the Well-Architected Framework and Cloud Adoption Framework. This is a design exam, not a configuration exam.

Skill Domain Exam Weight
Design infrastructure solutions 30–35% ← LARGEST
Design identity, governance, and monitoring solutions 25–30%
Design data storage solutions 25–30%
Design business continuity solutions 10–15%

Prerequisite: AZ-104 (Azure Administrator Associate) must be held before earning AZ-305 Expert certification.

Critical mindset shift: AZ-305 questions present a business scenario with stated requirements and ask you to recommend, evaluate, or compare Azure services. The key skill is understanding WHY one service fits a scenario better than another — not just knowing what each service does.


What is the Azure Well-Architected Framework?

The Azure Well-Architected Framework (WAF) is Microsoft's set of guiding principles for building high-quality cloud solutions. Every AZ-305 design decision should be justified using WAF pillars.

Five WAF Pillars:

1. Reliability:
→ Design for failure — assume components will fail
→ Use redundancy: Availability Zones, geo-replication, multi-region
→ Define and meet RTO (Recovery Time Objective) and RPO (Recovery Point Objective)
→ Health monitoring, automatic failover, circuit breakers
→ Example: deploy SQL Database with zone-redundant Business Critical tier
             + auto-failover group to paired region

2. Security:
→ Defence in depth: multiple layers of security
→ Principle of least privilege: minimum permissions needed
→ Zero Trust: verify explicitly, assume breach, limit blast radius
→ Encrypt data at rest and in transit; manage secrets in Key Vault
→ Example: Private Endpoints for PaaS, WAF on Application Gateway,
             Managed Identity instead of service accounts

3. Cost Optimisation:
→ Right-size resources — don't over-provision
→ Match consumption to business value (pay for what you use)
→ Reserved Instances for predictable workloads
→ Use PaaS over IaaS where possible (lower management overhead)
→ Azure Hybrid Benefit for existing licences

4. Operational Excellence:
→ Infrastructure as Code (Bicep/Terraform) — repeatable, version-controlled
→ CI/CD pipelines for deployment automation
→ Monitoring: Azure Monitor, Log Analytics, Application Insights
→ Runbooks and automated remediation
→ Change management: blue-green deployments, feature flags

5. Performance Efficiency:
→ Scale horizontally (add instances) not just vertically (bigger VM)
→ Cache frequently accessed data (Azure Cache for Redis)
→ CDN for static content delivery (Azure Front Door / CDN)
→ Choose the right service tier for the workload profile
→ Autoscaling: VMSS, App Service autoscale, AKS cluster autoscaler

What is the Cloud Adoption Framework (CAF)?

Cloud Adoption Framework (CAF):
→ Microsoft's guidance for adopting Azure at enterprise scale
→ Covers: strategy, planning, landing zones, governance, operations

CAF phases:
Strategy:    define business justification, expected outcomes
Plan:        assess current state, create migration backlog
Ready:       set up landing zones, management groups hierarchy
Adopt:       migrate or modernise workloads (lift-and-shift, re-architecture)
Govern:      establish guardrails — Azure Policy, cost management, security baseline
Manage:      operations baseline — monitoring, backup, disaster recovery
Innovate:    build cloud-native solutions, AI/ML, data analytics

Azure Landing Zone:
→ Preconfigured, governance-ready Azure environment for enterprise adoption
→ Includes: management group hierarchy, Azure Policy assignments, networking,
            identity, security baseline, monitoring
→ Conceptual architecture: Platform vs Application landing zones
→ Platform: connectivity hub, identity, management subscriptions (managed by central IT)
→ Application: individual workload subscriptions (managed by application teams)
→ Accelerator: Bicep/Terraform modules to deploy landing zone in hours

Management Group hierarchy (CAF-recommended):
Tenant Root Group
  ├── Platform (managed by central IT)
  │     ├── Management (Log Analytics, Automation)
  │     ├── Identity (AD DS, Entra Connect)
  │     └── Connectivity (hub VNet, VPN/ExpressRoute, Firewall)
  └── Landing Zones (workload teams)
        ├── Corp (connected to hub, private)
        └── Online (internet-facing, DMZ)

2. Design Identity, Governance & Monitoring (25–30%)

How do you design an identity architecture for a hybrid enterprise?

Hybrid identity decision tree:

Question 1: Do you have on-premises Active Directory?
No:  → Cloud-only Entra ID. Use Entra ID Joined devices. Done.
Yes: → Need Entra Connect for identity synchronisation

Question 2: Authentication method for synchronised identities?
Password Hash Sync (PHS): → RECOMMENDED for most orgs
  Pros: works if on-prem unavailable, leaked credential detection,
        seamless SSO with seamless SSO extension
  Cons: password hash in cloud (some orgs have policy against this)

Pass-Through Auth (PTA): → when policy prohibits cloud password hashes
  Pros: passwords never leave on-prem, real-time account state
  Cons: requires on-prem PTA agent availability, no leaked cred detection

Federation (AD FS): → only when advanced requirements (smart cards,
                       complex claims transformation)
  Pros: full control over authentication claims
  Cons: complex, expensive infrastructure, Microsoft recommends migrating away

Question 3: Device management?
Cloud-native devices:  → Entra ID Joined + Intune (MDM)
Existing domain:       → Hybrid Entra ID Joined (domain join + Entra registration)
BYOD:                  → Entra ID Registered + MAM (App Protection Policies)

Identity architecture for a 10,000-person hybrid enterprise:
→ Entra Connect with PHS + Seamless SSO
→ All admin roles in PIM (eligible assignments, not permanent)
→ Break-glass accounts: 2 cloud-only Global Admins, excluded from all CA
→ Conditional Access: MFA all users, block legacy auth, require compliant device
→ Identity Protection: sign-in risk ≥ Medium → MFA, user risk High → password reset
→ Named locations: corporate IP ranges for trusted sign-in signals
→ B2B: Entitlement Management for partner access, time-limited, self-service
→ Entra ID P2 required for PIM, Identity Protection risk policies, Access Reviews

How do you design a governance architecture at scale?

Governance architecture layers:

Layer 1 — Management Group hierarchy:
Root → Decommissioned MG | Platform MG | Landing Zones MG | Sandbox MG
→ Azure Policy applied at MG level inherits to all child subscriptions
→ RBAC applied at MG level inherits to all child subscriptions

Layer 2 — Azure Policy:
Initiative: "CIS Azure Benchmark" or custom baseline
Key policies:
  Deny:  "No public IP on VMs" (enforces private-only VMs)
  Deny:  "Allowed locations: UK South, UK West" (data residency)
  Deny:  "Allowed VM SKUs" (prevent large SKUs in dev)
  Audit: "Storage accounts should use private endpoints"
  DINE:  "Deploy Azure Monitor Agent if missing" (auto-remediate)

Layer 3 — Azure Blueprints (or Bicep/Terraform for landing zones):
→ Combine: role assignments + policy assignments + ARM templates
→ Assign to subscriptions for consistent baseline deployment
→ Note: Bicep + Azure DevOps is now preferred over Blueprints for new designs

Layer 4 — RBAC design:
Management Group → Owner (cloud platform team only — use PIM)
Subscription → Contributor (workload team — via PIM)
Resource Group → Contributor/specific roles (workload developers)
Resources → Reader/specific data roles (application service principals)

Layer 5 — Tagging strategy:
Mandatory tags enforced by Azure Policy:
  Environment: Production | Development | Test
  Owner:        team or product owner email
  CostCentre:   cost allocation code
  Application:  application name/ID
  DataClass:    Public | Internal | Confidential | Restricted
Cost Management: filter by tag to see per-team, per-app spending

Layer 6 — Subscription design:
Option A: One subscription per environment (simplest)
  Prod-Sub | Dev-Sub | Test-Sub
Option B: One subscription per workload (better isolation)
  Sales-Prod | HR-Prod | Finance-Prod (separate blast radius, billing)
Option C: Hybrid (recommended for large orgs)
  Platform subs (connectivity, identity, management) + Workload subs

How do you design a monitoring solution for Azure?

Monitoring architecture:
→ Centralised Log Analytics workspace (one per environment or per org)
→ All resources send diagnostic logs and metrics to central workspace
→ Azure Monitor alerts trigger action groups (email, Teams, PagerDuty)

Data sources and collection:
Activity Log:        subscription-level control plane operations (all subs → workspace)
Resource Diagnostics: service-level logs (SQL queries, App Gateway access, Key Vault ops)
VM Guest OS:          Azure Monitor Agent + Data Collection Rules → workspace
Application:          Application Insights SDK → telemetry (requests, exceptions, dependencies)
Container:            Container Insights → AKS node + pod metrics to workspace
Security:             Microsoft Defender for Cloud → security findings to workspace
Network:              Network Watcher → flow logs, connection monitor

Application Insights:
→ APM (Application Performance Monitoring) for web applications
→ Instrumentation: add SDK or use auto-instrumentation (App Service, AKS)
→ Telemetry: requests, exceptions, dependencies (SQL, HTTP calls), custom events
→ Live Metrics: real-time monitoring during deployment
→ Availability tests: ping test every 5 minutes from multiple Azure regions
→ Smart detection: ML-based anomaly detection (failure rate spikes, performance degradation)

Azure Monitor Alerts:
Metric alerts:   trigger on: CPU > 80%, DTU > 90%, response time > 2s
Log alerts (KQL): trigger on: error rate > 5%, specific exception count
Activity log:    trigger on: resource deleted, policy denied, security event

Action Groups (what happens when alert fires):
Email:           notify team
SMS:             notify on-call
Teams webhook:   post to Teams channel
Azure Function:  auto-remediate (restart service, scale out)
Logic App:       create ITSM ticket, update status page
Automation Runbook: execute remediation script

Dashboard and visualisation:
Azure Monitor Dashboards: operational view for NOC
Azure Workbooks:          custom parameterised reporting and analysis
Power BI:                 management-level KPI reporting from Log Analytics
Grafana:                  popular open-source dashboards (integrates with Azure Monitor)

3. Design Data Storage Solutions (25–30%)

How do you choose the right Azure storage service?

Storage service selection matrix:

Requirement                                  → Best Service
Unstructured blobs (documents, images, video) → Azure Blob Storage
Virtual machine disks                         → Azure Managed Disks
File shares (SMB/NFS, lift-and-shift)         → Azure Files
Hybrid file server (on-prem + cloud cache)    → Azure File Sync
NoSQL document database (JSON)                → Azure Cosmos DB (SQL API)
NoSQL key-value at massive scale              → Azure Cosmos DB (Table API)
Globally distributed, multi-write            → Azure Cosmos DB (any API)
Relational data, OLTP workloads              → Azure SQL Database
SQL Server features, lift-and-shift           → Azure SQL Managed Instance
Data warehouse, analytical queries (OLAP)    → Azure Synapse Analytics / Fabric
Real-time analytics over streaming data      → Azure Synapse Analytics + Event Hubs
Message queue (simple, cheap, massive)        → Azure Storage Queues
Enterprise messaging (ordering, DLQ, pub/sub) → Azure Service Bus
Event streaming (millions/sec, telemetry)     → Azure Event Hubs
Time-series / IoT analytics                  → Azure Data Explorer / KQL
Graph data (relationships between entities)  → Azure Cosmos DB (Gremlin API)
Cache layer (session, query results)          → Azure Cache for Redis

Blob storage access tiers (cost vs latency):
Hot:     frequent access, highest storage cost, lowest access cost
Cool:    30-day minimum, cheaper storage, higher access cost
Cold:    90-day minimum, very cheap storage, higher access cost
Archive: 180-day minimum, cheapest storage, OFFLINE (rehydrate before read)
Lifecycle policy: automatically tier blobs based on last modified age

Blob storage redundancy (durability vs cost):
LRS:   3 copies, single datacenter, cheapest
ZRS:   3 copies across AZs, zone-resilient (recommended for most production)
GRS:   LRS + async copy to paired region, secondary readable only after failover
GZRS:  ZRS + async to paired region, highest durability (16 nines)
RA-GRS/RA-GZRS: read from secondary at all times (DR read scale-out)

How do you design a relational database solution on Azure?

Azure SQL options:

Azure SQL Database (fully managed PaaS):
→ Serverless tier: auto-pause during idle (cost saving for dev/test)
→ General Purpose: balanced compute/storage (most production OLTP)
→ Business Critical: in-memory OLTP, readable secondary, local SSD
→ Hyperscale: up to 100 TB, fast backup/restore (large databases)
→ Elastic Pool: share resources across multiple databases (multi-tenant SaaS)
→ Auto-failover groups: automatic geo-replication + failover (RPO < 5 sec)
→ Zone-redundant: Business Critical and General Purpose (zonal HA)

Azure SQL Managed Instance (PaaS with near-full SQL Server compatibility):
→ Lift-and-shift of SQL Server workloads needing: SQL Agent, CLR, linked servers,
  Service Broker, CDC, cross-database queries (not available in SQL Database)
→ Deployed INSIDE a VNet (private, no public endpoint by default)
→ Business Critical tier: in-memory OLTP + readable secondary
→ Migration: Database Migration Service from on-prem SQL Server
→ Choice: if application needs SQL Agent or cross-database queries → Managed Instance

SQL Server on Azure VM (IaaS):
→ Full SQL Server control (any version, any edition, OS-level access)
→ Use when: need features only available on bare SQL Server (SSRS, SSAS, SSIS),
            or specific versions/configurations not supported in PaaS
→ Higher management overhead vs PaaS options

Decision framework:
Can PaaS SQL Database handle the requirements?
  Yes: use SQL Database (lowest management overhead)
  Needs SQL Agent, cross-DB queries, Service Broker?
    Yes: use SQL Managed Instance
    Needs full OS control or specific SQL Server version?
      Yes: SQL Server on Azure VM

High availability for SQL:
Single region:    Business Critical tier → built-in Always On AG (3 replicas, ZR)
Multi-region:     Auto-failover group → geo-replication + automatic DNS failover
RPO:              < 5 seconds (geo-replication log shipping)
RTO:              < 30 seconds (automatic failover with DNS redirect)

How do you design a Cosmos DB solution?

Azure Cosmos DB:
→ Globally distributed, multi-model NoSQL database
→ SLA: 99.999% availability, single-digit millisecond latency (P99)
→ APIs: SQL (Core), MongoDB, Cassandra, Gremlin (graph), Table, PostgreSQL

Key design decisions:

1. Partition key selection (MOST CRITICAL decision):
→ Must provide even distribution of data (high cardinality)
→ Must be included in most queries (enables partition-targeted reads)
→ Cannot be changed after container creation
→ Good: UserId, CustomerId, TenantId, ProductId
→ Bad: Boolean, Status (low cardinality — hot partitions)
→ Synthetic key: if single key has low cardinality, combine fields
   e.g., {country}-{city} instead of country alone

2. Consistency levels (5 levels, stronger = more latency/cost):
Strong:           linearisable — always reads latest write (highest cost)
Bounded Staleness: reads lag writes by configurable window (K ops or T seconds)
Session:           strong consistency within a session (DEFAULT — best for most apps)
Consistent Prefix: reads never see out-of-order writes
Eventual:          weakest — reads may lag, highest performance

3. Request Units (RUs):
→ Currency of Cosmos DB — normalised unit of throughput
→ Every operation (read, write, query) consumes RUs
→ Provision throughput (guaranteed RU/s) or serverless (pay per op)
→ 1 RU = reading a 1 KB document by its partition key + id

4. Global distribution:
→ Add regions with one click — data replicated automatically
→ Single-write region: one primary write, any region reads (default)
→ Multi-region write: any region can write (use for write-heavy global apps)
→ Conflict resolution: needed for multi-write (last write wins or custom)

5. Change Feed:
→ Ordered stream of inserts and updates in a Cosmos DB container
→ Use for: event-driven microservices, materialised views, ETL to analytics
→ Consumers: Azure Functions trigger, Spark, SDK change feed processor

4. Design Infrastructure Solutions (30–35%)

How do you design a compute solution — choosing between VM, App Service, AKS, and Functions?

Compute service selection framework:

Azure Virtual Machines (IaaS):
→ Use when: need full OS control, specific OS/software, GPU, legacy apps
→ Lift-and-shift: move existing apps without code changes
→ HA pattern: Availability Zones + Standard Load Balancer (99.99% SLA)
→ Scale: VM Scale Sets (VMSS) for auto-scaling clusters
→ Avoid for: stateless web apps (use App Service/containers instead)

Azure App Service (PaaS):
→ Use when: web apps, REST APIs, mobile backends in .NET, Java, Node, Python, PHP
→ No VM management: Azure handles OS, patching, load balancing, scaling
→ Deployment slots: zero-downtime deployments, blue-green, A/B testing
→ VNet Integration: outbound private connectivity to databases/services
→ Private Endpoint: inbound private access (no public internet)
→ Scale: horizontal (add instances) up to 30, vertical (bigger plan)
→ Choose tier: Free/Basic (dev/test) → Standard (production, autoscale)
             → Premium (VNet integration) → Isolated (ASE, dedicated)

Azure Kubernetes Service (AKS):
→ Use when: microservices, containerised workloads, complex orchestration
→ Benefits: auto-scaling, rolling deployments, self-healing, rich ecosystem
→ Design: multiple node pools (system + user), node autoscaler, HPA
→ Networking: Azure CNI (direct pod IPs from VNet — needed for private)
→ Storage: Azure Disk (ReadWriteOnce) or Azure Files (ReadWriteMany)
→ Security: Managed Identity for pod-level Azure access (Workload Identity)
→ Ingress: Azure Application Gateway Ingress Controller (AGIC) for WAF

Azure Functions (Serverless):
→ Use when: event-driven compute, short-lived operations, unknown/spiky traffic
→ Scale to zero: pay only during execution (Consumption plan)
→ Premium plan: pre-warmed instances, VNet integration, longer timeout
→ Triggers: HTTP, Service Bus, Event Hub, Blob Storage, Timer, Cosmos DB
→ Durable Functions: stateful orchestration (fan-out/fan-in, long workflows)
→ Avoid for: long-running processes > 10 min (use App Service or AKS)

Decision tree:
Need OS-level control?              → VM
Containerised microservices?        → AKS
Web/API app, managed PaaS?          → App Service
Event-driven, short duration?       → Azure Functions
Burst traffic, stateless?           → Functions or App Service with autoscale
Complex stateful workflow?          → Durable Functions or Logic Apps

How do you design a network architecture for enterprise Azure?

Hub-Spoke network topology (recommended for most enterprises):

Hub VNet (central):
→ Shared services: Azure Firewall, VPN/ExpressRoute Gateway, Bastion, DNS
→ Managed by central networking team
→ All spoke traffic routes through hub (forced tunnelling)
→ Hub in each Azure region for global presence

Spoke VNets (per workload/environment):
→ Each application or team gets own spoke VNet
→ Peered to Hub: VNet Peering (low latency, same region)
               Global VNet Peering (cross-region)
→ No direct spoke-to-spoke peering (routes through hub firewall for inspection)
→ Subnet design: AppSubnet, DataSubnet, PrivateEndpointSubnet, etc.

Virtual WAN (alternative for large/global organisations):
→ Microsoft-managed hub-and-spoke at scale
→ Supports: any-to-any connectivity (spoke-spoke via VWAN hub)
→ Integrates: VPN, ExpressRoute, SD-WAN partners, Azure Firewall Manager
→ Use for: organisations with 10+ spokes or multiple regions

On-premises connectivity:
VPN Gateway:     encrypted IPsec over internet (up to 10 Gbps, simpler, cheaper)
ExpressRoute:    private dedicated circuit via connectivity provider
                 (consistent latency, up to 100 Gbps, higher cost, compliance)
ExpressRoute + VPN: redundant connectivity (ExpressRoute primary, VPN backup)

DNS architecture:
Azure Private DNS zones: private name resolution within Azure VNet
  privatelink.blob.core.windows.net → maps to storage private endpoint IPs
  privatelink.database.windows.net  → maps to SQL private endpoint IPs
Azure DNS Resolver: forward on-prem DNS queries to Azure private zones
                    forward Azure queries to on-prem DNS servers
  → Enables split-horizon DNS for hybrid environments

DDoS Protection:
DDoS Network Protection: per-VNet (recommended for public-facing)
DDoS IP Protection:      per-public IP (simpler, less features)
WAF:                     Application Gateway WAF or Front Door WAF
                         (protects against OWASP Top 10, layer 7 attacks)

How do you design a secure solution using Azure Key Vault?

Azure Key Vault:
→ Centralised secrets, keys, and certificates management
→ Every application should use Key Vault — NEVER store secrets in code/config

Key Vault uses:
Secrets:      connection strings, API keys, passwords
Keys:         RSA/EC keys for envelope encryption, signing
Certificates: X.509 certificates with auto-renewal (Let's Encrypt, DigiCert)

Access patterns:
Managed Identity (RECOMMENDED):
  → Application Managed Identity → assigned Key Vault Secrets User role
  → No credentials to manage, no rotation risk
  → Code: var secret = await client.GetSecretAsync("ConnectionString");

RBAC roles for Key Vault:
  Key Vault Secrets User:    read secret values (applications)
  Key Vault Secrets Officer: manage secrets, not read values (operations)
  Key Vault Administrator:   full control (admin — use PIM)
  Key Vault Reader:          read metadata, not values (audit)

Key Vault networking:
  Private Endpoint:     Key Vault accessible only via private IP in VNet
  Service Endpoint:     traffic stays on Azure backbone (no private IP)
  Firewall:             allowlist specific IPs/VNets; deny all others
  Production: always Private Endpoint + disable public access

Soft delete + Purge Protection:
  Soft delete (90 days): deleted secrets recoverable for 90 days
  Purge Protection:      prevents permanent deletion for retention period
  Both required for: compliance, ransomware protection, accidental deletion
  NEVER disable purge protection in production

Key rotation:
  Manual:   generate new version, update application to use latest version
  Automatic (certificates): Key Vault rotates before expiry via CA integration
  Event-driven: Key Vault fires Event Grid event on near-expiry
                → Logic App / Azure Function generates and stores new key
                → Notifies application to reload secret

5. Design Business Continuity Solutions (10–15%)

How do you design for high availability and disaster recovery?

Key definitions:
RTO (Recovery Time Objective):
  Maximum acceptable time for service to be restored after failure
  "We can be down for no more than 4 hours" → RTO = 4 hours

RPO (Recovery Point Objective):
  Maximum acceptable data loss measured in time
  "We cannot lose more than 15 minutes of transactions" → RPO = 15 minutes

SLA tiers and what they require:
99.9%   = 8.7 hours downtime/year  → single instance + Standard SSD (min)
99.95%  = 4.4 hours downtime/year  → Availability Set (2+ VMs)
99.99%  = 52 minutes downtime/year → Availability Zones (2+ VMs, 2+ AZs)
99.999% = 5.2 minutes downtime/year → multi-region active-active

Azure HA architecture patterns:

Single region HA (protects against hardware/datacenter failure):
  Azure Load Balancer + VM Scale Set across 3 Availability Zones
  SQL: Business Critical (3 replicas, zone-redundant)
  Storage: ZRS (3 copies across AZs)
  App Service: Premium tier (zone redundancy)
  SLA: 99.99% for compute + 99.99% for database

Multi-region HA (protects against region-wide outage):
Active-Passive (failover):
  Primary region handles traffic
  Secondary region: pre-deployed, inactive (warm standby)
  DNS failover via Azure Traffic Manager or Azure Front Door
  SQL: auto-failover group with automatic DNS failover
  RTO: minutes (DNS TTL), RPO: < 5 seconds (geo-replication)
  Use for: moderate RTO/RPO requirements

Active-Active (both regions serve traffic simultaneously):
  Both regions active, load balanced globally
  Data: Cosmos DB multi-write, or synchronous replication
  DNS: Azure Front Door (anycast routing, fastest region wins)
  RTO: near-zero (no failover needed — traffic shifts automatically)
  RPO: near-zero (no replication lag for active-active write)
  Use for: highest availability requirements, global user base

Azure Site Recovery (ASR):
  VM replication to secondary region
  Recovery Plans: orchestrated failover in correct order
  Test failover: validate DR without impact to production
  RTO: 1-2 hours (VM startup + DNS propagation)
  RPO: 15 minutes (replication interval)

How do you design a backup strategy?

Azure Backup architecture:

Recovery Services Vault vs Backup Vault:
Recovery Services Vault: VMs, SQL in VM, Azure Files, on-prem (MARS/MABS)
Backup Vault:            newer vault type — Blobs, Disks, AKS, PostgreSQL Flexible

Backup policies (design per RPO/RTO/retention):
Frequency:  hourly, daily, weekly
Retention:  daily (7-30 days), weekly (up to 5 years), monthly/yearly (compliance)
Cross-region restore: restore to paired region for DR (opt-in, extra cost)

Azure Backup for VMs:
→ Crash-consistent (default) or application-consistent (VSS on Windows)
→ Instant restore: restore individual files in minutes from snapshot
→ Soft delete: 14 days protection against accidental/ransomware deletion
→ Immutable vault: prevents deletion of backup data (locked permanently)

SQL Server in Azure VM:
→ Workload-aware backup: full + differential + log backup
→ Log backup every 15 minutes → RPO of 15 minutes for SQL
→ Compression enabled by default

Azure SQL Database:
→ Built-in automated backups: full weekly, differential 12-24h, log every 5-12 min
→ Point-In-Time Restore (PITR): restore to any second within retention period
→ Long-term retention (LTR): store backups up to 10 years (compliance)

Geo-redundant backup storage:
→ Recovery Services Vault: GRS (default) or LRS
→ Cross-region restore: restore backup from primary in secondary region
→ Required for: regulatory compliance, DR strategy validation

Backup monitoring:
→ Azure Backup Reports (Power BI): compliance dashboard, which VMs NOT backed up
→ Azure Monitor alerts: backup job failures → email/Teams notification
→ Recovery Services Vault → Backup Jobs → filter by status = Failed

6. Azure Well-Architected Framework & Landing Zones

What is the Azure Architecture Centre and key architecture patterns?

Azure Architecture Centre (docs.microsoft.com/azure/architecture):
→ Microsoft's official reference for proven Azure architectural patterns
→ Reference architectures: tested designs for common scenarios
→ Design patterns: reusable solutions to recurring problems

Key cloud design patterns for AZ-305:

1. Retry pattern:
   Transient failures (network timeout, throttling) → automatically retry
   Exponential backoff: wait 1s, 2s, 4s, 8s between retries
   Circuit Breaker: stop retrying after threshold → fail fast

2. Circuit Breaker pattern:
   Prevent cascading failures when a downstream service is unhealthy
   States: Closed (normal) → Open (failing, reject calls) → Half-Open (test)
   Implementation: Polly (C#), resilience4j (Java)

3. CQRS (Command Query Responsibility Segregation):
   Separate read and write models
   Write model: transactional database (SQL), optimised for writes
   Read model: denormalised read store (Cosmos DB, Redis), optimised for reads
   Event sourcing: store events, not state; rebuild state by replaying events

4. Strangler Fig pattern:
   Incrementally replace a monolith with microservices
   New requests → new service; old requests → legacy system
   Gradually migrate functionality until legacy system is empty

5. Event-driven architecture:
   Services communicate via events (loose coupling)
   Event Grid: routing discrete state change events
   Service Bus: reliable ordered message delivery
   Event Hubs: high-volume event streaming

6. Bulkhead pattern:
   Isolate critical resources — if one component fails, others continue
   e.g., separate thread pools, connection pools per downstream service
   Prevents one slow service from exhausting all resources

7. Cache-Aside pattern:
   Application manages cache explicitly:
   1. Check cache (Redis) — if found, return cached value
   2. If not found: query database, store in cache, return value
   3. On update: update database, INVALIDATE cache (not update)
   Use: Azure Cache for Redis + Azure SQL / Cosmos DB

8. Federated Identity pattern:
   Delegate authentication to external identity provider (IdP)
   Application trusts tokens from Entra ID (or ADFS, Google, etc.)
   Benefits: SSO across apps, no password management per app

What are the key networking design patterns for AZ-305?

Private Endpoint (most important networking concept for AZ-305):
→ Assign a private IP from your VNet to an Azure PaaS service
→ Traffic between your VNet and the PaaS service never leaves the Microsoft backbone
→ Disable public endpoint on PaaS resource for maximum security
→ Requires: Private DNS Zone to resolve FQDN to private IP

Pattern: secure multi-tier application
  App Service (private endpoint inbound) ← only VNet traffic allowed
    ↓ (VNet Integration — outbound)
  Azure SQL Database (private endpoint) ← no public access
  Azure Key Vault (private endpoint) ← no public access
  Azure Storage (private endpoint) ← no public access

Azure Front Door:
→ Global application delivery network: CDN + WAF + load balancing + failover
→ Anycast: routes users to the closest Azure PoP (Point of Presence)
→ WAF: OWASP protection globally at the edge
→ Origin groups: pool of backends (App Service in US + App Service in EU)
→ Health probes: automatically route away from unhealthy backends
→ Use for: global web applications with multi-region active-active

Azure Traffic Manager:
→ DNS-based global load balancing (NOT a reverse proxy — users connect directly to origin)
→ Routing methods:
  Priority:      primary region + failover regions
  Weighted:      distribute traffic by percentage (canary deployments)
  Performance:   route to lowest latency region for the user
  Geographic:    route users to specific region (data residency)
  Multivalue:    return all healthy endpoints, client picks
→ Use for: global routing of any protocol (not just HTTP), DNS-based failover

Azure Front Door vs Traffic Manager:
Front Door:       HTTP/HTTPS only, reverse proxy, WAF, anycast, CDN, SSL offload
Traffic Manager:  any protocol, DNS-based (no proxy), no WAF, no CDN
Choose Front Door for modern web applications
Choose Traffic Manager for non-HTTP workloads or existing architectures

7. Scenario-Based Questions

Scenario: Design a globally available, zero-trust e-commerce platform handling 1M users.

Requirements:
→ 99.99% SLA, global users, GDPR compliance (EU data residency)
→ Zero Trust security, no public access to backend services
→ Auto-scaling for seasonal traffic spikes

Architecture:

GLOBAL LAYER:
Azure Front Door Premium:
  → WAF policy: OWASP 3.2, custom rules (bot protection, rate limiting)
  → Origins: App Service (West Europe) + App Service (East US)
  → Health probes: route away from unhealthy origins automatically
  → CDN: static assets (images, JS, CSS) cached at edge PoPs
  → Private Link to App Service backend (Front Door → App Service private)

COMPUTE LAYER (West Europe — primary):
Azure App Service (Premium v3, zone-redundant):
  → Outbound via VNet Integration → private access to all backends
  → Private Endpoint for inbound (Front Door is the only entry point)
  → Auto-scale: 2-50 instances based on CPU and HTTP queue
  → Deployment slots: blue-green deployments (swap staging → production)

DATA LAYER:
Azure SQL Database (Business Critical, zone-redundant):
  → Auto-failover group → East US (passive secondary)
  → Private Endpoint: no public internet access
  → Encryption: Always Encrypted for PII columns (GDPR)
  → Auditing: all queries logged to Log Analytics

Azure Cosmos DB (SQL API):
  → Multi-region: West Europe (write) + East US (read)
  → Product catalogue, shopping cart, user sessions
  → Session consistency (strong within session, eventual across regions)
  → PITR: 30-day point-in-time restore

Azure Cache for Redis:
  → Product catalogue cache (60-minute TTL)
  → Session state store (24-hour TTL)
  → Private Endpoint

SECURITY LAYER:
Azure Key Vault (private endpoint): connection strings, API keys, TLS certs
Managed Identity: App Service → Key Vault, SQL, Storage (no stored credentials)
Private DNS Zones: all PaaS services resolve to private IPs
DDoS Network Protection: on all public-facing VNets
Microsoft Defender for Cloud: security posture management across all services
Microsoft Purview: classify and track PII data (GDPR compliance)

MONITORING:
Application Insights: request traces, exceptions, dependency calls, availability tests
Azure Monitor: infrastructure metrics, alerts, action groups
Log Analytics workspace: centralised logs from all services
KQL alert: failed login rate > 5% in 5 minutes → Teams alert

Scenario: A company wants to migrate a 3-tier on-premises application to Azure. Design the migration approach.

Current state: 
  Web tier: 3 IIS servers (Windows Server 2019)
  App tier:  4 .NET application servers
  Data tier: SQL Server 2019 cluster (500 GB, 100 concurrent connections)

Migration phases using CAF Migrate + Modernise:

Phase 1 — Assess (2 weeks):
  Azure Migrate: discover and assess all servers
    → Right-size recommendations (map on-prem specs to Azure SKUs)
    → Dependency analysis (what does each server call?)
    → Cost estimates for IaaS (lift-and-shift) vs PaaS (modernise)

Phase 2 — Lift-and-Shift (IaaS first — 4 weeks):
  Web tier:  3 × D4s_v5 VMs → Application Gateway → 3 VMs in AZ1/2/3
  App tier:  4 × D8s_v5 VMs → Internal Load Balancer → AZ1/2/3
  Data tier: SQL Server on Azure VM (business critical, zone-redundant)
  Migration tool: Azure Migrate + Replication (agent-based for physical)
  Cutover: DNS switch, 4-hour maintenance window, rollback plan ready
  
Phase 3 — Optimise and Modernise (3 months post-migration):
  Web tier:  migrate IIS apps → Azure App Service (Premium, ZR)
             Benefits: no VM management, built-in scaling, deployment slots
  App tier:  containerise .NET apps → Azure Kubernetes Service
             Benefits: better resource utilisation, rolling deployments
  Data tier: assess SQL Managed Instance compatibility
             Azure Database Migration Service (DMS) → online migration (< 1h cutover)
             If SQL Agent or Service Broker needed → SQL Managed Instance
             If standard T-SQL → Azure SQL Database Business Critical

Phase 4 — Govern and Secure (ongoing):
  Azure Policy: enforce tagging, no public IPs on VMs, encryption at rest
  Cost Management: reserved instances for stable workloads (save 40%)
  Monitoring: Azure Monitor + Application Insights (enable for modernised apps)
  Security: Defender for Servers (VMs) + Defender for SQL (databases)

Scenario: Design a multi-tenant SaaS architecture on Azure.

Multi-tenant SaaS: one deployment serves multiple customer organisations

Tenancy model decision:

Model A — Shared everything (full multi-tenant):
  → One database, one compute, all tenants share
  → Lowest cost, highest density
  → Risk: noisy neighbour, data isolation challenges
  → Use for: small tenants, cost-sensitive, lower compliance requirements
  → Data isolation: Row-Level Security in SQL Database (TenantId filter)
  → Compute isolation: App Service multi-tenant with Entra ID OIDC tenant filtering

Model B — Shared compute, separate databases (hybrid):
  → One App Service plan, one Cosmos DB container per tenant (partition by TenantId)
  → OR: Elastic Pool — separate databases sharing one SQL server
  → Elastic Pool: up to 500 databases, pooled DTUs/vCores
  → Good balance: isolation at data layer, shared compute cost
  → Use for: SMB SaaS with moderate isolation requirements

Model C — Fully isolated (silo):
  → Separate subscription or resource group per tenant
  → Highest isolation, highest cost
  → Use for: enterprise tenants, strict compliance (FinTech, Healthcare)
  → Deployment: Bicep template, deploy new resources per tenant onboarding

SaaS-specific design patterns:
Onboarding automation: Logic App / Azure Function → provision new tenant infra
Tenant routing:   App Service → header/domain-based routing to correct data
Tenant billing:   Azure Cost Management tags (TenantId) → per-tenant cost tracking
Tenant offboarding: Data export → soft delete retention → hard delete after 90 days
Compliance:       Purview sensitivity labels per tenant, separate Key Vault per tenant

Scenario: How do you design for cost optimisation without sacrificing reliability?

Cost optimisation architecture decisions:

1. Right-size with Azure Advisor:
   → Azure Advisor → Cost → Underutilised resources
   → VMs with < 5% average CPU → downsize (D4 → D2)
   → SQL DTUs < 20% average → move to smaller service objective

2. Reserved Instances (40-72% savings):
   → 1-year RI for VMs known to run 24/7 (web servers, databases)
   → 3-year RI for very stable workloads (domain controllers, monitoring)
   → Scope: shared (across all subscriptions) for maximum flexibility

3. Azure Savings Plans (up to 65%):
   → Commitment to hourly spend on compute (any region, any size)
   → More flexible than Reserved Instances
   → Best for variable but consistent compute usage

4. Azure Hybrid Benefit:
   → Windows Server with SA: 40% savings on Windows VMs
   → SQL Server with SA: 55% savings on SQL licensing
   → Stack together with Reserved Instances for up to 80% savings

5. PaaS over IaaS:
   → Serverless/PaaS: pay only for what you use
   → App Service vs VMs: same capability, App Service scales to zero in some tiers
   → Azure Functions (Consumption): pay per execution (dev/test = free tier)

6. Autoscaling + scheduled scaling:
   → Scale in nights/weekends for non-production
   → VMSS: minimum 2 instances (HA), scale out on CPU > 70%
   → Dev VMs: auto-shutdown at 6pm via Azure Automation

7. Storage lifecycle management:
   → Blob: auto-tier (Hot → Cool after 30 days → Archive after 365 days)
   → Saves 70-95% on old data that must be retained

8. Dev/Test pricing:
   → Azure Dev/Test subscriptions: discounted Windows Server licensing
   → SQL in Dev/Test: no SQL licence cost (dev only workloads)

9. Spot VMs (up to 90% discount):
   → Fault-tolerant, interruptible workloads: batch processing, rendering, CI runners
   → Use VMSS with Spot priority + fallback to regular (Azure auto-evicts when needed)

10. Network costs:
    → Outbound bandwidth costs money; keep data in same region as consumers
    → VNet Peering cross-region: transfer costs (consider VPN vs peering)
    → CDN: serve static content from edge to reduce origin egress

8. Cheat Sheet — Quick Reference

AZ-305 Exam Domain Weights

Domain                                     Weight   Focus
Design infrastructure solutions            30-35%   Compute (VM/AKS/App Service/Functions)
                                                     Networking (hub-spoke, Front Door, VPN)
                                                     Security (Key Vault, Private Endpoints)
Design identity, governance & monitoring   25-30%   Hybrid identity, Conditional Access, PIM
                                                     Management Groups, Azure Policy, tagging
                                                     Azure Monitor, App Insights, Log Analytics
Design data storage solutions              25-30%   SQL DB vs MI vs VM, Cosmos DB design
                                                     Blob tiers, redundancy, Key Vault
                                                     Synapse / Fabric for analytics
Design business continuity solutions       10-15%   RTO/RPO, AZ vs multi-region, ASR
                                                     Azure Backup, immutable vault, PITR

Compute Decision Tree

Need OS-level control / specific software?     → VM + Availability Zones
Containerised microservices / complex scaling? → AKS
Web/API managed PaaS (.NET/Java/Node/Python)?  → App Service
Event-driven, short burst, unknown traffic?    → Azure Functions
Stateful orchestration (long workflow)?        → Durable Functions / Logic Apps
GPU workloads (AI/ML training, rendering)?     → N-series VMs
Burst compute (CI runners, batch)?             → Spot VMs or Batch
Virtual desktop for remote workers?            → Azure Virtual Desktop

SLA achieved by:
Single VM + Premium SSD:  99.9%
Availability Set (2+ VMs): 99.95%
Availability Zones (2+ AZs): 99.99%
Multi-region active-active: 99.999%

Storage Decision Matrix

Use case                              → Service
Blobs (unstructured: media, docs)     → Blob Storage (Hot/Cool/Archive)
VM Disks                              → Managed Disks (Premium SSD for prod)
Shared file system (SMB/NFS)          → Azure Files
Hybrid file server caching            → Azure File Sync
Relational OLTP (managed)             → Azure SQL Database
SQL Server features (SQL Agent, etc.) → Azure SQL Managed Instance
Full SQL Server control               → SQL Server on Azure VM
NoSQL document / JSON                 → Azure Cosmos DB (SQL API)
Global multi-region, multi-write      → Azure Cosmos DB
Data warehouse / OLAP                 → Azure Synapse Analytics / Fabric
Enterprise message queue              → Azure Service Bus
Event streaming (IoT, telemetry)      → Azure Event Hubs
Session cache, query cache            → Azure Cache for Redis
Graph data                            → Cosmos DB (Gremlin API)

Networking Quick Reference

Topology:           Hub-Spoke (most enterprises) or Azure Virtual WAN (large scale)
On-prem private:    ExpressRoute (dedicated, consistent) preferred over VPN
On-prem encrypted:  VPN Gateway (encrypted over internet, simpler, cheaper)
Global HTTP/HTTPS:  Azure Front Door (anycast, WAF, CDN, private link origins)
Global any protocol: Azure Traffic Manager (DNS-based, any protocol)
Regional HTTP:      Application Gateway (L7, WAF, SSL termination, URL routing)
Regional TCP/UDP:   Azure Load Balancer Standard (L4, zone-redundant)
Private PaaS:       Private Endpoint + Private DNS Zone (production standard)
Admin access:       Azure Bastion (no public IP on VMs, browser-based RDP/SSH)
Perimeter firewall: Azure Firewall Premium (IDPS, TLS inspection, centralised)
DDoS:               DDoS Network Protection (per-VNet for public-facing workloads)

Business Continuity Quick Reference

RTO/RPO targets → design pattern:
Hours/Hours:     Azure Backup + ASR warm standby (passive failover)
Minutes/Minutes: Auto-failover group + Traffic Manager / Front Door failover
Near-zero/zero:  Active-active multi-region (Cosmos DB multi-write, Front Door)

SQL DR:
Single region: Business Critical (3 replicas, AZ) — 99.995% SLA
Multi-region:  Auto-failover group → automatic DNS failover
               RPO: < 5 seconds, RTO: < 30 seconds

VM DR:
Azure Site Recovery: replicate VMs to secondary region
Recovery Plans: orchestrate failover order (DC first, then app, then DB)
Test failover: validate quarterly without impacting production

Backup essentials:
Soft delete: 14 days recovery after accidental deletion
Immutable vault (locked): ransomware protection (cannot be disabled)
Cross-region restore: restore backup in secondary region for DR validation
PITR (SQL): restore to any second in the retention window

Well-Architected Framework Pillars Summary

Pillar           Key services / patterns
Reliability      AZs, multi-region, auto-failover, health probes, retry+circuit breaker
Security         Zero Trust, Private Endpoints, Key Vault, Managed Identity, WAF
Cost             Reserved Instances, right-sizing, lifecycle tiers, PaaS over IaaS
Operational Exc. IaC (Bicep), CI/CD, Azure Monitor, runbooks, deployment slots
Performance      Autoscale, CDN (Front Door), Redis cache, read replicas, AKS HPA

Top 10 Tips

  1. AZ-305 is a DESIGN exam, not a configuration exam — every question presents a business scenario asking you to RECOMMEND, COMPARE, or EVALUATE. The key skill is justifying WHY one service fits better than another — not knowing every configuration option.

  2. Infrastructure is 30–35% of the exam — the largest domain. Master: compute service selection (VM vs App Service vs AKS vs Functions), hub-spoke networking, Private Endpoints, Key Vault, and Azure Front Door vs Traffic Manager.

  3. Always anchor decisions in the Well-Architected Framework — every design choice has a WAF justification. "Why Private Endpoints?" → Security pillar (defence in depth). "Why Reserved Instances?" → Cost pillar. love WAF-framed answers.

  4. Private Endpoints are the production networking standard — any PaaS service (SQL, Storage, Key Vault, App Service) in production should have a Private Endpoint and disabled public access. Service Endpoints are insufficient for most enterprise requirements.

  5. Managed Identity eliminates credential management — any Azure resource authenticating to another Azure service should use Managed Identity. No secrets in code, no rotation risk, no leakage. Always the first recommendation for any "how do you authenticate" question.

  6. Hub-Spoke topology with Azure Firewall — the standard enterprise network architecture. Hub contains shared services (Firewall, VPN/ExpressRoute GW, Bastion). Spokes are workload VNets peered to hub. All spoke-to-spoke traffic inspected via hub Azure Firewall.

  7. RTO and RPO drive the HA design — before answering any HA/DR question, establish the RTO and RPO requirements. RTO/RPO in hours → warm standby + ASR. Minutes → auto-failover groups + Traffic Manager. Near-zero → active-active multi-region with Cosmos DB.

  8. SQL Database vs SQL Managed Instance — the most commonly confused SQL decision. SQL Database = most managed, best for greenfield. SQL Managed Instance = when you need SQL Agent, cross-database queries, Service Broker, or CLR. Know this boundary cold.

  9. Azure Front Door vs Traffic Manager — Front Door is a reverse proxy (HTTP/HTTPS, WAF, CDN, anycast, SSL offload). Traffic Manager is DNS-based routing (any protocol, no proxy, no WAF). Global web apps → Front Door. Non-HTTP global routing → Traffic Manager.

  10. The Cloud Adoption Framework provides the governance story — management group hierarchy, landing zones, Azure Policy at scale, and subscription design are all CAF concepts. For any "how do you govern 50 subscriptions" question, the answer starts with CAF landing zones.



Microsoft Azure Administrator (AZ-104) Complete Guide

Microsoft Azure Administrator (AZ-104) — Complete Guide

Identity & Governance · Storage · Compute · Virtual Networking · Monitoring & Backup · ARM & Bicep · Scenarios · Cheat Sheet

Top Hashtags: #AzureAdministrator, #AZ104, #MicrosoftAzure, #AzureAdmin, #CloudComputing, #AzureCertification, #AzureNetworking, #AzureCompute, #AzureStorage, #MicrosoftCertified


Table of Contents

  1. Exam Overview & Identity/Governance (20–25%)
  2. Implement and Manage Storage (15–20%)
  3. Deploy and Manage Azure Compute (20–25%)
  4. Implement and Manage Virtual Networking (15–20%)
  5. Monitor and Maintain Azure Resources (10–15%)
  6. ARM Templates, Bicep & Automation
  7. Scenario-Based Questions
  8. Cheat Sheet — Quick Reference

1. Exam Overview & Identity/Governance (20–25%)

AZ-104 Exam at a Glance

The AZ-104 Microsoft Azure Administrator exam validates expertise in implementing, managing, and monitoring an organisation's Azure environment. It covers virtual networks, storage, compute, identity, security, and governance.

Skill Domain Exam Weight
Manage Azure identities and governance 20–25%
Deploy and manage Azure compute resources 20–25%
Implement and manage virtual networking 15–20%
Implement and manage storage 15–20%
Monitor and maintain Azure resources 10–15%

Prerequisites: No formal prerequisites, but 6+ months of hands-on Azure experience is strongly recommended. Familiarity with PowerShell, Azure CLI, Azure Portal, and ARM/Bicep templates expected.


What is Azure Resource Manager (ARM) and how does it underpin everything in Azure?

Azure Resource Manager (ARM):
→ The management layer for ALL Azure resources
→ Every action (Portal, CLI, PowerShell, REST API, Terraform) goes through ARM
→ Provides: authentication, authorisation, tagging, locking, templates

ARM concepts:
Subscription:      billing and access boundary — contains resource groups
Resource Group:    logical container for related Azure resources
                   all resources in an RG share the same lifecycle
Resource:          individual Azure service (VM, storage account, VNet)
Resource Provider: the service that supplies a resource type
                   Microsoft.Compute (VMs), Microsoft.Network (VNets),
                   Microsoft.Storage (storage accounts)

ARM operations:
Control plane:   manage resources (create, delete, configure) via ARM
Data plane:      access resource data (read a blob, send a queue message)
                 controlled by resource-level access (keys, RBAC data roles)

Resource Group best practices:
→ Group by lifecycle: resources deleted together go in same RG
→ Group by environment: Production-RG, Dev-RG, Test-RG
→ Region: RG has a region (for metadata), but can contain resources
  from any region
→ RBAC applied at RG level applies to all resources in the RG
→ Delete RG = delete ALL resources in it (use locks to protect)

What are Azure Management Groups and how do they enable governance at scale?

Management Group hierarchy:
Root Management Group (tenant level)
  └── Management Group (e.g., "Production")
        └── Management Group (e.g., "EMEA")
              └── Subscription A
              └── Subscription B
        └── Management Group (e.g., "APAC")
              └── Subscription C

Why Management Groups:
→ Apply Azure Policy across multiple subscriptions at once
→ Apply RBAC role assignments across multiple subscriptions
→ Manage hundreds of subscriptions from a single hierarchy
→ Up to 6 levels of hierarchy (not counting root)

Example governance with Management Groups:
Root
  ├── Corporate (MG) — Audit policy applied here (all subs inherit)
  │     ├── Production (MG) — No public IP policy applied here
  │     │     ├── Prod-UK subscription
  │     │     └── Prod-US subscription
  │     └── Non-Production (MG) — Dev/test allowed policies
  │           ├── Dev subscription
  │           └── Test subscription
  └── Sandbox (MG) — Allow all (experimental)
        └── Sandbox subscription

What is Azure Policy and how does it work?

Azure Policy enforces organisational standards and assesses compliance
at scale across subscriptions and resource groups.

Policy components:
Policy definition:  the rule (e.g., "VMs must use managed disks")
Initiative:         a collection of policy definitions (e.g., "CIS Azure benchmark")
Assignment:         apply policy/initiative to a scope (MG/subscription/RG)
Compliance:         dashboard showing compliant vs non-compliant resources
Remediation:        fix non-compliant resources (deployIfNotExists,
                    modify effects)

Policy effects (what happens when condition is met):
Deny:                block the resource creation/update (strongest)
Audit:               allow but mark as non-compliant (reporting only)
Append:              add fields to the resource (e.g., required tags)
Modify:              change resource properties (e.g., disable public IP)
DeployIfNotExists:   deploy a related resource if missing (e.g., deploy
                     diagnostics extension if not present)
AuditIfNotExists:    audit if a related resource is missing

Common built-in policies:
→ "Allowed locations" — restrict deployments to specific regions
→ "Require a tag and its value" — enforce tagging standards
→ "Allowed virtual machine SKUs" — restrict VM sizes
→ "VMs should use managed disks" — no unmanaged disk VMs
→ "Secure transfer to storage accounts should be enabled"
→ "Allowed resource types" — whitelist only approved resource types

Policy vs RBAC:
Azure Policy: WHAT can be deployed (resource properties/config)
Azure RBAC:   WHO can deploy/manage resources (identity-based)
Both needed: RBAC controls access, Policy controls configuration

What are Azure resource locks and when do you use them?

Resource locks prevent accidental deletion or modification of
critical Azure resources — even by subscription owners.

Lock types:
CanNotDelete (Delete lock):
→ Users can read and modify the resource but CANNOT delete it
→ Most common lock — protect production resources from accidental deletion

ReadOnly:
→ Users can read the resource but CANNOT modify OR delete it
→ Equivalent to applying Reader role to everyone
→ Use with caution — may break operations that need to modify resource
   (e.g., restarting a VM requires a write operation)

Lock scope (inherited by children):
Subscription → Resource Group → Resource
Lock on RG protects all resources in the RG

Lock hierarchy:
If RG has Delete lock: resources in RG cannot be deleted
If Resource has Delete lock: that specific resource cannot be deleted
Most restrictive lock wins

Commands:
# Apply lock:
az lock create --name "ProductionLock" --resource-group "Prod-RG" \
  --lock-type CanNotDelete

# PowerShell:
New-AzResourceLock -LockName "ProductionLock" -LockLevel CanNotDelete \
  -ResourceGroupName "Prod-RG"

# Remove lock (must remove before deleting resource):
az lock delete --name "ProductionLock" --resource-group "Prod-RG"

Tip: Resource locks are the last safety net for production resources. Always apply a CanNotDelete lock to production resource groups. Locks must be removed before deleting — this intentional friction prevents accidents.


What is Azure Cost Management and how do you control spending?

Azure Cost Management + Billing:
→ Monitor, allocate, and optimise Azure spending
→ Access: Azure Portal → Cost Management + Billing

Key features:
Cost analysis:    visualise spending by service, resource, tag, location
Budgets:          set spending thresholds with email/action group alerts
Cost alerts:      alert when budget reaches 50%, 75%, 90%, 100%
Advisor:          AI recommendations to reduce cost, improve security,
                  performance, reliability

Cost control tools:
Tags:             tag resources (Environment=Production, Team=Finance)
                  filter Cost Analysis by tag to see team-level spend
Reservations:     commit to 1 or 3 years → 40-72% discount vs pay-as-you-go
Savings Plans:    flexible hourly commitment → 11-65% discount
Azure Hybrid Benefit: use existing Windows Server/SQL Server licences
                      on Azure VMs → save up to 40%
Dev/Test pricing: reduced rates for non-production subscriptions
Auto-shutdown:    schedule VMs to shut down outside business hours

Budget alert example:
Budget: £10,000/month for Production subscription
Alerts:
  → 80% (£8,000) reached: email Finance team
  → 100% (£10,000) reached: email Finance + CTO + trigger action group
  → Action group: call Azure Automation runbook to tag new VMs for review

2. Implement and Manage Storage (15–20%)

What are Azure Storage account types and redundancy options?

Storage account types:
Standard General Purpose v2 (GPv2):
→ Supports: Blob, File, Queue, Table storage
→ Performance: Standard (HDD-backed)
→ Use for: most workloads, backup, archive

Premium Block Blobs:
→ Supports: Block blobs and append blobs only
→ Performance: SSD-backed, very low latency
→ Use for: high-throughput scenarios, AI/ML data pipelines

Premium File Shares:
→ Supports: Azure Files only
→ Performance: SSD-backed
→ Use for: high-performance file shares (databases, FSLogix profiles)

Premium Page Blobs:
→ Supports: Page blobs only (used for VM disks)
→ Performance: SSD-backed
→ Use for: IaaS VM managed disks (usually auto-selected)

Redundancy options (data durability):
LRS (Locally Redundant Storage):
→ 3 copies within a single datacenter (single availability zone)
→ 11 nines durability (99.999999999%)
→ Cheapest — no protection against datacenter failure

ZRS (Zone-Redundant Storage):
→ 3 copies across 3 availability zones in the same region
→ 12 nines durability
→ Survives datacenter failure
→ Recommended for most production workloads

GRS (Geo-Redundant Storage):
→ LRS in primary region + LRS in secondary region (100s of miles away)
→ Secondary is read-accessible only after Microsoft initiates failover
→ 16 nines durability

GZRS (Geo-Zone-Redundant Storage):
→ ZRS in primary + LRS in secondary
→ Highest durability (16 nines)
→ Most expensive — use for critical data

RA-GRS / RA-GZRS:
→ Adds read access to secondary region at all times (not just after failover)
→ Use when: need to read from secondary for DR or read scale-out

What are the Azure Blob storage access tiers?

Access tiers (balance cost vs access frequency):

Hot:
→ Highest storage cost, lowest access cost
→ Use for: frequently accessed data (active databases, app files)
→ Minimum storage duration: none

Cool:
→ Lower storage cost than Hot, higher access cost
→ Use for: infrequently accessed data (30-day minimum recommended)
→ Minimum storage duration: 30 days (early deletion fees apply)

Cold (newer tier):
→ Lower storage cost than Cool, higher access cost than Cool
→ Use for: rarely accessed data, kept at least 90 days
→ Minimum storage duration: 90 days

Archive:
→ Lowest storage cost (~90% cheaper than Hot)
→ OFFLINE — data is not immediately accessible
→ Rehydration required before reading:
  Standard rehydration: up to 15 hours
  High priority rehydration: under 1 hour (higher cost)
→ Use for: long-term backup, compliance data, rarely accessed archives
→ Minimum storage duration: 180 days

Lifecycle Management policies:
→ Automatically transition blobs between tiers based on age/conditions
→ Example:
  After 30 days → move from Hot to Cool
  After 90 days → move from Cool to Cold
  After 365 days → move to Archive
  After 2555 days (7 years) → delete

# PowerShell - set blob access tier:
Set-AzStorageBlobTier -Container "mycontainer" -Blob "myfile.pdf" \
  -Tier Archive -Context $storageContext

What is Azure Files and how does it compare to Blob storage?

Azure Files:
→ Fully managed cloud file shares accessible via SMB (3.0/2.1) and NFS
→ Can be mounted as a network drive on Windows, Linux, macOS
→ Compatible with on-prem file server applications
→ Use cases: lift-and-shift of on-prem file servers, shared config files,
             FSLogix profile containers (Azure Virtual Desktop)

Azure File Sync:
→ Caches Azure file shares on Windows Server on-premises
→ On-prem server has frequently used files locally (fast access)
→ Infrequently used files stored only in Azure (cloud tiering)
→ Supports multiple on-prem servers all syncing to the same Azure share
→ Use for: hybrid file server scenarios, replacing DFS

Azure Blob vs Azure Files:
                    Blob Storage          Azure Files
Access protocol:    HTTP/HTTPS REST       SMB, NFS, REST
Mount as drive:     No                    Yes (SMB/NFS)
Use case:           Unstructured data,    File shares, home dirs
                    media, backup         app config, lift-and-shift
Max file size:      190.7 TB per blob     4 TB per file (Standard)
Performance:        Scales massively      Depends on share tier
POSIX permissions:  No                    Yes (NFS shares)

What are Shared Access Signatures (SAS) and when do you use them?

SAS (Shared Access Signature):
→ A URI that grants limited, time-bound access to Azure Storage resources
→ No need to share the storage account key
→ Granular control: which resource, what operations, how long, from where

SAS types:
Account SAS:    access to multiple storage services (Blob + Queue + Table)
Service SAS:    access to a specific service (Blob only)
User delegation SAS: signed with Entra ID user credentials (most secure)
                     no storage account key needed — audit trail in Entra logs

SAS parameters:
sv:  service version
st:  start time
se:  expiry time (always set — limit exposure window)
sr:  resource type (b=blob, c=container, f=file, q=queue)
sp:  permissions (r=read, w=write, d=delete, l=list, c=create)
sig: cryptographic signature

Example SAS URI:
https://mystorageaccount.blob.core.windows.net/mycontainer/file.pdf
?sv=2023-11-03&st=2025-01-01T00%3A00%3A00Z
&se=2025-01-31T23%3A59%3A00Z&sr=b&sp=r
&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxx

Stored Access Policy:
→ Define SAS constraints on the container/queue/table (server-side)
→ Allows revoking a SAS by modifying or deleting the stored access policy
→ Without a stored access policy, a SAS cannot be revoked before expiry

Access control hierarchy (most to least preferred):
1. Entra ID RBAC (Storage Blob Data Reader/Contributor) — no keys needed
2. User delegation SAS — Entra-backed, audited
3. Service/Account SAS — key-based, harder to revoke
4. Storage account key — full access, treat like a root password

3. Deploy and Manage Azure Compute (20–25%)

What are Azure Virtual Machines and key configuration concepts?

VM creation key decisions:
Region:         where the VM runs — affects latency, compliance, availability
Size/SKU:       CPU, RAM, temp disk, max NICs, max data disks
                B-series: burstable (dev/test)
                D-series: general purpose (most workloads)
                E-series: memory optimised (databases, in-memory analytics)
                F-series: compute optimised (batch, gaming)
                N-series: GPU (AI/ML training, graphics)
Image:          OS (Windows Server 2022, Ubuntu 22.04, RHEL, custom)
Disk:           OS disk (required) + data disks (optional)
Authentication: SSH key pair (Linux) or password (Windows — avoid for prod)
Networking:     VNet, subnet, NSG, public IP (avoid if possible)
Availability:   Availability Zones, Availability Sets, VMSS

VM disk types:
Standard HDD:  cheapest, high latency — backup/archive workloads
Standard SSD:  lower latency than HDD — dev/test, light workloads
Premium SSD:   SLA-backed, low latency — production workloads
Premium SSD v2: more granular performance control
Ultra Disk:    highest IOPS (up to 400,000) — SAP HANA, top-tier DBs

Managed disks:
→ Azure manages storage account for disk — no self-management needed
→ Snapshots: point-in-time copy of a managed disk
→ Images: generalised snapshot used to create new VMs
→ Disk encryption: Azure Disk Encryption (BitLocker/dm-crypt)
               or Server-Side Encryption with customer-managed keys

VM extensions:
Custom Script Extension:  run scripts on VM after deployment
Azure Monitor Agent:      collect metrics/logs to Azure Monitor
DSC Extension:            apply PowerShell DSC configurations
Diagnostics Extension:    send guest OS metrics to Azure Monitor
Microsoft Antimalware:    antivirus for Windows VMs

What are Availability Sets and Availability Zones?

Availability Sets:
→ Protect VMs from hardware failures WITHIN a single datacenter
→ Fault domains: separate physical hardware (rack, power, network)
→ Update domains: separate maintenance windows
→ VMs spread across fault domains (up to 3) + update domains (up to 20)
→ SLA: 99.95% uptime (for 2+ VMs in an availability set)
→ Does NOT protect against datacenter/zone failure
→ Legacy approach — prefer Availability Zones for new deployments

Availability Zones:
→ Physically separate datacenters within the same Azure region
→ Each zone has independent power, cooling, and networking
→ Deploy VM in Zone 1, Zone 2, Zone 3 = protected from datacenter failure
→ SLA: 99.99% uptime (for 2+ VMs in different zones)
→ Not all regions have 3 AZs — check region capabilities first
→ Zone-resilient services: ZRS storage, zone-redundant App Gateways

VM Scale Sets (VMSS):
→ Deploy and manage a group of identical, load-balanced VMs
→ Auto-scale: add/remove VMs based on CPU, memory, schedule, or custom metrics
→ Uniform mode: all VMs use the same image and size
→ Flexible mode: mix of VMs (different sizes/images) — recommended
→ Works with Azure Load Balancer or Application Gateway

Decision:
Single datacenter protection   → Availability Set (legacy)
Datacenter/zone protection     → Availability Zones (recommended)
Auto-scaling web tier          → VM Scale Sets in Availability Zones
Highest HA (99.99% SLA)        → 2+ VMs across 2+ Availability Zones

What are Azure App Service and its key features?

Azure App Service:
→ Fully managed PaaS for hosting web apps, REST APIs, mobile backends
→ Supports: .NET, Java, Node.js, Python, PHP, Ruby, custom containers
→ No server management — Azure handles OS patching, scaling, load balancing

App Service Plan:
→ The compute resources underlying the App Service
→ Defines: region, number of VM instances, size of VM instances, pricing tier

Pricing tiers:
Free/Shared: no SLA, shared infrastructure, limited — dev only
Basic:       dedicated compute, manual scale, no slots
Standard:    auto-scale, deployment slots (staging), custom domains/SSL
Premium:     more instances, more slots, VNet integration, higher performance
Isolated:    App Service Environment (ASE) — private, VNet-injected, highest isolation

Key features:
Deployment slots:
→ Separate environments (staging, QA) on the same App Service
→ Swap slots: zero-downtime deployment
   Staging → Production swap: production gets staging's code instantly
   If deployment fails: swap back (rollback in seconds)
→ Standard tier: 5 slots, Premium: 20 slots

Auto-scale:
→ Scale out (add instances): based on CPU %, memory, HTTP queue length
→ Scale in (remove instances): when metrics drop
→ Schedule-based: scale up at 8am, scale down at 6pm

VNet Integration:
→ App Service can make outbound calls to resources in a VNet
→ Required for: private SQL, private storage, on-prem via VPN/ExpressRoute
→ Does NOT allow inbound traffic from VNet (use Private Endpoint for that)

Deployment methods:
→ GitHub Actions / Azure DevOps CI/CD pipeline (recommended)
→ Local Git deployment
→ ZIP deploy (az webapp deployment)
→ Container deployment (ACR → App Service)

What is Azure Kubernetes Service (AKS) and key admin concepts?

AKS: managed Kubernetes cluster on Azure
→ Microsoft manages: control plane (API server, etcd, scheduler)
→ You manage: worker nodes (node pools), workloads

Key concepts:
Node pool:      group of VMs with same size/config — can have multiple pools
System pool:    runs kube-system pods (required)
User pool:      runs application workloads
Node size:      choose VM SKU for the node pool
Autoscaler:     cluster autoscaler — adds/removes nodes based on pod demand
HPA:            Horizontal Pod Autoscaler — adds/removes pods based on CPU/memory

Networking modes:
Kubenet:        nodes get IP from Azure VNet, pods get IP from overlay network
                pods use NAT to communicate outside cluster
Azure CNI:      pods get IP directly from VNet subnet
                enables direct pod-to-pod communication from VNet
                requires more IP addresses (plan subnet size carefully)

AKS + Entra ID integration:
→ RBAC for Kubernetes: use Entra ID groups as Kubernetes RBAC subjects
→ Managed Identity: AKS uses Managed Identity to pull from ACR, access Key Vault
→ Workload Identity: pods authenticate to Azure services using Entra ID

AKS storage:
Azure Disk:     ReadWriteOnce — one pod on one node
Azure Files:    ReadWriteMany — multiple pods on multiple nodes (SMB)
Azure Blob:     ReadWriteMany (via BlobFuse) — large unstructured data

4. Implement and Manage Virtual Networking (15–20%)

What are Virtual Networks (VNets) and subnets in Azure?

Virtual Network (VNet):
→ Isolated, private network in Azure — your own address space
→ Resources in a VNet communicate privately by default
→ Define address space: CIDR notation (e.g., 10.0.0.0/16)
→ VNet scoped to a single region (cannot span regions)

Subnets:
→ Subdivide VNet address space into smaller ranges
→ Each resource goes in a specific subnet
→ Reserved addresses per subnet: first 4 + last 1 = 5 IPs unusable
  e.g., 10.0.0.0/24 = 256 addresses, 251 usable

Subnet design example:
VNet: 10.0.0.0/16 (65,536 addresses)
  ├── WebSubnet:    10.0.1.0/24 (251 usable — web servers/App Service)
  ├── AppSubnet:    10.0.2.0/24 (251 usable — application tier)
  ├── DataSubnet:   10.0.3.0/24 (251 usable — databases)
  ├── GatewaySubnet: 10.0.4.0/27 (27 usable — VPN/ExpressRoute GW)
  └── AzureBastionSubnet: 10.0.5.0/26 (59 usable — Bastion host)
      (must be named exactly "AzureBastionSubnet")

VNet peering:
→ Connect two VNets privately through Microsoft backbone (no internet)
→ Can be same region (VNet Peering) or different regions (Global VNet Peering)
→ NOT transitive: A↔B, B↔C does NOT mean A↔C
   Solution: hub-spoke topology or Azure Virtual WAN
→ Peering is non-overlapping: address spaces must not overlap

Service endpoints:
→ Extend VNet identity to Azure PaaS services (Storage, SQL, Key Vault)
→ Traffic stays on Microsoft backbone (not internet)
→ PaaS service can be locked to your VNet's traffic only

Private Endpoints:
→ Assign a private IP from your VNet to a PaaS service
→ The PaaS service gets a private IP in your VNet
→ Disable public internet access on the PaaS resource
→ Access via Private DNS Zone: storage.privatelink.blob.core.windows.net
→ More secure than Service Endpoints — completely private
→ Recommended over Service Endpoints for production

What are Network Security Groups (NSGs) and how do they work?

NSG (Network Security Group):
→ Stateful firewall controlling inbound/outbound traffic
→ Applied to: subnet (all resources in subnet) or NIC (specific VM)

NSG rule components:
Priority:          100-4096 (lower number = higher priority)
Name:              descriptive name
Source:            IP, CIDR range, Service Tag, or Application Security Group
Source port:       * or specific port/range
Destination:       IP, CIDR range, Service Tag, or Application Security Group
Destination port:  80, 443, 3389, * or range
Protocol:          TCP, UDP, ICMP, or Any
Action:            Allow or Deny

Default rules (cannot be deleted, lowest priority):
Inbound:  AllowVNetInbound (65000), AllowAzureLoadBalancerInbound (65001),
          DenyAllInbound (65500)
Outbound: AllowVNetOutbound (65000), AllowInternetOutbound (65001),
          DenyAllOutbound (65500)

Service Tags (pre-defined IP ranges maintained by Microsoft):
Internet:           all public IP addresses
VirtualNetwork:     VNet address space + peered VNets + on-prem
AzureLoadBalancer:  Azure Load Balancer's health probe IP (168.63.129.16)
Storage:            Azure Storage IP ranges
Sql:                Azure SQL IP ranges
AppService:         App Service IP ranges

Application Security Groups (ASG):
→ Group VMs logically (WebServers, AppServers, DBServers)
→ Write NSG rules referencing ASG instead of IP addresses
→ As VMs are added to ASG, rules apply automatically — no IP updates needed

NSG best practices:
→ Apply at subnet level (not NIC) for simpler management
→ Never allow RDP (3389) or SSH (22) from Internet — use Azure Bastion
→ Use Service Tags instead of hard-coded IP ranges
→ Use ASGs for application-tier segmentation

What are Azure Load Balancer and Application Gateway?

Azure Load Balancer (Layer 4 — TCP/UDP):
→ Distributes inbound flows across backend pool VMs
→ Layer 4 (transport layer) — balances based on IP + port
→ No SSL termination, no URL routing, no WAF

Types:
Public LB:   balances internet-facing traffic
Internal LB: balances traffic within a VNet (no public IP)

SKUs:
Basic:   limited features, no SLA, no AZ support — avoid for production
Standard: zone-redundant, secure by default, SLA 99.99%, HTTPS health probes

Standard LB components:
Frontend IP:    public or private IP that receives traffic
Backend pool:   VMs or VMSS that receive distributed traffic
Health probe:   TCP, HTTP, or HTTPS check — removes unhealthy VMs
Load balancing rule: frontend port → backend port mapping
Inbound NAT rule:   direct specific port to specific VM (e.g., RDP to VM1)

Application Gateway (Layer 7 — HTTP/HTTPS):
→ Web traffic load balancer with SSL termination, URL routing, WAF
→ Layer 7 (application layer) — makes routing decisions based on URL/headers

Key features:
SSL termination:     decrypts HTTPS at the gateway — backend can use HTTP
URL path routing:    /images → ImageServers pool, /api → APIServers pool
Host-based routing:  store.contoso.com → StoreFrontend, api.contoso.com → APIBackend
WAF (Web App Firewall): protects against OWASP Top 10 (SQLi, XSS, etc.)
Autoscaling:         Application Gateway v2 scales automatically
Cookie-based affinity: stick user sessions to same backend server

Decision:
Non-HTTP traffic (TCP/UDP)       → Azure Load Balancer
HTTP/HTTPS with URL routing/WAF  → Application Gateway
Global HTTP routing (multi-region) → Azure Front Door
DNS-based routing (any protocol)  → Azure Traffic Manager

What is Azure VPN Gateway and ExpressRoute?

Azure VPN Gateway:
→ Connects on-premises networks to Azure via encrypted VPN tunnel (IPsec/IKE)
→ Requires GatewaySubnet in the VNet

VPN types:
Site-to-Site (S2S):
→ Persistent IPsec tunnel between on-prem VPN device and Azure
→ Traffic encrypted over public internet
→ Bandwidth: up to 10 Gbps (depends on SKU)
→ Use for: branch office connectivity, hybrid workloads

Point-to-Site (P2S):
→ Individual client devices connect to Azure VNet via VPN
→ Supports: OpenVPN, SSTP, IKEv2
→ Use for: remote workers connecting to Azure resources

VPN Gateway SKUs:
Basic:      dev/test, limited bandwidth, no zone-redundancy
VpnGw1-5:  production, varying bandwidth (650 Mbps to 10 Gbps)
VpnGw1-5AZ: zone-redundant (recommended for production)

Azure ExpressRoute:
→ Private, dedicated connection from on-prem to Azure (NOT over internet)
→ Through a connectivity provider (BT, Equinix, Megaport)
→ Bandwidth: 50 Mbps to 100 Gbps
→ Latency: consistent, predictable (dedicated circuit)
→ SLA: 99.95% uptime

ExpressRoute vs VPN:
                    VPN Gateway          ExpressRoute
Connectivity:       Over internet        Private (dedicated)
Encryption:         Yes (IPsec)          No (provider responsibility)
Bandwidth:          Up to 10 Gbps        Up to 100 Gbps
Latency:            Variable             Consistent/low
Cost:               Lower               Higher
Use for:            Dev/test, smaller   Production, regulated,
                    workloads           high bandwidth needs

5. Monitor and Maintain Azure Resources (10–15%)

What is Azure Monitor and what does it collect?

Azure Monitor:
→ Comprehensive monitoring solution for Azure resources
→ Collects: metrics, logs, distributed traces, changes

Data types:
Metrics:    numerical time-series data (CPU %, disk IOPS, request count)
            stored 93 days in Azure Monitor Metrics store
            sub-minute granularity available
Logs:       structured/unstructured text data (activity logs, resource logs)
            stored in Log Analytics workspace (configurable retention)
            queried with Kusto Query Language (KQL)
Traces:     distributed transaction traces (App Insights)
Changes:    resource configuration changes (Change Analysis)

Azure Monitor sources:
Activity Log:    ALL control plane operations in a subscription
                 (who created/deleted/modified which resource)
                 90 days retention, export to Log Analytics for longer
Resource logs:   diagnostic logs from Azure resources
                 (VM guest OS, Storage analytics, SQL query logs)
                 not collected by default — must enable Diagnostic Settings
Guest OS metrics: CPU, memory, disk from inside the VM
                  requires Azure Monitor Agent installed on VM
Application logs: custom app telemetry via Application Insights SDK

Azure Monitor Agent (AMA):
→ Replaces deprecated Log Analytics agent (MMA) and Diagnostics extension
→ Collects: Windows Event Logs, Linux Syslog, performance counters
→ Configured via Data Collection Rules (DCRs) — flexible, per-VM rules
→ Deploy via Azure Policy for all VMs or Arc-connected servers

What is Log Analytics and KQL (Kusto Query Language)?

Log Analytics workspace:
→ Central repository for all Azure Monitor log data
→ All resource diagnostic logs, VM logs, Activity Log sent here
→ Queried using KQL
→ Retention: 30 days default, configurable to 2 years (longer via archive)

KQL basics (most common exam patterns):
// Get all VMs that had high CPU in last 24 hours:
Perf
| where TimeGenerated > ago(24h)
| where ObjectName == "Processor" and CounterName == "% Processor Time"
| where CounterValue > 90
| summarize avg(CounterValue) by Computer, bin(TimeGenerated, 1h)
| order by avg_CounterValue desc

// Find all failed login attempts:
SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4625  // Failed logon
| summarize count() by Account, Computer
| order by count_ desc

// Storage account operations:
StorageBlobLogs
| where TimeGenerated > ago(1d)
| where OperationName == "DeleteBlob"
| project TimeGenerated, CallerIpAddress, Uri, StatusCode

// Join two tables:
AzureActivity
| where OperationNameValue == "Microsoft.Compute/virtualMachines/delete"
| join kind=inner (
    Heartbeat | summarize LastSeen=max(TimeGenerated) by Computer
  ) on $left.ResourceGroup == $right.Computer

KQL operators:
where:      filter rows
project:    select columns
summarize:  aggregate (count, sum, avg, max, min)
order by:   sort results
join:       combine tables
extend:     add calculated columns
ago():      time ago (ago(1h), ago(7d), ago(30d))
bin():      group time into buckets (bin(TimeGenerated, 1h))

What is Azure Backup and how does it work?

Azure Backup:
→ Cloud-based backup service — no on-prem backup infrastructure needed
→ Central management: Recovery Services Vault (classic) or Backup Vault (new)

What can be backed up:
Azure VMs:          full VM backup (OS + data disks) — agent-less
Azure SQL in VM:    workload-aware backup (transaction log backup)
Azure Files:        file share snapshots
Azure Blobs:        operational backup (point-in-time restore)
On-prem Windows:    via MARS agent → files, folders, system state
On-prem servers:    via Azure Backup Server (MABS) or DPM

Azure VM Backup:
→ Snapshot → transferred to Recovery Services Vault
→ Crash-consistent backup: VM point-in-time consistent
→ Application-consistent: quiesce app before snapshot (VSS on Windows)
→ Retention: up to 9,999 recovery points
→ Restore options: Create new VM | Replace existing disk | Restore files

Recovery Services Vault key settings:
Backup policy:      frequency (daily/weekly) + retention schedule
                    (daily: 7-180 days, weekly: up to 5 years)
Soft delete:        deleted backup data retained 14 days — protects against
                    ransomware deletion attacks (cannot be disabled in 14-day window)
Cross-region restore: restore to paired region for DR testing
Immutable vault:    lock vault to prevent deletion of backup data

Azure Site Recovery (ASR):
→ Disaster Recovery — replicate VMs to another Azure region
→ Continuous replication → near-zero RPO (minutes)
→ Failover: redirect traffic to replica VMs in DR region
→ Failback: return to primary region after incident resolved
→ Test failover: validate DR plan without impacting production

RTO vs RPO:
RTO (Recovery Time Objective):  how long before service is restored?
RPO (Recovery Point Objective): how much data loss is acceptable?
ASR typically achieves: RPO < 15 minutes, RTO < 2 hours

6. ARM Templates, Bicep & Automation

What are ARM templates and Bicep?

ARM Templates (JSON):
→ Declarative infrastructure-as-code for Azure resources
→ Define WHAT you want — Azure figures out HOW to create it
→ Idempotent: apply same template multiple times → same result

ARM template structure:
{
  "$schema": "https://schema.management.azure.com/schemas/...",
  "contentVersion": "1.0.0.0",
  "parameters": {         // inputs to the template
    "vmName": { "type": "string", "defaultValue": "myVM" },
    "vmSize": { "type": "string", "allowedValues": ["Standard_D2s_v3"] }
  },
  "variables": {          // computed values
    "storageAccountName": "[concat('storage', uniqueString(resourceGroup().id))]"
  },
  "resources": [          // resources to deploy
    {
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2023-03-01",
      "name": "[parameters('vmName')]",
      "location": "[resourceGroup().location]",
      "properties": { ... }
    }
  ],
  "outputs": {            // values to return after deployment
    "vmPublicIp": { "type": "string", "value": "[reference(...).ipAddress]" }
  }
}

Bicep (recommended over JSON ARM):
→ Domain-specific language that compiles to ARM JSON
→ Cleaner syntax, better IntelliSense, type safety
→ Transpiles to ARM JSON — same capabilities, easier to write

// Bicep equivalent of above:
param vmName string = 'myVM'
param vmSize string = 'Standard_D2s_v3'

var storageAccountName = 'storage${uniqueString(resourceGroup().id)}'

resource vm 'Microsoft.Compute/virtualMachines@2023-03-01' = {
  name: vmName
  location: resourceGroup().location
  properties: {
    hardwareProfile: {
      vmSize: vmSize
    }
    ...
  }
}

output vmId string = vm.id

Deploy ARM/Bicep:
# Azure CLI:
az deployment group create \
  --resource-group "MyRG" \
  --template-file "main.bicep" \
  --parameters vmName="MyVM"

# PowerShell:
New-AzResourceGroupDeployment \
  -ResourceGroupName "MyRG" \
  -TemplateFile "main.bicep" \
  -vmName "MyVM"

What is Azure Automation and what are Runbooks?

Azure Automation:
→ Cloud-based automation service for process automation, configuration,
  update management, and desired state configuration

Components:
Runbooks:          PowerShell or Python scripts run automatically
                   Types: PowerShell, PowerShell Workflow, Python, Graphical
Schedules:         trigger runbooks on a time-based schedule
Webhooks:          trigger runbooks via HTTP POST (from alerts, Logic Apps)
Managed Identity:  authenticate runbooks to Azure without stored credentials
Hybrid Runbook Worker: run runbooks on on-prem servers (not just Azure)

Update Management:
→ Assess and deploy OS updates to Azure VMs and on-prem servers
→ Scheduled maintenance windows for controlled patching
→ Compliance reporting: which VMs are missing updates

Desired State Configuration (DSC):
→ Ensure VMs maintain a specific configuration (PowerShell DSC)
→ E.g., ensure IIS is always installed, specific registry keys are set
→ Azure Automation pulls VM configuration and remediates drift

Common Runbook scenarios:
→ Start/stop VMs on schedule (cost saving)
→ Clean up old snapshots/resources
→ Auto-remediate Azure Policy non-compliance
→ Scale App Service Plan based on business hours
→ Rotate storage account keys and update Key Vault

# PowerShell Runbook example — stop all VMs in a resource group:
Connect-AzAccount -Identity  # Use Managed Identity — no credentials

$vms = Get-AzVM -ResourceGroupName "Dev-RG" -Status |
       Where-Object { $_.PowerState -eq "VM running" }

foreach ($vm in $vms) {
    Stop-AzVM -Name $vm.Name -ResourceGroupName "Dev-RG" -Force
    Write-Output "Stopped: $($vm.Name)"
}

7. Scenario-Based Questions

Scenario: Design a highly available web application architecture on Azure.

Requirement: 99.99% SLA, auto-scaling, DDoS protection, private backend

Architecture:
Internet
  ↓
[Azure DDoS Protection Standard] — protects public endpoint
  ↓
[Application Gateway v2 + WAF] — Zone-redundant, SSL termination,
  ↓                               URL routing, OWASP protection
[VM Scale Set — WebTier]        — Windows/Linux web servers
  3 zones × auto-scale (2-20 instances)
  Standard LB (internal) for health distribution
  ↓
[Internal Load Balancer]        — distributes to app tier
  ↓
[VM Scale Set — AppTier]        — application servers
  3 zones × auto-scale (2-10 instances)
  ↓
[Azure SQL — Business Critical] — zone-redundant, auto-failover group
  + Azure Cache for Redis        — session cache, query cache

Networking:
VNet: 10.0.0.0/16
  WebSubnet:  10.0.1.0/24 (App Gateway + Web tier)
  AppSubnet:  10.0.2.0/24 (App tier)
  DataSubnet: 10.0.3.0/24 (SQL private endpoint)
  GWSubnet:   10.0.4.0/27 (for future VPN/ExpressRoute)

Security:
NSG on WebSubnet:  allow 80/443 from Internet, deny all else inbound
NSG on AppSubnet:  allow only from WebSubnet (no direct internet)
NSG on DataSubnet: allow only from AppSubnet on SQL port 1433
Private Endpoint:  Azure SQL accessed via private IP in DataSubnet
Bastion:           Azure Bastion for admin RDP/SSH (no public IP on VMs)
Key Vault:         store connection strings, API keys (no secrets in config)
Managed Identity:  VMs access Key Vault and Storage — no credentials in code

Scenario: A VM cannot connect to Azure SQL Database. How do you troubleshoot?

  1. Check NSG rules: VM's subnet NSG and NIC NSG — is outbound port 1433 allowed to the SQL server IP or Service Tag Sql?

  2. Check SQL firewall: Azure SQL → Networking → is the VM's subnet added as a VNet rule (Service Endpoint) or is there a private endpoint? Is public access disabled?

  3. Check routing: is there a custom UDR (User Defined Route) redirecting SQL traffic through a firewall/NVA? Ensure the route to SQL doesn't black-hole traffic.

  4. Test connectivity from VM:

    # Test TCP connection on port 1433:
    Test-NetConnection -ComputerName "myserver.database.windows.net" -Port 1433
    # Check for: TcpTestSucceeded: True
    
  5. Check Private DNS: if using Private Endpoint, the VM must resolve myserver.database.windows.net to the private IP (10.x.x.x), not the public IP. Check if the VNet is linked to the Private DNS Zone.

  6. Check SQL authentication: connection string correct? Entra ID auth vs SQL auth? User has permissions on the database?

  7. Network Watcher — IP Flow Verify: Network Watcher → IP Flow Verify — simulate traffic from VM to SQL and see which NSG rule is blocking.


Scenario: Reduce Azure costs for a development environment running 24/7.

  1. Auto-shutdown: enable VM auto-shutdown at 6pm (or use Azure Automation runbook) → restart at 8am. Saves ~58% of VM compute cost.

  2. Spot VMs for dev workloads: use Azure Spot VMs for dev/test (up to 90% discount) — acceptable for non-critical workloads that can tolerate interruption.

  3. B-series VMs: switch dev VMs to B-series (burstable) — much cheaper than D-series for low-average-load workloads.

  4. Dev/Test pricing: activate Dev/Test subscription pricing for non-production workloads — discounted Windows Server and SQL licensing.

  5. Azure Hybrid Benefit: if you have existing Windows Server or SQL Server licences with Software Assurance → apply Hybrid Benefit on VMs to eliminate licence cost.

  6. Reserved Instances: for always-on resources (build server, dev database) → 1-year reservation saves ~40%.

  7. Right-size: Azure Advisor Cost recommendations → identify over-provisioned VMs with <5% average CPU utilisation → downsize.

  8. Storage lifecycle policies: dev storage → Cool tier after 30 days, Archive after 90 days for old test data.

  9. Delete unused resources: set Azure Policy to audit/alert on resources without required tags. Runbook: delete resources tagged Environment=Dev older than 30 days with no activity.


Scenario: How do you implement a backup strategy for Azure VMs in a regulated industry?

Requirements: 7-year retention, immutable backup, cross-region DR, audit trail

Implementation:
1. Recovery Services Vault per region (Primary + Secondary)

2. Backup policy:
   Daily backup:   retained 30 days
   Weekly backup:  retained 1 year (every Sunday)
   Monthly backup: retained 7 years (first Sunday of month)
   Yearly backup:  retained 7 years (January 1st)

3. Soft delete: enabled (default 14 days)
   Extended soft delete: 180 days for regulated environments

4. Immutable vault (locked):
   → Once locked, backup data cannot be deleted or modified
   → Protects against ransomware that tries to delete backups
   → Enable: Vault → Properties → Immutability → Locked

5. Cross-region restore: enabled on vault
   → Restore to secondary region for DR testing

6. Azure Monitor + Log Analytics:
   → Diagnostic settings on vault → Log Analytics
   → Alert on: backup job failures, unexpected deletions
   → KQL query: AzureDiagnostics | where Category == "AzureBackupReport"
                 | where OperationName == "DeleteBackupData"

7. Azure Backup Reports (Power BI dashboard):
   → Track compliance: which VMs are not backed up?
   → Report on backup storage consumption
   → Evidence for compliance audits

8. Azure Policy:
   → "Azure Backup should be enabled for Virtual Machines" initiative
   → Automatically enrol new VMs in backup policy

8. Cheat Sheet — Quick Reference

AZ-104 Exam Domain Weights

Domain                                      Weight    Priority
Manage Azure identities and governance      20-25%    ⭐⭐⭐⭐⭐
Deploy and manage Azure compute resources   20-25%    ⭐⭐⭐⭐⭐
Implement and manage virtual networking     15-20%    ⭐⭐⭐⭐
Implement and manage storage                15-20%    ⭐⭐⭐⭐
Monitor and maintain Azure resources        10-15%    ⭐⭐⭐

VM Availability Quick Reference

Protect against:              Use:
Hardware failure in rack      Availability Set (2+ fault domains)
Datacenter failure            Availability Zone (2+ VMs in 2+ zones)
Region failure                Azure Site Recovery (replicate to paired region)
App crashes (load balance)    Azure Load Balancer or App Gateway

SLAs:
Single VM (Premium SSD):  99.9%
Availability Set:         99.95%
Availability Zone (2+):   99.99%
Zone + Load Balancer:     99.99%

Storage Tier Decision

Data access frequency:        Use tier:
Multiple times per day        Hot
Once per 30 days              Cool
Once per 90 days              Cold
Once per year or less         Archive (+ rehydration time)

Redundancy decision:
No DR needed:                 LRS (cheapest)
Zone outage protection:       ZRS (recommended for most prod)
Region outage protection:     GRS or GZRS
Read access to secondary:     RA-GRS or RA-GZRS

Networking Quick Reference

Resource                 Purpose
VNet                     Private network — your isolated Azure network
Subnet                   Subdivide VNet — group resources by tier/function
NSG                      Stateful firewall on subnet or NIC
ASG                      Logical grouping of VMs for NSG rules
VNet Peering             Connect VNets privately (non-transitive)
Private Endpoint         Private IP for PaaS services in your VNet
Service Endpoint         Route PaaS traffic via VNet backbone
Azure Bastion            Secure RDP/SSH without public IP
Azure Firewall           Managed, stateful L4-L7 firewall (centralised)
Load Balancer            L4 TCP/UDP load balancing
Application Gateway      L7 HTTP/HTTPS with WAF and URL routing
VPN Gateway              Encrypted VPN to on-prem (over internet)
ExpressRoute             Private dedicated circuit to on-prem
Azure Front Door         Global HTTP load balancing + CDN + WAF
Traffic Manager          DNS-based global routing (any protocol)

Useful Azure CLI Commands

# Login and set subscription:
az login
az account set --subscription "Production"

# Create resource group:
az group create --name "Prod-RG" --location "uksouth"

# Create VM:
az vm create --resource-group "Prod-RG" --name "MyVM" \
  --image "Win2022Datacenter" --size "Standard_D2s_v3" \
  --admin-username "azureadmin" \
  --generate-ssh-keys

# Start/Stop VM:
az vm start --resource-group "Prod-RG" --name "MyVM"
az vm stop  --resource-group "Prod-RG" --name "MyVM"
az vm deallocate --resource-group "Prod-RG" --name "MyVM"

# Create storage account:
az storage account create --name "mystorageacc" \
  --resource-group "Prod-RG" --location "uksouth" \
  --sku "Standard_ZRS" --kind "StorageV2"

# Create VNet and subnet:
az network vnet create --resource-group "Prod-RG" \
  --name "MyVNet" --address-prefix "10.0.0.0/16"
az network vnet subnet create --resource-group "Prod-RG" \
  --vnet-name "MyVNet" --name "WebSubnet" --address-prefix "10.0.1.0/24"

# Apply resource lock:
az lock create --name "ProdLock" --resource-group "Prod-RG" \
  --lock-type "CanNotDelete"

# Deploy Bicep:
az deployment group create \
  --resource-group "Prod-RG" --template-file "main.bicep"

# Query logs (KQL via CLI):
az monitor log-analytics query \
  --workspace "MyWorkspace" \
  --analytics-query "AzureActivity | where ActivityStatus == 'Failed' | take 10"

Top 10 Tips

  1. ARM is the control plane for everything — every Azure action (Portal, CLI, PowerShell, Terraform) goes through ARM. Understanding ARM hierarchy (Management Group → Subscription → Resource Group → Resource) is fundamental to every governance, RBAC, and policy question.

  2. Policy controls WHAT, RBAC controls WHO — Azure Policy enforces resource configuration (must use managed disks, must be in specific region). RBAC controls who can deploy/manage resources. Both are needed — not interchangeable.

  3. Availability Zones over Availability Sets for new deployments — Availability Zones protect against datacenter failure (99.99% SLA). Availability Sets only protect within one datacenter (99.95% SLA). Always recommend AZs for production.

  4. Private Endpoints over Service Endpoints for production — Service Endpoints route traffic via backbone but PaaS still has a public endpoint. Private Endpoints give PaaS a private IP in your VNet — you can completely disable public access. More secure, more enterprise.

  5. ZRS for most production storage — ZRS replicates across 3 availability zones (survives datacenter failure). LRS only replicates within one datacenter. GRS/GZRS for cross-region requirements. Knowing the right tier for the scenario is heavily tested.

  6. Blob lifecycle management policies for cost control — move blobs from Hot → Cool → Cold → Archive automatically based on age. This pattern (with the day thresholds) is a common scenario question.

  7. NSG is stateful — response traffic is automatic — if you allow inbound port 80, the response traffic is automatically allowed outbound. You don't need a separate outbound rule for responses. Only need rules for initiated connections.

  8. Azure Bastion eliminates public IP on VMs — never open RDP (3389) or SSH (22) to the internet from an NSG. Use Azure Bastion (deployed in AzureBastionSubnet) for secure RDP/SSH via the Azure Portal. This is the correct answer to any "how do you securely administer VMs" question.

  9. Soft delete + Immutable vault = ransomware protection for backups — soft delete keeps deleted backups for 14 days. Immutable vault (locked) prevents backup data deletion entirely. Both are the answer to "how do you protect backups against ransomware."

  10. Bicep over JSON ARM for new IaC — Bicep is the modern, recommended IaC language for Azure (compiles to ARM JSON). Cleaner syntax, type safety, better tooling. Know how to deploy Bicep via CLI (az deployment group create --template-file main.bicep).



Featured Post

Scoping Microsoft Graph Mail Permissions to a Single Mailbox with Exchange Online RBAC for Applications

Automations that read reports from a shared mailbox or send notifications from a service mailbox usually run as a daemon application. They ...

Popular posts