Back to Terraform

Serverless AWS: Lambda Artifacts, API Gateway and Event Permissions

November 6, 2026 Wasil Zafar 27 min read

Promote immutable application code and wire API and event sources with precise execution identities

Table of Contents

  1. Build the Function Artifact Before Planning
  2. Model Function Settings and Execution Roles Separately
  3. Trace API Gateway and Event Invocation Authorization
  4. Choose Queue, EventBridge or Workflow Boundaries Deliberately
  5. Test Success, Retry and Denied Invocation

Build the Function Artifact Before Planning

A plan with no diff is not proof that nothing changed. Lambda can keep serving an older package while the configuration looks settled, because Terraform only notices code when a hash argument tells it to look. The artifact has to exist, and its identity has to reach the plan, before the function is worth reviewing.

The artifact is a build output, not a source directory. CI compiles, bundles and zips; Terraform uploads the finished bytes. Keeping those steps apart is what makes a release reviewable: the build job can run without AWS credentials, and the apply cannot silently rebuild.

RecordTerraform fieldWhy the plan needs it
Zip digestcode_sha256separates a code change from a settings change
Runtimeruntimefixes the interpreter the handler expects
Architecturearchitecturesrules out native dependencies built for another CPU
Handlerhandlernames the entry point the runtime will call
Layer versionslayerspins shared code to a version, not a name
Image digestimage_urimakes a container release immutable

In provider 6.72.0 the digest field is code_sha256. It carries the base64-encoded SHA-256 of the zip and also notices a package replaced out of band. The older synthetic hash still exists, but it only tracks what your configuration already says, so it cannot see that replacement. Set the digest from the built file and keep one hash argument per function.

Reproducibility is a release property. Pin the runtime, the build image and the dependency lockfile; normalize file modes and timestamps in the zip. A rebuild from the same commit should produce the same digest, and a digest that changes without a commit is a build defect rather than a new release.

Pin the toolchain that produces the plan. Terraform 1.17.1 and hashicorp/aws 6.72.0 are the versions this article was checked against; a range such as ~> 6.0 is not a pin. The lock file belongs in the artifact record too, because a different provider build can change which arguments exist and which diff appears.

data "archive_file" is convenient and easy to misuse. It writes a zip while Terraform evaluates the plan, and its timestamp metadata can change between runs. Build in CI instead, record the digest in the release note, and pass a frozen path to the function.

