Skip to main content

Deploying Azure Web App Monitoring & Alerts Using Terraform

Published 16 min readMarkdown
Deploying Azure Web App Monitoring & Alerts Using Terraform

Hello everyone, Tech Bro here again!

I recently finished my CloudNorth Final Bootcamp Project, and trust me, it was both time-consuming and exciting. I’m really pleased it turned out to be a success and is now getting the attention it deserves on Hashnode.

After taking a short break to recharge, I’m back with something fresh. Since I’ve already covered several projects on AWS, I thought it was the right time to continue showcasing my multi-cloud skills by switching to Azure.

Today, we’ll explore Azure Monitoring with a new project titled “Deploying Azure Web App Monitoring & Alerts Using Terraform.” In this project, I set up an Azure Web App monitoring solution using Terraform and Terraform Cloud. The aim is to provision everything as Infrastructure as Code (IaC), including the App Service, Application Insights, Log Analytics Workspace, Diagnostic Settings, and Alert Rules, without hardcoding sensitive values like my subscription ID. Once deployed, I moved into the Azure Portal to check the setup, configure email alerts through Action Groups, and trigger simulated failures to test the monitoring pipeline.

This project is part of my cloud and DevOps journey, where I document practical projects across AWS, Azure, Terraform, Jenkins, Ansible, and Kubernetes. Each project is hands-on, ready for my portfolio, and designed to reflect the workflows I’d encounter in a professional cloud and DevOps role.

Please note: I partnered with AI to generate clean and precise Terraform code for this project. This is one of the key advantages of using AI: it gives you the freedom to speed up code generation and seek guidance when needed, while still keeping you in full control of building, customizing, and delivering the final solution.

Introduction

Monitoring is one of the most important aspects of running applications in the cloud. Without proper visibility, you’re in the dark. You won’t know when your app is down, when performance is slowing, or when errors are accumulating. In production, this can lead to unhappy users and lost revenue.

In this project, I built a complete Azure Web App Monitoring stack using Terraform and Terraform Cloud. Instead of navigating the portal, I provisioned everything as Infrastructure as Code (IaC). This approach ensures the setup is consistent, repeatable, and version-controlled.

The stack includes:

i. Azure App Service (Linux Web App hosting)

ii. Application Insights for performance and telemetry

iii. Log Analytics Workspace to centralize logs

iv. Diagnostic Settings for capturing metrics and logs

v. Action Group with email alerts to notify me when failures occur

vi. Metric alerts for CPU usage and HTTP 5xx errors

vii. Availability test to simulate uptime from multiple regions

Once I deployed the infrastructure with Terraform, I used the Azure Portal GUI to validate telemetry, run alert simulations, and test how Azure Monitor reacts when the app misbehaves.

This project is unique because it demonstrates the entire lifecycle of monitoring: from provisioning with Terraform, to validating in the portal, to documenting and version-controlling the setup on GitHub.

As always, I’ll break everything down step by step, from the code to the GUI, so you can replicate it in your own Azure environment.

Prerequisite

Before starting this project, ensure the following requirements are met:

  1. Terraform Setup

Install Terraform CLI version 1.6.0 or higher.
Have a Terraform Cloud account ready.
Create a new organization named: azure-monitoring-iac-ORG.
Inside that organization, create a workspace named: "project8-azure-monitor-iac." Ensure the workspace is set to CLI-driven runs.

  1. Azure Subscription

You need an active Azure subscription with Owner or Contributor permissions.
Install Azure CLI and log in using: "az login."

  1. Environment Variables in Terraform Cloud

Add these variables in your Terraform Cloud workspace under Variables → Environment Variables:

  • ARM_CLIENT_ID

  • ARM_CLIENT_SECRET

  • ARM_SUBSCRIPTION_ID

  • ARM_TENANT_ID

Mark sensitive values as sensitive in Terraform Cloud.

  1. Git + Version Control

Create a GitHub repository named: azure-monitoring-iac.
This repository will contain only Infrastructure-as-Code files (.tf, .gitignore, README.md).
No Azure subscription ID, tenant, or secrets will appear in the code. Everything is pulled securely through environment variables to maintain industry security standards.

  1. Email for Alerts

Provide a working email for Azure Monitor to send alert notifications.
In this project, we set up: contact@techbrodev.com.ng.
You can update this later in variables.tf if needed.

  1. Basic Knowledge Required

