Back to Terraform

Azure Applications: Functions, App Service, APIs and Event Wiring

November 6, 2026 Wasil Zafar 33 min read

Coordinate infrastructure, managed identities and separately versioned application deployment

Table of Contents

  1. Choose Hosting and Runtime Settings from Current Schemas
  2. Build and Promote a Versioned Application Artifact
  3. Wire Managed Identity to Storage and Messaging
  4. Model Service Bus, Event Grid or API Management Boundaries
  5. Test an Actual Request or Trigger and Its Failure Path

Choose Hosting and Runtime Settings from Current Schemas

A hosting plan is a contract, not a price tag. It fixes the operating system, the unit that scales, whether deployment slots exist and how the app fetches its package. Provider 5.13.0 expresses those choices as different resources rather than one resource with flags, so the first schema question is which resource name you are allowed to write.

Four plans cover almost every workload, and they are not interchangeable. Flex Consumption is the current serverless default for Linux; Consumption still exists under the older SKU; Premium adds pre-warmed workers and slots; a dedicated App Service plan gives you an always-on web host. The differences that matter in review are the scale ceiling, the slot story and the storage path.

PlanTerraform resourceScale unitSlotsChoose it when
Flex Consumption, FC1azurerm_function_app_flex_consumptionper-function instances, ceiling 1,000nonew Linux function apps that need scale to zero, VNet or larger instances
Consumption, Y1azurerm_linux_function_appshared consumption workers, ceiling 200noan existing Linux app that has not migrated yet
Premium, EP1 to EP3azurerm_linux_function_apppre-warmed workers plus burstyesa cold-start budget, VNet integration and a staging slot
App Service plan, B1 to P1v3azurerm_linux_web_app or a function appfixed workers plus autoscaleyesalways-on APIs with predictable CPU

The resource name is the first compatibility check. The provider's 4.0 major release removed the old plan and app resources, so a snippet that still uses azurerm_app_service_plan or azurerm_function_app was written against a schema you no longer have. Current names separate operating system and workload, which is why a Linux function app and a Windows function app are two resources instead of one argument.

Flex Consumption is Linux only and hosts one app per plan. The plan SKU is FC1, the app chooses an instance memory of 512, 2048 or 4096 MB, and the scale ceiling is 1,000 instances. There are no deployment slots today; zero-downtime releases use rolling site updates, which the service documentation still marks as public preview.

Consumption has a date attached to it. The provider documentation flags retirement of Linux Functions on the Consumption plan after 30 September 2028 and recommends Flex for new Linux apps. Moving between those plans is not an in-place edit: the documented migration creates a new app and redeploys the package.

A dedicated plan is a web host that happens to run functions. The same service plan resource accepts B1 through P1v3, the always-on setting keeps the worker resident, and slots behave the way they do for any App Service app. Always-on should stay off on Consumption and Premium plans, so the setting is a property of the chosen plan rather than a general default.

The plan sets the ceiling; the app sets the behaviour. SKU, operating system, zone balance and instance memory live on one resource; runtime, extension version, health path and app settings live on the other. A review that reads only the app resource approves half a contract.

Runtime pinning is spelled differently on each resource. Flex requires the runtime name and runtime version as top-level arguments, while a plan-based app uses an application-stack block plus an extension version that defaults to ~4. Both are pinned per app, so two apps on one plan can run different stacks.

StackFlex argumentsPlan-based fieldNote
Python 3.13runtime_name = "python"python_version = "3.13"Flex lists 3.10 to 3.14
Node.js 22runtime_name = "node"node_version = "22"Flex lists 22 and 24
.NET 10runtime_name = "dotnet-isolated"dotnet_version plus isolated flagIn-process C# is not supported on Flex
Java 21runtime_name = "java"java_version = "21"Provider marks 21 as preview for plan-based apps

The accepted list is wider than the supported list. Python 3.9 and Node 18 still appear in the plan-based field documentation while being absent from the Flex stack list, and every runtime eventually leaves support. Pin the version you tested and let a scheduled change, not a surprise platform update, move it.