Build the Function Artifact Before Planning
%%{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
    SRC["Source and lockfile
pinned toolchain"] --> BUILD["Build outside Terraform
compile, bundle, zip"] BUILD --> ZIP["Normalized package
code and dependencies"] BUILD --> LAYER["Layer version
own digest and ARN"] ZIP --> DIG["code_sha256
base64 SHA-256"] DIG --> PLAN["terraform plan
artifact digest"] LAYER --> PLAN PLAN --> FN["aws_lambda_function
bytes and contract"] FN --> VER["Published version
immutable snapshot"] PLAN --> Q{"Digest changed?"} Q -->|"no"| SAME["No code update
settings may still move"] Q -->|"yes"| UP["In-place code update
new version if publishing"] BUILD -.->|"dirty tree or
unpinned tool"| BAD1["Rebuild changes the digest
without a commit"] LAYER -.->|"rebuilt at the
same layer ARN"| BAD2["Function keeps
the old layer"] 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 SRC,PLAN,FN primary; class BUILD,ZIP,LAYER,UP secondary; class DIG,VER ok; class Q,SAME warn; class BAD1,BAD2 danger;
The deployment package is built outside Terraform while the function resource declares the contract around it On the left, source, a pinned build image and a normalized zip produce a digest. On the right, the function resource holds the uploaded bytes and the runtime contract: runtime, architecture, handler and layer ARNs. The bottom strip shows the two silent failures: no digest means a package change is invisible, and a layer rebuilt at the same ARN is never picked up. What the plan uploads, and what it only declares The zip is bytes. Runtime, architecture, handler and layers are the contract around them. Build boundary Outside Terraform, no AWS credential source and lockfile one commit, one dependency resolution pinned build image runtime and CPU target fixed normalized package code, dependencies, stable metadata Function boundary One mutable resource, one immutable version uploaded bytes digest recorded as code_sha256 a changed digest updates the function declared contract runtime, architecture, handler layer ARNs, timeout, memory these decide whether the bytes start Two silent failures No digest argument: a replaced package stays invisible. Rebuilt layer at the same ARN: the function keeps the old dependency.

The package and the function are separate layers. The zip holds code and dependencies; the function resource holds the contract around it: runtime, architecture, handler, timeout and layers. A review that reads only the code diff misses the half that decides whether the code can start.

A layer is a second artifact with its own version. The function stores a layer ARN that ends in a version number, so rebuilding the layer's contents does not update a function that still names the old ARN. Publish a new layer version and change the reference in the same pull request.

Architecture is a build decision, not a deployment toggle. An arm64 function needs dependencies compiled for arm64, and switching the architecture of a function that carries native code produces a start-up failure rather than a performance change. Record the target in the build job and in the function resource, and test the artifact on that target.

Five layers is the ceiling, and the extracted size is shared. The function and its layers must fit the same unzipped budget, so a large dependency layer reduces what is left for application code. Treat the layer list as a budget with an owner, not as a place to park shared code.

The artifact record is small enough to review. Commit, digest, runtime, architecture, handler and layer ARNs; if the release cannot name all six, the plan is guessing at least one of them.

Model Function Settings and Execution Roles Separately

Settings and permissions fail in different ways. A wrong memory value shows up as a timeout or a bill; a wrong role shows up as an access-denied error from a service the function called. Modelling them as one "function config" hides which of the two a change actually touched.

The execution role is an identity, not a setting. Lambda assumes it to write logs, read a queue or call a database; the permissions the function uses are statements on that role, its attached policies, or a resource policy that names the role. The function's resource policy is the other direction entirely: it decides who may invoke the function.

SettingLab valueConsequence to review
Memory512 MBCPU scales with memory, so a timeout is not always a timeout problem
Timeout10 sthe handler stops before the edge budget, so the caller sees a function error
Runtimepython3.13the package must match the interpreter and its wheels
Architecturearm64native dependencies must be built for arm64
Reserved concurrency5caps blast radius and throttles callers at the quota
Log retention14 daysset on the log group, not on the function

Logs have an owner and a bill. Lambda creates a log group on first invocation if none exists, and that group has no expiry. Create the group in Terraform with the exact name Lambda expects, set retention, and make the function depend on it so the first invocation does not create an unmanaged twin.

Environment variables are configuration, not a secret store. They are visible in the console, in plan output and in state, and KMS encryption protects the stored value rather than the people who can read it. Keep non-secret settings there and fetch credentials at runtime through the role.

A published version is a snapshot; an alias is a pointer. Publishing freezes code and settings, and the alias gives callers a stable name that can move between versions. Editing the unpublished function after a publish does not change what the alias serves, which is why a "small config fix" can appear to do nothing in production.

Model Function Settings and Execution Roles Separately
%%{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
    CFG["Function settings
memory, timeout, runtime"] --> PLAN["terraform plan"] ROLE["Execution role
trust and policies"] --> PLAN PLAN --> FN["aws_lambda_function"] PLAN --> IAM["Role policy attachment"] FN --> VER["Published version
code and settings frozen"] VER --> ALIAS["Alias
production pointer"] ALIAS --> CALLER["Integration uses
the alias ARN"] FN --> LOG["Log group
explicit retention"] ROLE -.->|"role destroyed
and recreated"| KMS["Environment KMS grant
no longer valid"] CFG -.->|"secret placed in
environment"| LEAK["Value readable in
plan, state and console"] ALIAS -.->|"settings edited after
the last publish"| STALE["Alias still serves
the old snapshot"] LOG -.->|"no retention set"| COST["Logs kept forever"] 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 CFG,PLAN primary; class ROLE,IAM,FN secondary; class VER,ALIAS,CALLER ok; class KMS,LEAK,STALE danger; class LOG,COST warn;

The alias is the integration contract. API Gateway and event sources should target the alias, not the unqualified function, so a promotion changes one pointer instead of every caller. A permission granted on the alias must also name the alias as its qualifier, or the invocation arrives at an ARN the policy does not cover.

Weighted aliases split traffic, not configuration. Both versions behind the alias keep their own settings and layers, so a canary compares two complete snapshots. That is useful for behaviour, and misleading if the two snapshots differ in more than the change under test.

ObjectMutable?Terraform addressDrift symptom
Code and settingsupdated in placeaws_lambda_functiona plan that hides a package swap
Published versionimmutable snapshotaws_lambda_function with publishan alias that still serves the old snapshot
Aliaspointeraws_lambda_aliastraffic on a version no one promoted
Execution roleidentity and policiesaws_iam_role plus attachmentsan out-of-band policy grant
Log groupretention and classaws_cloudwatch_log_groupa second group created by Lambda

Role recreation is the quiet failure. When a role is destroyed and recreated, the function keeps working until it reads an encrypted environment variable, then fails with a KMS denial because the grant belonged to the old role. Treat role replacement as a function event: force Lambda to refresh the grant by changing the function's role and changing it back, or recreate the function, then invoke once before calling the release done.

Read back three values after apply. The alias's version, the digest recorded in state and the role ARN; if any of them is not what the plan named, the release is not the one that was reviewed.

Trace API Gateway and Event Invocation Authorization

A 500 from API Gateway is often a missing permission, not a broken handler. The request reached the API, the authorizer accepted the caller, and then the service could not invoke the function. Reading the layers in order turns a vague server error into a specific statement to fix.

Three decisions sit on one request. The caller is authenticated and authorized at the edge; the service principal is allowed to invoke the function by the function's resource policy; the function's execution role is allowed to reach whatever it calls next. Each decision has its own object and its own error signature.

Caller authorization, function policy and execution role are three separate checks A client reaches API Gateway, where an authorizer decides whether the caller may proceed. The Lambda resource policy then decides whether the API Gateway service principal may invoke the function. EventBridge and S3 reach the same policy directly. Finally the function assumes its execution role to call a downstream resource. A denied caller gets 401 or 403, a missing function policy gets a 5xx with no function log, and a missing role action gets an error from inside the handler. Four checks before a byte reaches the handler Every hop has one policy. The error signature tells you which hop refused. Caller Who is asking client JWT or IAM credential EventBridge rule service principal S3 notification service principal Invocation boundary May this caller invoke this function? API Gateway authorizer JWT, IAM or Lambda authorizer rejects before integration Lambda resource policy principal plus source ARN qualifier must match the target 401 or 403 caller refused 5xx, no log service refused Execution boundary What may the function touch? function alias-qualified ARN execution role assumed by Lambda downstream table, bucket or queue Read the signature before reading the code 401 or 403: caller refused. 5xx with no log: service refused. Handler access denied: role refused.

The authorizer owns the caller, not the function. A JWT or Lambda authorizer that rejects a request produces a 401 or 403 before any invocation. A function policy that is missing produces a 5xx from the API because the gateway itself was refused, which is why the two failures should never share a dashboard panel.

API Gateway HTTP APIs and REST APIs expose different policy surfaces. REST APIs can carry a resource policy that restricts which accounts, source addresses or VPC endpoints may call the API. HTTP APIs rely on IAM authorization, JWT or Lambda authorizers, and still need a Lambda permission statement for the integration.

SourcePrincipalScope to narrowFailure signature
API Gateway HTTPapigateway.amazonaws.comstage, method and path under the execution ARN5xx and no function log
API Gateway RESTapigateway.amazonaws.comresource policy plus a statement on the function403 at the API or 5xx at the integration
EventBridge ruleevents.amazonaws.comthe rule ARN, not just the servicefailed invocations and retries
S3 notifications3.amazonaws.comthe bucket ARN and source accountnotification configuration rejected
SNS topicsns.amazonaws.comthe topic ARNdelivery failure on the subscription
Function URL* or an IAM principalthe URL auth type, never an open public grant403 at the URL
SQS mappingno statement; role-basedqueue ARN in the execution rolemapping creation fails or stays disabled

Polled sources use the execution role, not a resource policy. SQS, Kinesis and DynamoDB streams are read by the Lambda service on the function's behalf, so the role needs the receive or stream actions and the queue or stream ARN. There is no Lambda permission to add for the mapping, and adding one does not fix a role that cannot poll.

Pushed sources need a statement before the wiring. S3, EventBridge and SNS call the function directly, so their permission must exist first; otherwise the notification or target either fails validation or registers and then cannot deliver. In Terraform the dependency is explicit, not inferred from an ARN string.

A service principal without a source is an open door. Granting EventBridge or S3 permission with no source ARN lets any resource using that service in any account attempt an invocation. Name the rule, bucket or topic, and add the source account when the caller can live elsewhere.

The qualifier must match the ARN the caller uses. A permission on the unqualified function does not authorize an invocation addressed to an alias, and an integration pointed at the alias will fail even though the policy looks correct. Keep the alias name in one local value and use it for the integration, the permission and the invocation test.

Downstream access is a second, separate grant. The role needs actions on the table, bucket or queue the handler touches, scoped to those ARNs. A successful invocation that returns an access-denied error from DynamoDB is a role problem that no function policy can solve.

Same-account IAM callers are the exception. An IAM principal in the same account can invoke through its identity policy without a statement on the function, while service principals and other accounts need the resource policy. That asymmetry explains why a script works and the event source does not.

Trace one request with four names. Caller identity, API or event source, function qualifier, and the downstream resource; each hop should have exactly one policy that allows it.

Choose Queue, EventBridge or Workflow Boundaries Deliberately

A queue is a buffer, not a workflow engine. It absorbs load and retries delivery, but it does not know that step three must wait for step two or that a failure at step four should refund a payment. Choosing the boundary is choosing which of those guarantees you are buying.

BoundaryDeliveryOrderingRetry ownerUse when
Synchronous APIcaller waitsper requestcallerfast reads inside the edge budget
Async invokeat least oncenoneLambda, zero to two retriesfire and forget with a failure destination
SQS standardat least oncebest effortpoller plus queue redrivebuffer, backpressure, one consumer group
SQS FIFOat least once, deduplicatedper message grouppoller plus queue redriveordered work with a group key
EventBridgeat least oncenoneEventBridge, up to 24 hoursfacts, fan-out, content filtering
Step Functionsone execution, retried tasksdefined by the flowstate machinemulti-step work with waits or compensation

SQS owns retention and backpressure. A standard queue holds work until a consumer deletes it, and the redrive policy moves a message to a dead-letter queue after a receive count you choose. That is the right boundary for work that must survive a deploy or a throttled downstream.

Partial batch failure is a per-message decision. With the report-failures response type, the handler returns the identifiers that failed and Lambda retries only those, instead of replaying a whole batch. Without it, one bad record can redeliver every good record beside it, so idempotency becomes mandatory rather than advisable.

EventBridge is for facts other teams may care about. A rule matches an event pattern, filters before invocation and fans out to several targets. It retries for up to 24 hours and does not preserve order, so it suits "an order was placed" and not "apply this exact sequence of writes".

A workflow boundary belongs around decisions, not inside a consumer. Step Functions can wait, branch, retry with backoff and run compensation, which a queue consumer cannot do without becoming a hidden state machine. Keep each task Lambda to one idempotent mutation and let the state machine own the sequence.

Queue, event bus and workflow boundaries compared by what each one guarantees The queue panel shows a producer, a buffer, a polled function and a dead-letter queue after a bounded receive count. The event bus panel shows one producer, a rule with a filter, and three independent targets with a 24 hour retry window. The workflow panel shows an event starting a state machine that sequences two tasks and a compensation path. The bottom strip says to choose by guarantee rather than by service name. Three boundaries, three different guarantees Pick the failure you can explain, then pick the service that produces it. Queue: survive load producer writes and moves on queue retention plus visibility timeout poller and function batch, then delete on success dead-letter queue after limit Bus: notify many producer publishes a fact rule and filter match before invocation target A target B target C, retried for 24 hours Workflow: sequence work trigger event or API call state machine branch, wait, retry, compensate task one task two compensation is part of the flow Choose by guarantee, not by service name Buffer, fan-out or sequence: the sentence you write about the boundary predicts the failure you must test.

The event schema is part of the interface. Verify the shape the source actually sends: an SQS record carries a JSON string in its body, EventBridge wraps the payload under detail, and API Gateway sends a proxy envelope. A consumer tested against a hand-written object will pass locally and fail on the first real event.

Envelope every event, even inside a typed source. Include an event identifier, a schema version, an occurrence time and a trace identifier; then a consumer can reject an unknown version instead of guessing. The envelope is also where an idempotency key belongs, because the transport will deliver duplicates.

Choose the timeout budget before the service. API Gateway gives an HTTP integration about 30 seconds and a REST integration about 29, while a function can run for 15 minutes. Work that needs longer than the edge budget belongs behind a queue or a workflow, not inside the request.

Write the boundary sentence down. "This queue exists to absorb spikes for one consumer" and "this bus exists so three teams can react independently" are different designs, and the sentence predicts which failure you will need to handle.

Test Success, Retry and Denied Invocation

Three tests prove three different layers. A success shows the happy path; a retry shows the delivery boundary; a denied call shows the policy is actually attached. A release that only tests the first is trusting the other two to configuration review.

TestSetupExpectedEvidence
Successsynthetic payload with a valid caller2xx and exactly one downstream writerequest id and alias version
Retryhandler fails once, then succeedsa second attempt, still one stored recordattempt count and empty DLQ
Denied invocationremove the function permission5xx at the API, no function logAPI log and policy diff
Denied downstreamremove one role actioninvocation succeeds, handler reports denialfunction log error code

Test the payload shape the source sends. Invoke with a captured sample that has been redacted, not a simplified object; keep the fixture in the repository and version it with the schema. The test should fail when a required field disappears, not when the handler happens to tolerate it.

A retry test needs a controlled failure. Make the first attempt fail after the write or before it, deliberately, and assert what the second attempt does. The interesting result is not that the retry happened but that the duplicate did not create a second record.

Lab

Test Success, Retry and Denied Invocation

Execution status: design-only. These steps are a lab plan; no live account output is recorded here, and identifiers are written as tokens rather than real values.

Prerequisites. Terraform CLI 1.17.1, AWS provider 6.72.0, one sandbox account, one function and HTTP API you can break, one queue with a dead-letter queue, and permission to read the function's logs.

FixtureShapePurpose
success.jsonHTTP API proxy envelope, version 2.0prove the happy path and the alias version
retry.jsonSQS record with a JSON string bodyprove retry without a duplicate write
denied.jsona valid payload sent after the permission is removedprove the policy is the thing refusing
  1. Build the zip outside Terraform and record its base64 SHA-256. Confirm the plan shows the digest and no unrelated function change.
  2. Apply the function, alias, log group and role. Read back the alias version, the digest recorded in state and the role ARN, then invoke the alias directly and confirm one log line with the request id.
  3. Wire the HTTP API route to the alias and add the permission with the alias qualifier. Send the success fixture and expect a 2xx plus one downstream write.
  4. Remove the permission in a branch and apply. Send the same request; expect a 5xx from the API and no function log. Restore the permission and repeat the success test.
  5. Send the retry fixture to an idempotent handler that fails once after committing. Expect two attempts, one stored record and an empty dead-letter queue.
  6. Force a permanent failure and let the receive count reach the redrive limit. Expect the message in the dead-letter queue and the source queue depth back to zero.
  7. Remove one downstream action from the role policy and invoke again. Expect the invocation to succeed while the handler reports an access-denied error.
  8. Read the invoked function ARN from the response context, resolve the alias to its current version, and compare it with the version promoted in step 2. Record both in the release note.

Expected observation. Each test changes one layer only: removing the permission changes the API result without touching the handler, removing the role action changes the handler result without blocking invocation, and the retry produces one record rather than two.

Failure checks. The lab fails if a denied invocation still reaches the function, if a retry creates a duplicate, if the dead-letter queue receives a message the handler reported as successful, or if the observed alias version differs from the promoted one.

Cleanup. Delete the API, queue, dead-letter queue, alias and function after the last test, and remove the log group explicitly because Lambda does not delete it with the function.

Evidence to keep. The artifact digest, the alias and version pair, the permission statement diff, the retry attempt count, and one redacted log line from each outcome.

Redact at the boundary, not in the dashboard. Log an event identifier, outcome, duration and alias version; keep payloads out of logs unless the field is explicitly safe. A test that proves retry by printing the whole body has created a second incident in the log store.

Acceptance is a record, not a green check. The release is accepted when the digest, alias version, permission diff and test outcomes are written down together. That record is what lets the next person tell a code regression from a policy change without rebuilding the whole story.

Next in the Series

In Containers on AWS: ECR, ECS and EKS Ownership Boundaries, we'll explore Provision managed container infrastructure without mixing cluster creation and workload reconciliation.