You should have familiarity with Azure services like App Service, Application Insights, Log Analytics, and Monitor.
An understanding of Terraform basics, such as providers, variables, outputs, and remote state, is necessary.
Be open to exploring both Infrastructure as Code (Phase 1) and the Azure Portal GUI (Phase 2) for testing alerts.

With these prerequisites set up, you’re ready to provision the entire monitoring stack using Terraform. Then, you can switch to the Azure Portal for real-time alert simulation and troubleshooting.

Project Phases

This project is structured into three clear phases:

Phase 1: Terraform IaC with Terraform Cloud (no subscription ID in code)

Phase 2: Azure Portal GUI validation and alert simulations

Phase 3: Version control and portfolio documentation

Phase 1, Terraform IaC with Terraform Cloud

Goal: Set up all Azure monitoring resources using Terraform while saving remote state in Terraform Cloud. I handle credentials and subscription IDs through environment variables, so there's nothing sensitive in the code.

Steps:

  1. Prepare Project Folder

Folder: project8-azure-monitor-iac

Files: versions.tf, providers.tf, variables.tf, main.tf, outputs.tf, .gitignore, README.md

  1. Configure Terraform Cloud

Organization: azure-monitoring-iac-ORG

Workspace: project8-azure-monitor-iac (CLI-driven runs)

Add sensitive environment variables:

ARM_CLIENT_ID

ARM_CLIENT_SECRET

ARM_SUBSCRIPTION_ID

ARM_TENANT_ID

Optional Terraform variables:

location = "West Europe"

alert_email = "contact@techbrodev.com.ng"

cpu_alert_threshold = 10