Zone balance needs room to move. zone_balancing_enabled is accepted only on Consumption, Premium, Isolated and Workflow SKUs, and it requires a worker count greater than one in a region with more than one zone. Setting it on a single-worker plan is rejected rather than quietly ignored.

Verify against the schema, not the snippet. Ask the provider for the argument list and the region for the runtime list before writing the block; an argument that existed under a different name is a plan error, and a runtime that is not offered in the region is an apply error. Two commands answer both questions faster than a search result.

Choose Hosting and Runtime Settings from Current Schemas
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    W["Workload and required OS
HTTP API, queue consumer, timer"] --> L{"Linux and
scale to zero?"} L -->|"yes, new app"| FX["Flex Consumption
FC1, one app per plan"] L -->|"existing Linux app"| Y["Consumption Y1
retirement flagged 2028"] L -->|"no"| S{"Need slots or
pre-warmed workers?"} S -->|"yes"| PR["Premium EP1 to EP3
slots and VNet"] S -->|"no"| AP["App Service plan
B1, S1 or P1v3"] FX --> RT["runtime_name and
runtime_version"] PR --> RT2["application_stack and
extension version"] AP --> RT2 Y --> RT2 RT --> OK["Contract reviewed against
the provider schema"] RT2 --> OK FX -.->|"Windows runtime"| X1["No such resource
on Flex"] FX -.->|"in-place plan move"| X2["New app and
redeploy instead"] AP -.->|"zone balance on
one worker"| X3["Plan rejected"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class W,L,S primary; class FX,PR,AP secondary; class RT,RT2,OK ok; class X1,X3 danger; class Y,X2 warn;

The plan boundary sits inside a subscription boundary. Quota, SKU availability and provider registration are decided outside the resource, and each one can reject a plan that Terraform considered valid. Flex adds a regional memory quota shared by every Flex app in the subscription, so a maximum instance count is a request rather than a guarantee.

The plan fixes compute, the app fixes the runtime contract, and three checks live outside the resource group Inside a resource group boundary, a service plan box holds SKU, operating system and scale ceiling, while the app resource holds runtime, extension version, slots and settings. Below them are the deployment container and the managed identity. A side panel lists regional quota, SKU availability and provider registration as decisions outside the resource. Two resources, one contract The plan fixes compute. The app fixes what runs on it. Resource group boundary Service plan SKU and OS type scale ceiling zone balance Function or web app runtime and extension slots and health path app settings Deployment container one package per release digest recorded by the pipeline not a Terraform setting Managed identity principal id for role grants host storage and bindings survives a package change Checks outside the resource Regional quota Flex shares 250 cores by default SKU availability per region and per zone Provider registration Microsoft.App for Flex VNet A plan can pass validation and still be unbuildable in a region. One app per Flex plan. Slots belong to Premium and dedicated plans.

Choose the plan that matches the failure you can afford. A cold start is cheaper to explain than a slot that quietly consumes production messages, and a fixed worker is cheaper to explain than a scale ceiling nobody measured. Write that sentence down before the first apply; it is the decision the rest of the article tests.

Build and Promote a Versioned Application Artifact

The artifact and the app resource have different clocks. Code changes several times a day; the runtime, identity and scale contract changes when someone approves a design change. Keeping both in one apply couples those clocks, so every infrastructure review carries a package and every package review carries a plan.

Three owners keep three records. The build owns the bytes and the digest, the artifact store owns immutability, and Terraform owns the app contract. No owner should be able to overwrite another owner's record, because that is how a rollback becomes an archaeological dig.

StepOwnerRecordVisible to Terraform
BuildCI jobcommit, lockfile, build imageno
Storepipelineimmutable blob name and digestno
DeclareTerraformruntime, identity, settingsyes
Deploypipelinedeployment id and release versionno
Verifysmoke testversion response and traceno

Name the artifact so it cannot be overwritten. Include the app, a release number, the commit and the digest in the blob path, and never reuse that path. Overwriting a "latest" object turns a rollback into a rebuild and destroys the evidence of what ran last week.

The digest is the identity of the bytes. Hash the zip after a normalized build with fixed timestamps and file modes, then record the digest beside the release. Two builds from one commit must produce the same digest, and a digest that changes without a commit is a build defect rather than a new version.

Flex Consumption has a single deployment path. The package is deployed to a blob container and the host runs from it on startup; the app settings that used to steer deployment behaviour are documented as deprecated on this plan. That removes a class of "which flag won" bugs and makes the container part of the release contract.

Plan-based apps expose more knobs, including a security one. zip_deploy_file uploads a local package during apply, and the provider notes that basic publishing authentication must be disabled for it to work. Run-from-package makes the package read-only, while a remote build moves dependency restore to the platform, and each choice changes where the bytes live.

A volatile artifact path makes the plan dishonest. If the zip is rebuilt while Terraform evaluates, the digest changes under the review that approved it. Build with a pinned image, pass a frozen path, and fail the plan when the file digest does not match the release record.

Promotion is a pointer move, not a rebuild. A slot swap moves the hostname between prepared apps, a rolling update replaces Flex instances gradually, and an API revision or traffic weight moves the edge. All three should promote the blob digest that was tested, not a fresh build of the same commit.

MechanismAvailable onWhat movesWhat staysRollback
Slot swapPremium and dedicatedhostname bindingpackage and slot settingsswap back
Rolling updateFlex, public previewinstancesidentity and app settingsdeploy the previous blob
API revisionapps behind API Managementrevision and routebackend apppoint the revision back
Traffic weightFront Door or API Managementshare of requestsboth apps stay liveset the weight to zero

A staging slot is a running app. Its triggers connect to the same queues and topics as production, so a Service Bus consumer in staging competes for production messages before the swap. Stop the trigger in the slot, or test against a separate namespace, and treat the swap as a routing change rather than an isolation boundary.

Sticky settings protect slot-specific values. The app resource accepts a sticky-settings block naming app settings that should travel with the slot instead of the swap. Anything that names an environment, an endpoint or a feature flag belongs on that list; anything that names the build does not.

Basic publishing credentials are a credential you did not mean to keep. Disable the publishing profile and deploy over an Entra-authenticated SCM call. A lab can leave it on to use the provider's upload argument, but a production app that keeps it on has a second, long-lived secret beside the one you just removed from storage.

Rollback must not depend on a rebuild. Keep the last few blobs, record their digests, and make rollback the act of deploying digest X. A rollback that checks out the previous tag and builds again tests the build system during an incident, which is the worst moment to discover a dependency change.

Make the app answer with its version. A small version route returning the release id and digest costs one function and makes every later test checkable. It also gives the smoke test a value to compare with the pipeline record instead of trusting a green deployment status.

Build and Promote a Versioned Application Artifact
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    C["Commit and lockfile
pinned build image"] --> B["Build outside Terraform
normalized zip"] B --> D["SHA-256 digest
recorded with the release"] B --> A["Immutable blob
app, release, digest"] D --> A A --> DP["Deploy step
Entra-authenticated SCM"] DP --> SL["Slot or rolling update
same bytes as the test"] SL --> SM["Smoke test
version and one write"] SM --> PR["Promote
swap or traffic weight"] B -.->|"rebuilt during apply"| X1["Digest differs
from the review"] A -.->|"latest tag overwritten"| X2["Rollback becomes
a rebuild"] DP -.->|"basic auth off
and no replacement"| X3["Deploy fails after
a green apply"] PR -.->|"staging trigger live"| X4["Duplicate consumption"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class C,B primary; class D,A secondary; class DP,SL,SM,PR ok; class X1,X2,X3,X4 danger;

The release record is smaller than the pipeline. Commit, digest, runtime, identity and deployment id are enough to answer what ran, where it ran and as whom. If the record cannot name all five, at least one of them was chosen by something other than the review.

Wire Managed Identity to Storage and Messaging

An identity is a principal with a name you can grant to. A system-assigned identity is created and deleted with the app, which is convenient until a role assignment outlives it. A user-assigned identity is a resource you create first, so the grant can exist before the app and be reused by the next deployment of it.

The host storage connection is the first grant and the largest. The Functions host reads and writes its own container, queue and table to coordinate locks, keys and diagnostics. Storage Blob Data Owner on the account is the documented minimum, with Storage Table Data Contributor added so diagnostic events can be persisted.

Identity-based host storage removes the connection string, not the requirement. Flex sets the storage authentication type to a system-assigned identity, while a plan-based app sets the managed-identity flag on the storage block. Both still need the role assignment, and the settings the provider composes should be read back after apply rather than assumed.

Consumption and Premium still need Azure Files. The share that holds the deployment package cannot authenticate with a managed identity, so that connection string stays a secret and belongs in Key Vault. Flex has no Azure Files share, which is why it is the cleanest plan for a host connection with no stored secret.

Binding connections are separate settings with a prefix. A Service Bus trigger reads a fully qualified namespace and a managed-identity credential under its own prefix; a storage binding reads a blob or queue service URI under a different prefix. The prefix is the name the binding's connection property points at, and a missing prefix is a listener that never connects.

ConnectionRoleScopeFailure when missing
Host storageStorage Blob Data Ownerstorage accounthost cannot start or take a lock
Host diagnosticsStorage Table Data Contributorstorage accountwarnings and missing diagnostic events
Blob triggerStorage Queue Data Contributorstorage accountpoison blob cannot be recorded
Service Bus triggerAzure Service Bus Data Receiverqueue or topic subscriptionlistener cannot peek-lock
Service Bus sendAzure Service Bus Data Senderqueue or topicproducer receives 401
Event Grid deliveryStorage Queue Data Message Senderdestination queuesubscription creation fails

Grant to the resource, not to the service. A Service Bus receiver role must cover the queue or the topic subscription that the function reads. A grant on the topic alone authorizes nothing for a subscription consumer, and some clients do not even offer the subscription as a scope.

Role assignments are eventually consistent. The documented propagation window is up to ten minutes, and a 403 inside that window is expected rather than evidence of a wrong role. Put the wait in the test, not in a retry loop inside the handler, because a handler that retries authorization hides the real delay.

Terraform cannot infer a dependency that lives in another control plane. An Event Grid subscription that delivers with a managed identity needs the identity on the system topic and a role on the destination before creation. The provider documentation recommends an explicit dependency for exactly this reason, since the reference is invisible in the configuration graph.

Turn off shared keys where you can afford the consequence. A Service Bus namespace accepts a local-authentication flag, and a storage account accepts a shared-key flag that removes key-based authorization entirely. The cost is real: account-key SAS, some samples and the basic publishing profile stop working, so decide the replacement before the flag rather than after the outage.

One identity per app, not one per environment. Sharing an identity across apps turns every grant into a grant to all of them, so a token from the least important app reaches the most important data. A separate identity costs one resource and one assignment per app, and it makes the access review answerable.

Managed identity does not remove the network boundary. A role assignment authorizes a token; it does not create a private endpoint, a firewall rule or a service tag. A storage account restricted to a private endpoint needs the endpoint and matching DNS before the token is worth anything.

One app identity obtains a token and presents it to storage and Service Bus, replacing stored connection strings A function app with a user-assigned identity requests a short-lived token from Microsoft Entra ID. The token is presented to a storage account, where blob, queue and table roles apply, and to a Service Bus namespace, where receiver and sender roles are scoped to a queue or subscription. A crossed-out panel shows a connection string in app settings as the rejected alternative, and a note records the ten-minute role propagation window. The token replaces the secret The app asks for a token, presents it, and never stores a key. Function app user-assigned identity one identity per app principal id known before the app exists Microsoft Entra short-lived token audience per service Storage account Blob Data Owner for the host Table Data Contributor for diagnostics Queue Data Contributor for poison records shared key disabled, SAS removed Service Bus namespace Data Receiver on the queue Data Sender on the topic local authentication disabled Rejected: keys in settings readable in plan and state rotation becomes a config change Propagation is part of the contract A new role assignment can take up to ten minutes. Event Grid delivery needs an explicit dependency before the subscription is created.

Read the effective grant, not the plan. After apply, confirm the assignment exists at the scope you meant with the principal id the app reports. A role assignment that names a stale principal looks correct in state and authorizes nobody, which is the quietest failure in this section.

Model Service Bus, Event Grid or API Management Boundaries

The boundary decides who retries. A queue retries because the consumer did not complete the message, Event Grid retries because the endpoint did not answer, and API Management returns the failure to the caller. Choosing the boundary is choosing which of those three stories you will debug during an incident.

Service Bus is a lock, a count and a dead-letter queue. A receive takes a peek-lock for the lock duration, one minute by default and five at most, and an abandoned or expired delivery increments the count. At the maximum delivery count, ten by default, the broker moves the message to the dead-letter queue with a reason you can read.

Sessions buy order at the cost of parallelism. Enabling sessions gives first-in-first-out delivery per session id and stops competing consumers from overtaking each other. It also pins a session to one consumer at a time, so a single hot key becomes a single lane.

Duplicate detection is a window, not a guarantee. Enabling duplicate detection suppresses a repeated message id inside the history window, and the setting is fixed when the queue is created. It protects against producer retries; it does not make the consumer idempotent, and it does not span a topic subscription you forgot to configure.

Event Grid is a fact delivered at least once. Event Grid waits thirty seconds for an answer, then retries on an exponential schedule that stretches from seconds to hours. The defaults are thirty attempts and a 1440-minute time to live, and whichever limit is reached first ends delivery.

Some answers are never retried. A 400 or 403 is treated as a configuration problem, while a 401 is retried after five minutes and a 503 after thirty seconds. That asymmetry explains why a bad role assignment dead-letters immediately while a cold endpoint recovers on its own.

Dead-lettering is off until you configure it. An Event Grid subscription without a dead-letter destination drops events that exhaust their retries, and the destination blob receives them after a short delay once it is configured. A dead-letter location that is itself unavailable for four hours loses the events.

The function endpoint must exist and carry the right trigger. The subscription names a function id in the form application id plus function name, and a destination without an Event Grid trigger fails validation with a specific outcome. Terraform must use the function's name rather than the HTTP route.

Batching is all or none. A batched delivery can carry up to 5,000 events, and the endpoint must answer the whole batch inside the same thirty-second window. Ask for the batch size the consumer can finish, not the batch size the publisher can produce.

BoundaryDeliveryOrderingRetry ownerPoison destination
Service Bus queueat least onceFIFO with sessionsconsumer lock and delivery countdead-letter queue
Service Bus topicat least once per subscriptionper sessioneach subscriptionper-subscription dead-letter queue
Event Grid system topicat least once, unorderednoneEvent Griddead-letter blob
Storage queueat least oncenoneFunctions hostpoison queue
API Managementsynchronousper requestcallernone

API Management is an edge, not a queue. It validates a subscription or a token, applies rate limits, selects a revision and forwards to a backend with a timeout. Work that can outlive that timeout belongs behind Service Bus, because an edge that waits is an edge that fails slowly.

A private app is not reachable by a platform service just because it is private. Event Grid and API Management deliver from outside your subnet, so a function app restricted to a private endpoint needs a path for that service. Test delivery from the service, not from a laptop that happens to be on the virtual network.

A function key in a backend URL is a secret in state. API Management can carry the key in a named value, authenticate with its own managed identity, or call an anonymous function that is restricted to the gateway's network. Each option moves the trust boundary; none of them removes it.

Two event boundaries and their failure paths: Service Bus retries against a delivery count and Event Grid retries against attempts and time to live The left lane shows a publisher, a Service Bus queue and a consumer function. An abandoned message returns to the queue, increments the delivery count, and moves to the dead-letter queue at the maximum count. The right lane shows a storage event, an Event Grid system topic with a filter and a function endpoint. A failed delivery is retried up to thirty attempts or 1440 minutes and then dead-lettered to a blob. A footer notes that delivery is at least once and that 400 and 403 responses are not retried. Two boundaries, two retry clocks The service you pick decides who owns the retry and where the poison lands. Service Bus: lock, count, dead-letter Publisher sends and moves on Queue peek-lock, 1 to 5 minutes Consumer function commits once, then returns Dead-letter queue at delivery count 10 Abandon or expiry returns the message and increments the delivery count. Event Grid: attempts and time to live Blob event a fact, not a command System topic filter by event type Function endpoint Event Grid trigger required Retry 30 attempts by default TTL 1440 minutes Dead-letter blob only if configured At least once, both ways The consumer owns the idempotency key. A 400 or 403 is not retried, and delivery is not ordered.

Write the boundary sentence down. "This queue absorbs checkout spikes for one consumer group" and "this topic lets three teams react independently" are different designs, and the sentence predicts the failure you must test. If the sentence needs the word "and" three times, the boundary is doing too much.

APIM revisions are not message versions. A revision changes the route or contract a caller sees, and it can be promoted or retired at the edge. It says nothing about the message schema inside the payload, so schema versioning remains the producer's job.

Size the lock before the work. A lock shorter than the handler's worst case produces duplicate deliveries that look like a broker bug. Either extend the lock through the client or make the handler finish inside it, and measure the worst case with a real dependency rather than a local stub.

Test an Actual Request or Trigger and Its Failure Path

Readiness has three states, and only the third serves traffic. The app is running, the host has indexed the functions, and every trigger listener has connected to its source. A green resource proves the first, a function inventory proves the second, and a consumed message proves the third.

Cold start is a state, not a bug. Flex scales to zero by default and its host initialisation times out after thirty seconds, so the first request after idle is a different measurement from the tenth. Always-ready instances remove the difference at a cost, and both numbers belong in the release note.

A key error and a trigger error look different. A wrong function key returns 401 before the host runs anything, a missing role returns 403 from the downstream service after the invocation, and a missing Event Grid trigger fails when the subscription is created. The status code names the layer that refused.

TestSetupExpectedEvidence
HTTP successvalid key, synthetic body200 and one writeinvocation id and version
Wrong keysame request, key removed401, no invocationhost log without a request
Queue retryconsumer throws oncesecond delivery, one recorddelivery count and empty DLQ
Queue poisonconsumer always throwsmessage in the DLQdead-letter reason
Event Grid retryendpoint returns 500 twiceredelivery, then successdelivery attempts
Event Grid wrong triggersubscription to an HTTP functioncreation rejectedvalidation message
Edge failureapp stopped behind API Management5xx from the edgegateway response, no backend trace

Test with the payload the source really sends. Event Grid wraps a single event in an array, a Service Bus body arrives as a string that must be parsed, and an API Management request carries gateway headers. A hand-written object tests the handler and leaves the wiring untested.

Assert the absence of a duplicate. Retry tests are only interesting when they count writes. A second delivery that creates a second row is a failure even though the function returned a success code.

Delayed activation is part of the observable path. The first request after a deploy can be slow because the host is loading the package, and the first message after idle can be slow because the worker is starting. Measure both, and record which one the alert is measuring.

Lab

Test an Actual Request or Trigger and Its Failure Path

Status: design-only. No Azure subscription or credential was used to produce this article, and these steps were not executed here. Versions: Terraform CLI 1.17.1, hashicorp/azurerm 5.13.0, verified 6 November 2026.

Prerequisites. A sandbox subscription with an allowed subscription id, one resource group, a Flex Consumption plan and app running Python 3.13, a storage account used only by this lab, a Service Bus Standard namespace with one queue, and permission to read the app log and the queue's dead-letter count.

Setup. One HTTP producer function writes a message to the queue through an output binding, and one Service Bus trigger function consumes it and writes a record. Keep the record store trivial, a blob or a table row, because the lab tests the boundary rather than the business logic.

ObjectLab valueWhy it matters
PlanFlex Consumption, FC1, one appno slots, so promotion is a rolling update
RuntimePython 3.13, pinnedFlex lists 3.10 to 3.14
Storage authsystem-assigned identityno account key in settings
Queuepeek-lock, maximum delivery count 10the DLQ threshold is predictable
ProducerHTTP trigger, function-level keya 401 is testable without a role change
ConsumerService Bus trigger, receiver rolethe listener needs the data-plane role
  1. Apply the base. Create the plan, app, container, namespace, queue and role assignments, then read back the app state and the identity principal id.
  2. Confirm discovery. List the functions on the app and expect both names; an empty list means the host has not indexed the deployed package.
  3. Send one request. Call the producer with a valid function key and expect a success code plus one message on the queue. Record the invocation id from the log.
  4. Consume once. Let the trigger run and confirm one stored record, an empty queue and a delivery count of one.
  5. Deny the receiver. Remove the receiver role, send again and expect the listener to fail with 403 once its current token or connection refreshes, with the message still queued. Restore the role and allow up to ten minutes for propagation before retrying.
  6. Fail once, then succeed. Make the consumer throw after the write, send one message, and expect two deliveries with one record. This is the duplicate test, not the retry test.
  7. Exhaust the retries. Make the consumer throw before the write on every attempt and expect the message in the dead-letter queue at the configured count, with the reason readable.
  8. Break the subscription. Create an Event Grid subscription that targets the HTTP producer instead of an Event Grid trigger, expect creation to be rejected, then delete the attempt.
  9. Break the edge. Stop the app and call the API Management route if one fronts it; expect a 5xx from the gateway with no backend trace. Start the app and repeat the success request.
  10. Destroy and inspect. Apply a reviewed destroy plan, then list the queue, dead-letter queue, role assignments and container rather than assuming the group is empty.

Expected observation. A sequence rather than a duration: functions discovered, one message produced and consumed, one 403 after the role was removed, two deliveries with one record, a dead-letter message at the configured count, a rejected Event Grid subscription, and an edge error with no backend trace.

Failure checks. The lab fails if a denied listener still consumes, if the retry creates a second record, if the dead-letter queue receives a message the consumer reported as successful, or if the observed package version differs from the digest the pipeline recorded.

Cleanup. Delete the app, plan, namespace and container, and remove the role assignments before the identity. Keep the last artifact blob until the rollback window closes, and keep the deployment record after everything else is gone.

Evidence to keep. The artifact digest, the version response, the role assignment scope, the delivery count from both retry tests, the dead-letter reason, and one redacted trace per outcome.

References (verified 6 November 2026):

  • azurerm_function_app_flex_consumption: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/function_app_flex_consumption
  • azurerm_linux_function_app: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/linux_function_app
  • azurerm_service_plan: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/service_plan
  • azurerm_eventgrid_system_topic_event_subscription: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/eventgrid_system_topic_event_subscription
  • azurerm_servicebus_queue: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/servicebus_queue
  • Flex Consumption plan: https://learn.microsoft.com/en-us/azure/azure-functions/flex-consumption-plan
  • Identity-based connections in Azure Functions: https://learn.microsoft.com/en-us/azure/azure-functions/manage-connections
  • Event Grid delivery and retry: https://learn.microsoft.com/en-us/azure/event-grid/delivery-and-retry

Telemetry has to survive the cold start. Send the connection string through the app's site configuration, keep sampling deliberate, and query the invocation id against the downstream dependency. If the first request after a deploy has no trace, the release is not observable yet.

Acceptance is a record, not a green check. Digest, app version, role scope, trigger result and dead-letter state belong together in one place. That record is what lets the next person tell a code regression from a permission change without rebuilding the story from memory.

Next in the Series

In AKS and ACR: Cluster Provisioning, Workload Identity and Application Ownership, we'll explore Separate Azure cluster infrastructure from Kubernetes API resources and image promotion.