📋 In This Post
Lab Overview
Almost everything written about Azure Monitor managed service for Prometheus
assumes Kubernetes. The add-on scrapes AKS. The sample dashboards are cluster
dashboards. The rule groups take a clusterName. Read enough of it
and you come away believing the managed service is a Kubernetes
feature.
It isn't, and this week is the test. There is no cluster anywhere in
it. A self-managed Prometheus runs on one ordinary Linux VM and pushes
its metrics into an Azure Monitor workspace using Prometheus's own
remote_write. Microsoft documents exactly this: remote-write sends
metrics "from self-managed Prometheus running in your Kubernetes clusters
or virtual machines", and user-assigned managed identity authentication
lists Azure VM/VMSS among its supported targets.
The objective, in one sentence: get a metric produced on a VM into Azure's managed Prometheus store and prove it arrived, without a password, a certificate or a client secret existing anywhere. Expected outcome: a series queryable from the workspace carrying labels identifying the VM it came from, a Terraform-defined alert and recording rule evaluating against it, and a Grafana panel drawing the same data.
| Difficulty | Intermediate |
|---|---|
| Completion time | About 90 minutes, of which 30 is waiting — see Troubleshooting |
| Deployment | Terraform, one apply, state in HCP Terraform (local execution) |
| Source | week-11-managed-prometheus · runbook in LAB.md |
Cloud Services and Concepts
| Service | Purpose here | What it is |
|---|---|---|
| Azure Monitor workspace | stores the Prometheus time series | Azure's store for Prometheus-style metrics — numbers sampled on a schedule, each tagged with labels, kept as a series over time. You write series into it and query them back with PromQL. It is its own resource type (Microsoft.Monitor/accounts) with its own data, permissions and bill, and it is not the Log Analytics workspace that holds logs: Microsoft's note is that Azure Monitor workspaces "currently contain only metrics related to Prometheus". |
| Data collection rule (DCR) | accepts the write; its paired endpoint supplies the URL host, the rule only the path | Azure Monitor's ingestion contract. A DCR is a resource that declares what telemetry is accepted, how it should be shaped on the way in, and which workspace it lands in — so the pipeline is something you version, grant permissions on and reuse, rather than a setting hidden in a resource. Every Azure Monitor workspace is given one automatically. |
| User-assigned managed identity | what Prometheus authenticates as | An identity in Microsoft Entra that Azure creates and whose credentials Azure rotates, so nothing is ever stored by you. Attach it to a resource and code on that resource asks the local instance metadata service for a token. User-assigned means the identity is its own Azure resource with its own lifetime — delete the VM and the identity and its role assignments survive. A system-assigned one is born and deleted with its resource. |
Prometheus remote_write |
ships the samples | A standard Prometheus feature. Rather than only keeping samples on its own disk, a Prometheus server streams every sample it scrapes to a remote HTTP endpoint. It is how Prometheus hands long-term storage to something else while still doing the collecting itself. The azuread: block is what teaches it to authenticate to Azure. |
| Prometheus rule group | alerts and recording rules, as code | A set of PromQL rules that Azure evaluates on a schedule against a workspace. Two kinds, and they are often confused: a recording rule precomputes an expression and stores the answer under a new metric name, so dashboards read a cheap number instead of recalculating; an alert rule fires when its expression stays true for a given period. |
| Azure Managed Grafana | draws it | Grafana — the open-source dashboard tool — run, patched and signed-in-to by Azure. Grafana holds no data of its own: every panel is a live query against a data source you point it at. Azure can wire the workspace in as one at deploy time. |
Architecture and Workflow
- Prometheus on the VM scrapes its own
/metricsevery 30 seconds. - It asks the instance metadata service for a token, because a user-assigned managed identity is attached to the VM.
- It
remote_writes the samples over HTTPS to the metrics ingestion endpoint of the workspace's data collection rule. - The DCR accepts the write — but only because the identity holds Monitoring Metrics Publisher on that rule.
- The workspace stores the series and stamps its own resource id onto every one of them.
- A Prometheus rule group evaluates one recording rule and one alert rule against the workspace.
- Grafana reads the workspace through a separate identity holding Monitoring Data Reader.
The decisions worth defending. The permission is granted on the data collection rule — not the workspace, not the subscription — because the rule is the thing that accepts the write, and anything wider is scope nobody needs. The authentication is a managed identity rather than the Entra ID option Microsoft also documents, because that option requires a client secret; this lab forbids those outright, which makes the choice automatic rather than clever.
Prerequisites
- An Azure subscription, with Contributor plus User Access Administrator — the lab creates three role assignments and Contributor alone cannot.
- Terraform ≥ 1.10 and
hashicorp/azurerm~> 5.2. Thepreconditionbelow needs 1.2+. - An existing SSH public key. Azure requires a key or a password on a Linux VM; Terraform does not generate one here, because a generated key puts its private half in state.
- Resource providers
Microsoft.Monitor,Microsoft.Dashboard,Microsoft.AlertsManagement,Microsoft.Insights,Microsoft.Compute,Microsoft.Network,Microsoft.ManagedIdentity. - No cluster, no Entra licence, no prior lab. This week stands alone.
One prerequisite is a trap rather than a checkbox: VM size.
Three walls decided this lab's, and none announced itself clearly.
Standard_B2s is not offered in the region, but fails with
SkuNotAvailable ... Capacity Restrictions, which reads like a
temporary shortage. Every v2 B-series family had a vCPU quota of
zero here, while az vm list-skus reported them
unrestricted — SKU restrictions and quota are different systems, and
quota is only evaluated at create time. And p-suffixed sizes are
ARM64, which boot perfectly and then cannot run an amd64
binary.
Implementation
The remote-write URL is assembled, never pasted. Its host comes from the data collection endpoint; its path names the data collection rule by its immutable id, which is not the rule's resource name. Both are read back from the deployed workspace, so a rebuild in another subscription renders a correct config with nothing to hand-edit:
locals {
remote_write_url = join("", [
data.azurerm_monitor_data_collection_endpoint.metrics.metrics_ingestion_endpoint,
"/dataCollectionRules/",
data.azurerm_monitor_data_collection_rule.metrics.immutable_id,
"/streams/Microsoft-PrometheusMetrics/api/v1/write?api-version=2023-04-24",
])
}
That join hides a trap worth four lines of defence. The rule data
source also exposes a metrics_ingestion_endpoint attribute, and
for a workspace-managed rule it comes back empty. Terraform
cheerfully joins an empty host onto a path, applies, boots — and
Prometheus fails hours later with unsupported protocol scheme "".
An empty string is a valid string, so nothing warns. So the VM that bakes
this URL into its cloud-init refuses to be built with a broken one:
resource "azurerm_linux_virtual_machine" "prometheus" {
# ...
lifecycle {
precondition {
condition = startswith(local.remote_write_url, "https://")
error_message = "The assembled remote_write URL has no scheme, ..."
}
}
}
It must be a precondition, not a check
block — and this lab got that wrong first. A failed check
assertion only makes Terraform "report a warning and continue executing
the current operation", and the block runs "as the last step of plan
or apply operation, after Terraform has planned or provisioned your
infrastructure". It would have warned once the broken VM already existed.
Measured against an empty host: the check plans 1 to add and
exits 0; the precondition errors and exits
1.
A precondition is evaluated "after generating a plan but before creating the resource" and stops the operation. Against existing state it fails at plan; on a first apply the workspace does not exist yet, so the value is unknown and Terraform "delays checking that validation until the apply phase" — still before the VM is created. Either way the broken VM is never built.
managed_identity names a client id, and a client id is an
identifier, not a credential. The grep for passwords and secrets returns
0.The alert and recording rules are the other half. Both live in one
azurerm_monitor_alert_prometheus_rule_group whose
scopes is the workspace and whose cluster_name is
deliberately unset — the provider makes it optional, and leaving it empty
is what demonstrates that managed Prometheus rules do not require a
cluster.
Validation and Evidence
./scripts/validate.sh — 7 passed, 0
failed.
| Test | Expected | Actual | Status |
|---|---|---|---|
| ARM type of the workspace | microsoft.monitor/accounts | microsoft.monitor/accounts | PASS |
| Scope of Monitoring Metrics Publisher | on the DCR, 0 at subscription scope | 1 on the DCR, 0 at subscription | PASS |
prometheus.yml on the running host | no password, secret or private key | 0 matches | PASS |
| NSG inbound allow rules | none | none | PASS |
| A VM-written series queryable from the workspace | at least one series | up{job="prometheus"} = 1 | PASS |
| Rule group contents | 2 rules, no clusterName | 1 recording + 1 alert, no cluster | PASS |
| Grafana data source | points at this week's workspace | Managed_Prometheus_amw-wk11-... | PASS |
Two deserve a note. The config check reads the file on the running
host through az vm run-command, not from the template,
because the question is what actually deployed — and no SSH port is open
to read it any other way. The series check polls, 40 times at
60-second intervals, for reasons the next section explains.
instance: localhost:9090 is the VM talking about itself.
source: self-managed-vm is an external_label from
prometheus.yml, so provenance survives the whole journey. And
this is the query endpoint — a different host from the one the
write used, so both halves are demonstrated.
Security and Cost
No secret exists to leak. That is a design property, not a
discipline: the only credential-shaped thing in prometheus.yml is
a client id, which identifies an identity without granting anything.
The token comes from the instance metadata service at runtime and is never
written down. Microsoft's alternative Entra ID path would have put a
client_secret in that file.
Least privilege is enforced by scope. Monitoring Metrics Publisher sits on the data collection rule — not the workspace, not the subscription — and the validation asserts the subscription-scope count is zero rather than merely checking the grant exists. No inbound port is open at all, not even SSH; the public IP exists only because Azure's default outbound access is retired. Workspace data is encrypted at rest with a Microsoft-managed key.
What it cost, and the meter I failed to warn about. The bill is in. October for this subscription came to $7.21, against a $100 monthly budget. $7.19 of that is week 11; the remaining two cents is week 10's container registry, still sitting in the same subscription.
| Meter | Quantity | Cost |
|---|---|---|
| Azure Grafana Service — Standard User | 1 user | $6.0000 |
| Virtual Machines — D2als v7 | 11.27 hr | $1.0839 |
| Virtual Network — Standard IPv4 Static Public IP | 12.36 hr | $0.0618 |
| Storage — S4 LRS disk and disk operations | — | $0.0346 |
| Azure Monitor — metric samples ingested and processed | 757,000 samples | $0.0121 |
| Azure Monitor — PromQL queries | 2,000 samples | $0.0000 |
| Bandwidth — data transfer out | — | $0.0000 |
| Week 11 total | $7.1923 | |
Three things in that table are worth more than the total.
One: the 30-day free trial covered the wrong half. There is
no Standard Node line on the bill at all — the trial
absorbed the node hours, the roughly $0.93 this post would
have warned you about. It did not touch Standard User, which is a
flat monthly charge per active user and does not prorate. The
instance lived about twelve hours and billed a full month. Tearing
down quickly is no defence against a monthly meter — it saved
real money on the VM and saved nothing here. Signing in to capture a dashboard
screenshot is what created the active user.
Two: the metrics were almost free, and that inverts the week's own
framing. Azure metered 757,000 samples for $0.0083,
plus $0.0038 on a second meter, Metric Samples Processed. Call it
1.2 cents — 0.17% of the bill. The
compute was $1.17. The single largest line, at 83% of the total,
was a per-seat licence that is neither metrics nor compute. Measure where the
money actually is before optimising anything.
Three: Prometheus and Azure disagree about how much was sent. Prometheus's own counter read 796,849 samples; Azure metered 757,000. That is a ~5% gap, and it is stated here rather than smoothed over, because the number you are billed on is Azure's, not yours.
The hourly rates quoted earlier were read from the Azure retail price API
for southcentralus, and the totals above from Cost Management and
the Consumption API after the charges posted on 29 October. The caveat that
keeps the ratio honest: this is one Prometheus scraping
itself every 30 seconds. A real fleet multiplies samples without
multiplying VMs, and the ratio moves.
One control that exists for Log Analytics is unavailable here: Microsoft states that quota limits such as a daily cap or configurable retention cannot be used on an Azure Monitor workspace. Retention is 18 months, and that is not a dial.
Troubleshooting and Lessons
Problem: HTTP 403 for half an hour after a clean apply.
Root cause: the Monitoring Metrics Publisher grant had not propagated.
Microsoft documents this precisely — "It takes about 30 minutes for
the assignment of the role to take effect. During this time, you may see an
HTTP 403 error in the Prometheus log." That is roughly six times longer
than the equivalent grant took in week 08.
Resolution: wait, and make the validation poll rather than ask
once.
Lesson learned: a check that cannot distinguish wrong from not
yet teaches the wrong lesson. The apply finishes long before the pipeline
works, and in between, an empty query is indistinguishable from a broken
one.
Problem: unsupported protocol scheme "", hours after
Terraform reported success.
Root cause: the ingestion host was read from the data collection
rule, where that attribute is empty for a workspace-managed rule,
instead of from the endpoint.
Resolution: read it from the endpoint, and guard it with the
precondition shown above.
Lesson learned: an attribute existing on a data source does not mean it is
populated for your resource — and the instrument you assert it with must
be one that blocks. check is for continuous health reporting;
stopping a bad build is what preconditions are for.
Problem: cloud-init failed to download Prometheus.
Root cause: it ran before the VM had outbound connectivity, failing
after 132 seconds against github.com. The network came up shortly
after and worked fine.
Resolution: a wait-for-egress probe loop ahead of the download, plus
curl --retry on top.
Lesson learned: runcmd running "late in boot" is not a promise of
connectivity, and one successful probe does not promise the next request
succeeds. Wait and retry.
Problem: Grafana deployed, and nobody could open it.
Root cause: the Azure RBAC that creates the resource and the
Grafana RBAC that authorises a login are separate systems. Listing
role assignments on the healthy instance returned nothing.
Resolution: an explicit Grafana Admin assignment on the
instance for the deploying principal.
Lesson learned: easy to miss precisely because every other resource in this lab
is usable by whoever deployed it. A resource with its own internal
authorisation model needs that model configured too.
Cleanup and Key Takeaways
# teardown is the only irreversible step - check the figures first
python scripts/check_figures_before_destroy.py week-11-managed-prometheus
./scripts/cleanup.sh
Three things bill by the hour and none stops on its own: the Grafana
instance, the VM, and the public IP. cleanup.sh does not trust the
destroy's exit code — it counts what survives by resource type and prints
the number, because an earlier week in this lab had a destroy report success
while a firewall kept billing. Observed: 16 resources destroyed,
every count zero, including orphaned role assignments. Grafana alone took
10m12s to delete; that is normal, not a hang. Nothing shared was touched.
What this week taught:
- Managed Prometheus is not a Kubernetes feature. The
add-on scrapes clusters, but
remote_writeaccepts anything that can speak it — including one VM with no cluster in sight, and a rule group withclusterNameempty. - An Azure Monitor workspace is not a Log Analytics workspace. Different ARM type, different query language, different bill, and none of the retention or daily-cap controls carry over.
- Grant on the rule, not the workspace. The data collection rule is what accepts the write, so it is the narrowest scope that works — and "narrowest that works" is testable, which is why the validation asserts the subscription-scope count is zero.
- An empty string is a valid string. The most expensive
defect here applied cleanly, booted cleanly, and failed hours later. A
preconditionon the consuming resource costs six lines and stops the build; acheckblock, which this lab tried first, only warns. - Teardown speed is no defence against a monthly meter.
The VM ran eleven hours and cost $1.08 — the discipline worked. Grafana
ran the same eleven hours and cost $6.00, because
Standard Useris flat and per month. It was 83% of the bill, while the metrics this week is about were 0.17% of it. Enumerate every meter on a service before deploying it, not just the hourly one. - Creating a resource is not being granted access to it. Managed Grafana has its own authorisation model, and deploying it grants the deployer nothing inside it.
What production does differently: it scrapes a workload rather than itself, runs collection with redundancy instead of one VM, routes egress through a NAT gateway or private endpoint, and points its alert rules at an action group that actually notifies someone. This week's action group has no receiver — it proves a Terraform-defined rule becomes a rule Azure evaluates, and deliberately does not claim a notification was delivered.
References
- Connect self-managed Prometheus to Azure Monitor managed service for Prometheus
- Azure Monitor workspace overview
- Prometheus rule groups in Azure Monitor
- Share access to Azure Managed Grafana
- Prometheus configuration reference
-
azurerm_monitor_alert_prometheus_rule_group - Terraform custom conditions — preconditions and postconditions
- Terraform
checkblocks — and why they do not block - Source for this week · LAB.md runbook
Comments