web_test_locations = ["emea-nl-ams-azr","emea-gb-db3-azr","us-ca-sjc-azr", "emea-ru-msa-edge”, "emea-se-sto-edge"]

  1. Edit Versions File

Update the organization field in versions.tf with your chosen Terraform Cloud organization name.

Also, update the workspace name to whatever you prefer.

  1. Authenticate & Initialize

    terraform login
    terraform init

  2. Validate, Plan & Apply

    terraform validate

    terraform plan
    terraform apply

Please Note on Azure Authentication.

For this project, I didn’t use az login. Instead, I set up all necessary Azure credentials (like ARM_CLIENT_ID, ARM_CLIENT_SECRET, ARM_SUBSCRIPTION_ID, and ARM_TENANT_ID) as environment variables in Terraform Cloud. This allows Terraform Cloud to authenticate directly with Azure for me. Since the variables handle authentication, there’s no need to run az login locally.

  1. Quick Validation

Open the webapp_url in a browser.

Check the Azure Portal: The resource group and resources should be active.

Deliverables:

Live App Service with monitoring enabled

Remote state in Terraform Cloud

Clean codebase without a subscription ID

Phase 2, Azure Portal GUI Work & Alert Simulations

Goal: Check telemetry, trigger alerts, and gather screenshots for portfolio evidence.

Steps:

  1. Verify App Insights & Diagnostic Settings

Make sure App Insights is linked to Log Analytics.

Ensure Diagnostic Settings send logs and metrics to Log Analytics.

  1. Confirm Action Group

Action Group created (ag-project8) with email: contact@techbrodev.com.ng.

  1. Check Availability Test

Web test (webtest-project8) is active in App Insights.

Success = HTTP 200.

  1. Trigger Alert Simulations

CPU %: Open multiple browser tabs to quickly hit the small SKU threshold.

HTTP 5xx: Add a fake startup command, visit the site, then revert changes.

Availability: Change the test URL to /does-not-exist, then revert.

  1. Validate Alerts Fired

Azure Monitor shows active and resolved alerts.

Emails are received through the Action Group.

Application Insights displays failures and logs.

  1. Capture Screenshots

Web App Overview with URL

App Insights and Diagnostic Settings

Action Group page

Alert rule details

Availability test results

Alerts list showing fired alerts

Email notification evidence

Deliverables:

Fired alerts and emails

Screenshot pack for README and blog

Phase 3, Version Control & Documentation

Goal: Package everything into a portfolio-grade repository with clear documentation.

Steps:

  1. Ensure .gitignore is Present

Exclude .terraform/, .tfstate, *.tfvars, keys, and OS junk.

  1. Initialize Git & Push

git init
git remote add origin
https://github.com/stillfreddie/azure-monitoring-iac.git
git
add .
git commit -m "Project 8 IaC Azure Monitor on App Service"
git push -u origin main

  1. Theory Corner:

  2. Disclaimer

  3. Cleanup

terraform destroy

Deliverables:

Complete repository on GitHub

Portfolio-ready README.md

Let’s get Started.

Phase 1: Terraform IaC with Terraform Cloud

Step 1: Prepare Project Folder

What I will do right now is head to my local host, open VSCODE, then click on file----> Open Folder----> then locate my Project folder named project8-azure-monitor-iac, then click Open Folder.

Step 2: Configure Terraform Cloud

Once my Project folder is prepared and uploaded to VSCODE, the next step is to configure Terraform Cloud. I already have a Terraform Cloud account, so I will go to Terraform Cloud and log in with my credentials. I will then proceed to the Organization I created for this project, which is named azure-monitoring-iac-ORG. After that, I will access the Workspace named project8-azure-monitor-iac. I made sure to create a CLI-driven Workspace.

Now it's time to add my Azure Sensitive environment variables, which are :

ARM_CLIENT_ID

ARM_CLIENT_SECRET

ARM_SUBSCRIPTION_ID

ARM_TENANT_ID

Following Industry Security Standards, I have marked all my Variables as Sensitive.

Optional Terraform variables:

location = "West Europe" Defines the Azure region where all resources will be deployed.

alert_email = "contact@techbrodev.com.ng" Email address that will receive Azure Monitor alert notification

cpu_alert_threshold = 10 CPU usage percentage that triggers an alert (kept low here so alerts fire easily for demo).

web_test_locations = ["emea-nl-ams-azr","emea-uk-lon-azr","emea-se-sto-azr"] List of global Azure regions where synthetic availability tests will ping your app.

web_test_locations = [

"emea-nl-ams-azr", # Amsterdam, Netherlands (Azure region)

"emea-uk-lon-azr", # London, United Kingdom (Azure region)

"emea-se-sto-azr" # Stockholm, Sweden (Azure region)

These non-secret Variables Above are Optional Terraform Variables. In this project, we already defined defaults for non-secret variables inside variables.tf. This means you don’t need to set them again in Terraform Cloud; Terraform will automatically use the values provided in code.

Step 3: Edit Providers File

We will update the organization field in providers.tf with our chosen Terraform Cloud organization name. For this Project, it’s called azure-monitoring-iac-ORG, and the Workspace name is project8-azure-monitor-iac

Step 4: Authenticate and Initialize

Before running any plans, we need to authenticate Terraform with Terraform Cloud and initialize the working directory.

Run the following commands from inside your project folder:

terraform login
terraform init

terraform login opens a browser window and asks you to create a Terraform Cloud API token. This helps secure communication between your local CLI and Terraform Cloud.

Please note: For security reasons, I will not be documenting the step where Terraform opens a browser window and prompts you to create a Terraform Cloud API token.

terraform init downloads the necessary provider plugins, in this case, azurerm, and sets up the remote backend using the settings in providers.tf.

Step 5: Validate, Plan & Apply

Now that Terraform is initialized, it’s time to validate the configuration and apply it to Azure.

Run the following commands:

terraform validate

terraform plan

terraform apply

terraform validate: checks for syntax errors or misconfiguration in your .tf files.

terraform plan: shows you a preview of what Terraform will create in Azure without actually deploying. This step is like a dry run, so you can confirm everything looks correct.

terraform apply --auto-approve: executes the plan and provisions the resources. I added —auto-approve to Skip the YES Prompt.

Once complete, Terraform will output the values we defined in outputs.tf, including the webapp URL, resource group name, and Log Analytics Workspace ID.

Please note: For security reasons, I will now document my terraform output. Once Terraform apply is complete on the CLI the outputs will be available.

You can now open the web app URL in your browser to confirm that the default page loads.

Step 6: Quick Validation

Open the webapp_url in a browser.

Check the Azure Portal: The resource group and resources should be active.

Deliverables:

Live App Service with monitoring enabled.

Remote state in Terraform Cloud.

Clean codebase without hard-coding a subscription ID.

Theory Corner for Phase 1

What We Built

A Resource Group, App Service Plan, Linux Web App, Application Insights, Log Analytics Workspace, and Action Group, all created with Terraform.

We added diagnostic settings and a CPU metric alert directly in Terraform.

Error Encountered

When we tried to add an availability alert in Terraform, we received this error:

microsoft.insights/webtests is not a supported platform metric namespace

This means Terraform can’t directly connect metric alerts to Web Tests.

How We Fixed It

Instead of using the GUI, we used Azure CLI to create the availability alert after applying Terraform.

Command used:

az monitor metrics alert create --name alert-availability-drop --resource-group rg-project8-monitor --scopes "/subscriptions/<sub-id>/resourceGroups/rg-project8-monitor/providers/microsoft.insights/components/appi-project8" --condition "avg availabilityResults/availabilityPercentage < 80" --window-size 5m --evaluation-frequency 1m --action "/subscriptions/<sub-id>/resourceGroups/rg-project8-monitor/providers/microsoft.insights/actionGroups/ag-project8" --description "Availability below 80 percent"

This linked our App Insights availability results to the Action Group for the email alert.

Key Takeaway:

Use Terraform for the main infrastructure and simple metric alerts.

Use CLI when Terraform doesn’t support certain metrics, like Availability.

Phase 2: Azure Portal GUI Work & Alert Simulations

Goal

The purpose of this phase was to test monitoring and alerting in action. While Phase 1 (Terraform + CLI) took care of provisioning, this stage concentrated on the Azure Portal GUI to:

Inspect telemetry data from Application Insights and Log Analytics.

Trigger and observe alerts about CPU usage, 5xx errors, and availability.

Capture visual evidence with screenshots for portfolio presentation.

Step 1: Verify App Insights & Diagnostic Settings

i. Open App Insights Resource

In the Azure Portal, search for Application Insights.

Click on appi-project8 under resource group rg-project8-monitor

In the Overview tab, confirm it shows telemetry.

ii. Make sure App Insights is linked to Log Analytics Workspace.

Inside the App Insights blade, look at the Properties (left sidebar).

Find Log Analytics Workspace → confirm it’s showing your workspace

iii. Ensure Diagnostic Settings send logs and metrics to Log Analytics.

Still in the App Insights blade, scroll to Diagnostic settings.

Open the configured setting.

Still in the App Insights blade, scroll to Diagnostic settings.

Open the configured setting if No Diagnostic Setting is configured

If none exist, click + Add diagnostic setting.

Under Logs, check AllLogs (this covers requests, traces, availability, etc.).

Under Destination details, select Send to Log Analytics workspace.

Pick your subscription (e.g., Azure Subscription 1).

Choose your Log Analytics workspace → law-project8.

Under Metrics, select AllMetrics

Click Save.

Now all telemetry (logs + metrics) will be streamed into your Log Analytics workspace for queries and alerting.

Step 2. Confirm Action Group

I already created an Action Group named ag-project8.

This Action Group is configured to send notifications to my email: contact@techbrodev.com.ng

Step 3: Check Availability Test

The web test named webtest-project8 is active in Application Insights.

This test continuously checks if the app is reachable.

Success criteria: Response returns HTTP 200 (OK).

If the app fails the test, the availability alert (alert-availability-drop) will trigger via the Action Group.

Step 4: Trigger Alert Simulations

Now that our alerts are in place, let’s force some failures to see them in action

i. CPU % Alert Simulation

Open multiple browser tabs pointing to your web app (app-project8).

Simulating Load (Requests Spike)

Since my App Service Plan SKU doesn’t expose the CPU % metric, I used Requests Count as the alternative load simulation metric.

I went into Application Insights → Metrics.

Selected:

Namespace: App Service Standard Metrics

Metric: Requests

Aggregation: Sum

I then opened multiple tabs and refreshed the app repeatedly.

The Requests metric spiked up (arrow at ~35), proving that telemetry is flowing into Application Insights.

ii. Trigger Alert Simulations

CPU %: Open multiple browser tabs to quickly hit the small SKU threshold.

ii. HTTP 5xx Alert Simulation

iii. Availability Alert Simulation

Open App Insights → Availability → webtest-project8.

Edit the test URL: change from / to /does-not-exist.

Save → the test will immediately fail with HTTP 404.

Alert alert-availability-drop should fire because availability % falls below 80.

Step 5: Validate Alerts Fired

Azure Monitor shows active and resolved alerts.

Emails are received through the Action Group.

Application Insights displays failures

Application Insights displays logs.

Theory Corner For Phase 2: GUI Work & Alert Simulations

This phase demonstrates how Azure Monitor, Application Insights, and Action Groups collaborate in real-world monitoring.

Diagnostic Settings: These send telemetry (logs, metrics, traces, availability data) from App Insights to Log Analytics for centralized querying and long-term analysis. Without them, data stays in App Insights only.

Action Groups: They define who receives notifications and how (email, SMS, webhook, etc.) when an alert rule triggers. In this project, email alerts were set up to contact@techbrodev.com.ng.

Alert Rules: These act as logic gates. They continuously check metrics (CPU %, HTTP errors, availability %) and trigger when thresholds are crossed.

Simulations:

High traffic (requests spike) tests how alerts handle load.

Fake 5xx errors simulate app crashes or misconfiguration.

Broken availability test URL shows how monitoring detects downtime from the user’s perspective.

Lifecycle: Alerts go through a lifecycle of Fired, Acknowledged, and Resolved. This shows not only problems but also auto-recovery.

Key Takeaway: Phase 2 confirmed that the monitoring stack does more than collect data. It actively finds issues, triggers alerts, and provides evidence (emails, logs, graphs) to help engineers respond quickly.

Phase 3, Version Control & Final Documentation

Now that the infrastructure and alert simulations are functioning, the next step is to make it portfolio-ready by implementing proper version control and clean documentation.

Step 1: Ensure .gitignore is Present.

When working with Terraform and Azure, keeping your repo clean and secure is just as important as the code itself. A good .gitignore stops sensitive or unnecessary files from being committed.

Here’s the recommended .gitignore for this project:

Step 2: Initialize Git & Push to GitHub

With .gitignore in place, the next move is to version control your Infrastructure as Code and push it to GitHub. This makes your project professional, reusable, and portfolio-ready.

On VSCODE Run the following commands from inside your project folder (project8-azure-monitor-iac):

Initialize git with the command below.

git init

Connect to the GitHub repo with the command below.

git remote add origin https://github.com/stillfreddie/azure-monitor-iac.git

Stage all files

git add .

Commit changes with a clean message

git commit -m "Project 8 IaC Azure Monitor on App Service with Terraform"

Push to GitHub (main branch)

git push -u origin main

Verify Successful Push to GitHub Repository.

Theory Corner For Phase 3: Version Control & Final Documentation

Version control makes your Infrastructure-as-Code (IaC) easy to track, share, and prepare for your portfolio. With Git and GitHub, each change is kept as a history, which simplifies collaboration and showcasing your work.

Key concepts:

  1. .gitignore
    Exclude sensitive or unimportant files like .terraform/, .tfstate, *.tfvars, and unnecessary OS files. This keeps the repository clean and secure.
  1. Repository Initialization
    Using git init starts version control in your local folder. You connect it to GitHub with git remote add origin to make your project publicly accessible.
  1. Branching Best Practices
    Modern repositories use main instead of master. Always rename the default branch with git branch -M main.
  1. Commit & Push Workflow

Stage files with git add .

Save a snapshot using git commit -m "message"

Publish to GitHub by running git push -u origin main

  1. Documentation = Proof of Work
    A strong README.md clarifies project goals, structure, and lessons learned. This turns raw Terraform code into a portfolio piece that recruiters and hiring managers can trust.

Conclusion

This project showed how to design, implement, and validate end-to-end monitoring on Azure App Service using Infrastructure as Code (Terraform).

We achieved:

Automated provisioning of App Service, Application Insights, Log Analytics, and Action Groups.

Configuration of availability tests and alert rules through both Terraform and Azure CLI, which proved that we can manage cloud resources flexibly.

Practical alert simulations (CPU, HTTP 5xx, and Availability) confirmed that telemetry pipelines, alert triggers, and action groups functioned as expected.

Strong version control practices with Git and GitHub ensured that the project is reusable and ready for my portfolio.

With this, monitoring is no longer just a concept; it’s a real system that can track performance, detect issues, and notify stakeholders in real time.

This project is now part of my DevOps portfolio, demonstrating my ability to combine IaC, cloud monitoring, and documentation in a practical workflow.

Disclaimer:

This project was designed and implemented by me using real DevOps workflows. I used AI as an assistant for infrastructure generation and syntax accuracy, but I customized, deployed, and documented everything manually as part of my learning and real-world simulation.

“I push code, I scale clouds, and I eat amala"

About the author

  • I’m a Cloud and DevOps Engineer who loves building scalable infrastructure and automating deployments. My journey began a few years ago. Since then, I have completed several hands-on projects using AWS, Azure, Terraform, Jenkins, Ansible, Kubernetes, and various monitoring tools. I share what I learn to track progress, motivate other learners, and showcase practical DevOps workflows that reflect real-world situations. My long-term goal is to create cloud solutions that are reliable, cost-effective, and easy to scale. When I’m not coding or working on cloud projects, I spend my time learning, writing, and connecting with fellow tech enthusiasts.

No comments yet. Be the first to comment.