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.
| Record | Terraform field | Why the plan needs it |
|---|---|---|
| Zip digest | code_sha256 | separates a code change from a settings change |
| Runtime | runtime | fixes the interpreter the handler expects |
| Architecture | architectures | rules out native dependencies built for another CPU |
| Handler | handler | names the entry point the runtime will call |
| Layer versions | layers | pins shared code to a version, not a name |
| Image digest | image_uri | makes 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.
%%{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 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.
| Setting | Lab value | Consequence to review |
|---|---|---|
| Memory | 512 MB | CPU scales with memory, so a timeout is not always a timeout problem |
| Timeout | 10 s | the handler stops before the edge budget, so the caller sees a function error |
| Runtime | python3.13 | the package must match the interpreter and its wheels |
| Architecture | arm64 | native dependencies must be built for arm64 |
| Reserved concurrency | 5 | caps blast radius and throttles callers at the quota |
| Log retention | 14 days | set 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.
%%{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.
| Object | Mutable? | Terraform address | Drift symptom |
|---|---|---|---|
| Code and settings | updated in place | aws_lambda_function | a plan that hides a package swap |
| Published version | immutable snapshot | aws_lambda_function with publish | an alias that still serves the old snapshot |
| Alias | pointer | aws_lambda_alias | traffic on a version no one promoted |
| Execution role | identity and policies | aws_iam_role plus attachments | an out-of-band policy grant |
| Log group | retention and class | aws_cloudwatch_log_group | a 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.
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.
| Source | Principal | Scope to narrow | Failure signature |
|---|---|---|---|
| API Gateway HTTP | apigateway.amazonaws.com | stage, method and path under the execution ARN | 5xx and no function log |
| API Gateway REST | apigateway.amazonaws.com | resource policy plus a statement on the function | 403 at the API or 5xx at the integration |
| EventBridge rule | events.amazonaws.com | the rule ARN, not just the service | failed invocations and retries |
| S3 notification | s3.amazonaws.com | the bucket ARN and source account | notification configuration rejected |
| SNS topic | sns.amazonaws.com | the topic ARN | delivery failure on the subscription |
| Function URL | * or an IAM principal | the URL auth type, never an open public grant | 403 at the URL |
| SQS mapping | no statement; role-based | queue ARN in the execution role | mapping 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.
| Boundary | Delivery | Ordering | Retry owner | Use when |
|---|---|---|---|---|
| Synchronous API | caller waits | per request | caller | fast reads inside the edge budget |
| Async invoke | at least once | none | Lambda, zero to two retries | fire and forget with a failure destination |
| SQS standard | at least once | best effort | poller plus queue redrive | buffer, backpressure, one consumer group |
| SQS FIFO | at least once, deduplicated | per message group | poller plus queue redrive | ordered work with a group key |
| EventBridge | at least once | none | EventBridge, up to 24 hours | facts, fan-out, content filtering |
| Step Functions | one execution, retried tasks | defined by the flow | state machine | multi-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.
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.
| Test | Setup | Expected | Evidence |
|---|---|---|---|
| Success | synthetic payload with a valid caller | 2xx and exactly one downstream write | request id and alias version |
| Retry | handler fails once, then succeeds | a second attempt, still one stored record | attempt count and empty DLQ |
| Denied invocation | remove the function permission | 5xx at the API, no function log | API log and policy diff |
| Denied downstream | remove one role action | invocation succeeds, handler reports denial | function 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.
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.
| Fixture | Shape | Purpose |
|---|---|---|
success.json | HTTP API proxy envelope, version 2.0 | prove the happy path and the alias version |
retry.json | SQS record with a JSON string body | prove retry without a duplicate write |
denied.json | a valid payload sent after the permission is removed | prove the policy is the thing refusing |
- Build the zip outside Terraform and record its base64 SHA-256. Confirm the plan shows the digest and no unrelated function change.
- 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.
- 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.
- 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.
- 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.
- 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.
- Remove one downstream action from the role policy and invoke again. Expect the invocation to succeed while the handler reports an access-denied error.
- 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.