Back to Terraform

OCI Serverless: Functions, API Gateway and Event Delivery

November 6, 2026 Wasil Zafar 26 min read

Coordinate application images and infrastructure with resource-principal and invocation boundaries

Table of Contents

  1. Build the Function Image Before the Infrastructure Plan
  2. Map Application and Function Infrastructure to Compartments
  3. Trace Resource Principal and Gateway Invocation Permissions
  4. Choose Events, Notifications or Streaming by Delivery Contract
  5. Test a Synthetic Request and a Denied Caller

Build the Function Image Before the Infrastructure Plan

The image is the release unit; Terraform only records where it lives. Applying a function writes metadata and never pulls the bytes. OCI Functions pulls the image on the first invocation, through the subnets of the application, so a clean apply can still be followed by a failure before any handler runs.

Pin two identifiers, not one. The tag answers "which release" and the digest answers "which bytes". source_details accepts both, and the digest is the only field that makes a moved tag visible to a plan.

A mutable tag makes two releases look identical. When CI overwrites a floating tag, the configuration string does not change and Terraform proposes nothing. Use a tag derived from the commit or build id, then record the resolved digest in the release record outside state.

The deprecated fields are a review signal. The top-level image and digest arguments remain for compatibility, but source_details wins when both are present. New configuration should use the block, and a review should treat the older pair as unfinished migration.

Architecture is an application property, not an image detail. The application accepts a generic x86 shape, a generic Arm shape, or a mixed x86-Arm shape, and defaults to x86. An Arm-only image on an x86 application pushes cleanly and then fails at execution, which is a build-and-runtime mismatch rather than a Terraform error.

Registry ownership belongs in the same decision. The image should sit in Oracle Cloud Infrastructure Registry in the function's region, in a repository the platform can read. A repository in another region is not a supported shortcut, and a repository in another compartment is a policy question rather than a networking one.

Code-only functions change the artifact, not the rule. An ARCHIVE source points at an Object Storage object and a managed runtime; pin the object version, because the key alone can be overwritten by the next upload.

EvidenceRecorded inWhat it provesWhat it cannot prove
Immutable tagrelease manifestwhich pipeline run produced the imagewhich bytes the tag pointed at during apply
Image digestrelease record and function blockthe exact image the platform should runthat the pull succeeded
Archive object versionfunction source blockwhich archive was deployedthat the runtime matches the handler
Application shapeapplication resourcethe processor family the image must targetthat the image is multi-arch

Promotion is a replacement, not a pointer move. In provider 9.12.1 there is no separate version or alias resource for a function, so a release changes the image reference on the function itself. Keep the previous digest beside the release record; that value is the rollback, and without it the previous build has to be rediscovered.

Build the Function Image Before the Infrastructure Plan
%%{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','tertiaryColor':'#c4873b','tertiaryTextColor':'#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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    C["Commit and build id"] --> B["CI builds the image
immutable tag, not latest"] B --> P["Push to OCIR
same region as the function"] P --> D["Resolve the digest
record it with the release"] D --> F["oci_functions_function
source_details CONTAINER_IMAGE"] F --> A["oci_functions_application
shape matches the image"] A --> R["First invocation
pull through the app subnet"] R --> OK["Handler runs
release marker matches"] B -.->|"tag reused"| X1["Plan sees the same string
old bytes keep serving"] D -.->|"digest omitted"| X2["A moved tag is invisible
rollback becomes a guess"] A -.->|"arm image on x86"| X3["Build succeeds
execution fails"] R -.->|"no service gateway"| X4["502 image pull
before any log"] 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,D primary; class P,F,A secondary; class R,OK ok; class X1,X2 warn; class X3,X4 danger;

Figure 1 follows one artifact from commit to first pull. The top path is reproducible because the tag is never reused and the digest is recorded. The dashed branches are the failures that survive a green apply, and each one has a different owner.

The release artifact crosses four boundaries before the handler runs Four panels show the CI build, the container registry, the function definition and the runtime pull. The build produces an immutable tag, the registry resolves a digest, the function records that digest in source details, and the first invocation pulls the image through the application subnet. A crimson footer states that an apply records a reference while the first invocation proves the pull. Four boundaries, one digest Terraform owns the middle two panels. The platform owns the last one. 1. CI BUILD commit and build id immutable tag image architecture pushed by pipeline The build never touches Terraform state or the plan. 2. REGISTRY OCIR repository same region resolved digest tag can move The digest is the only identity that cannot be reused. 3. FUNCTION source_details image plus digest memory and timeout config keys The resource records what should run, not what did run. 4. RUNTIME PULL application subnet service gateway or internet gateway egress to OCIR The pull happens at invocation, not at plan or apply. Apply success is not invocation success A function can be created with a valid reference and still fail on first call when the subnet has no route to the registry. The error names the image pull, not the policy or the handler.

Figure 2 separates what you can compare from what the platform does. The build and registry columns are evidence a reviewer can check before apply. The function block is intent, and the runtime column is the only place where a pull failure becomes visible.

Map Application and Function Infrastructure to Compartments

An application is a network and configuration boundary before it is a grouping. oci_functions_application fixes the subnets, the processor shape, the network security groups and the shared config. Each function inherits them, and a function-level config key overrides the application value.

Functions run inside the application's subnet, not in a service-managed VCN. That one sentence explains most networking failures: the subnet needs a route and an egress rule to the registry and to every OCI service the handler calls.

A private subnet needs a service gateway. The route must target all services in the Oracle Services Network, and the security list or NSG must allow egress to the registry. Without it the function fails with FunctionInvokeImageNotAvailable, which looks like a bad image rather than a missing route.

Public subnets trade a gateway for exposure. They need an internet gateway and an egress rule to the service network, and the function becomes reachable from a broader path than a private subnet would allow.

Compartments bound policy and cost, not packets. Two resources in different compartments can still talk; what changes is who may grant access and where the bill lands. A network compartment that also owns the function makes the gateway's policy hard to scope.

CompartmentOwnsPolicy attached thereCost of merging it
platform-networkVCN, subnets, service gateway, NSGsnetwork use for the runtime and the gatewaythe function team can change routes
functionsapplication, function, configfunction write for deployers, invoke for consumersruntime grants blur with deployment
edgegateway, deployment, certificategateway use of the functions compartmentconsumers inherit deployer visibility
artifactsOCIR repository and imagesrepository read for the platformimage pushes inherit function admin
eventsrule, queue, stream, topicrule management and action useretry ownership becomes ambiguous

The gateway needs its own network path. A public gateway sits in a public subnet behind an internet gateway; a private gateway needs a route from its subnet to the target. The functions must be routable from the gateway's VCN, which is a routing check rather than a policy check.

Config is data, not identity. Function and application config keys become environment variables and are stored in the definition, so they are visible to anyone who can read the resource and to anyone who can read state. Put secrets in Vault and read them through the execution principal instead.

Capacity is a pre-plan check, not a post-bill surprise. Function memory, provisioned concurrency, gateway count, stream partitions and queue retention all have regional limits. Record the requested values and the owner of the quota increase in the same change that raises them.

Three subnets is the documented ceiling for an application. Prefer a regional subnet so a failed availability domain does not take the function with it, and keep the application in the same region as the registry it pulls from.

Map Application and Function Infrastructure to Compartments
%%{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','tertiaryColor':'#c4873b','tertiaryTextColor':'#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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    T["Tenancy
root compartment"] --> N["platform-network
VCN, subnets, gateways"] T --> F["functions
application and function"] T --> E["edge
gateway and deployment"] T --> R["artifacts
OCIR repository"] T --> V["events
rule, queue, stream, topic"] N --> S["private application subnet
regional, up to three"] S --> SG["service gateway route
all services in OSN"] SG --> R F --> A["function config
memory, timeout, shape"] E --> G["gateway subnet
public or private"] G --> A T --> I["tenancy policy
dynamic groups"] I --> A I --> G S -.->|"no service gateway"| X1["502 image pull
no handler log"] G -.->|"no route to the VCN"| X2["gateway error
before invocation"] A -.->|"quota or shape mismatch"| X3["apply or execution fails
with a limit message"] 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 T,I primary; class N,F,E,R,V secondary; class S,SG,A,G ok; class X1,X2,X3 danger;

Figure 3 is the order to verify a deployment. Compartments decide who may change each object, the subnet route decides whether the image can be pulled, and the gateway route decides whether a caller reaches the API. A plan can satisfy the first and fail the second.

Trace Resource Principal and Gateway Invocation Permissions

Every request crosses three authorization decisions. The caller must be allowed to use the API, the gateway must be allowed to invoke the function, and the function must be allowed to reach its data. They belong to different principals, and they fail with different evidence.

The gateway is a resource principal, not a proxy for the caller. Its permission is a policy on the functions compartment, conditioned on the gateway's compartment. The caller's group membership is irrelevant to that hop, which is why an authenticated caller can still produce a gateway failure.

Scoping is what turns any-user into a narrow grant. The statement pairs the verb with a principal type and a compartment condition, so a gateway in another compartment cannot invoke the function. The exact form used in the lab is ALLOW any-user to use functions-family in compartment <functions> where ALL {request.principal.type = 'ApiGateway', request.resource.compartment.id = '<gateway-compartment>'}.

A dynamic group is the alternative spelling. Match resource.type = 'ApiGateway' in a dynamic group, then grant that group use functions-family. It reads narrower in a review but adds a principal object that must be maintained as gateways change.

Gateway authentication and invocation permission answer different questions. A JWT policy decides who may call the route; it does not let the gateway call the function. An anonymous route removes the first check and keeps the second, so a public endpoint still needs the resource grant.

The function's execution identity comes from a dynamic group. Match resource.type = 'fnfunc' for every function in a compartment, or resource.id for one function, then grant only the data actions the handler uses. The platform injects a short-lived token; no access key belongs in the image.

Scope the data grant with a target condition. A policy on the dynamic group can name one bucket, one stream or one secret, which keeps a compromised handler inside the data boundary it was given.

Deployers need a different set of verbs. Function creation needs write actions on the application, while whoever creates the application needs network read for the subnet reference; the runtime principal needs neither. Keep deployment and execution in separate groups, and review the diff between them.

Events has its own service principal. A rule that calls a function requires a grant to cloudEvents; without it the rule can exist, match an event and deliver nothing. The same pattern applies to a queue or a stream destination.

Restrict who may invoke, not just who may deploy. A function grant can be conditioned on the caller's principal type, which is how a function stays private to one gateway, one queue or one scheduler.

IdentityAssumed byNeedsSymptom when absent
Callerclient or applicationuse of the API and a valid token401 or 403 at the gateway
Gateway principalAPI Gateway serviceuse functions-family in the functions compartmentgateway failure with no function log
Function principalOCI Functions runtimedata actions named by targethandler starts, downstream call is denied
Event principalEvents serviceuse functions-family for the actionrule matches, no invocation
Deployerpipeline group or userfunction write, plus network read for the appapply fails before the change lands
Invocation and execution are granted to different principals The invocation lane runs from a caller through API Gateway, the gateway principal grant and the function edge. The execution lane runs from function code through a dynamic group to a bucket or stream. A crimson strip maps a gateway rejection with no function log, an invocation denial with no container start, a downstream denial with a container log, and a rule that never fired. Two chains, three grants The caller is allowed in. The function is allowed out. INVOCATION PATH Caller JWT, token or anonymous gateway decides access not a function grant API Gateway validates the request assumes its principal route names the function Gateway grant any-user plus condition principal type ApiGateway scoped by compartment Function edge invocation admitted runtime starts log begins here EXECUTION PATH Function code runs as the function receives a short-lived resource principal token Dynamic group resource.type fnfunc or resource.id membership, not a role Data boundary bucket, stream, queue or secret named by target policy verb chosen from the handler's calls no wildcard compartment grant Where the refusal appears 401 or 403 at the gateway no function log 404 at invocation no container start 403 downstream container log exists Rule never fired action grant or filter The gateway grant calls the function. The dynamic group calls the data.

Figure 4 draws the two chains as separate grants. The invocation chain ends at the function edge, and the execution chain starts inside the container. One identity across both chains would give the gateway, or the caller behind it, the function's data access.

A missing function log is evidence, not a logging problem. If the request never reached the container, the invocation was refused before the runtime started. Look at the gateway grant or the rule action first, and at the handler last.

Choose Events, Notifications or Streaming by Delivery Contract

Events routes facts; it does not store work. A rule filters CloudEvents from its own compartment and child compartments, then delivers to Notifications, Streaming or Functions. Delivery is at-least-once with retries, so duplicate events are part of the contract rather than an exception.

An action list is fan-out, not a fallback chain. Every action in the rule receives the event, and one failing destination does not promote another. If two consumers must both succeed, that is two actions and two failure paths, not one reliable path.

A queue is the boundary for work that must wait. OCI Queue holds a message until a consumer deletes it or the visibility timeout expires, and a delivery count moves a poison message to the dead-letter queue. That is backlog control, which an event rule does not provide.

Streaming is the boundary for history and replay. Records are ordered inside a partition, retained for the stream's window, and read by consumers that commit a cursor. Two consumers can read the same record independently, which is what makes replay and a second reader possible.

Notifications is the boundary for people and broadcast. A topic pushes to its subscriptions and retries delivery, but it is not a backlog and it has no cursor to replay. A failed human notification is an operational event, not a work item.

Events cannot target a queue directly. The documented actions are Notifications, Streaming and Functions. Queue-backed work needs a consumer or a connector in front of the function, which also becomes the owner of pacing and retries.

Detached invocation adds an outcome record, not a retry loop. A detached call returns 202, and Functions writes an invocation record to the success or failure destination. The record is the outcome of that execution; whatever happens next belongs to the consumer of the destination, which is why the queue or stream needs its own policy.

The destination grant belongs to the function application. The policy conditions on request.principal.type = 'fnapp', because Functions writes the record after the caller has gone. A missing grant leaves the invocation successful and the record undelivered.

ContractDeliveryRetry ownerOrdering and replayPoison path
Events to Functionsat least oncerule actionnone, duplicates possibleretry budget, no rule DLQ
Detached invocationaccepted once, outcome recordeddelivery to the destinationnonesuccess and failure destinations
OCI Queueat least onceconsumer visibilitynone, backlog retaineddead-letter after delivery count
Streamingat least once per consumerconsumer cursorordered per partition, replay windowconsumer checkpoint
Notificationsat least oncetopic subscriptionnone, no replaysubscription retry

Idempotence is keyed on the event, not the request. Store the CloudEvents id before the side effect, or make the write conditional on that id. A retry then produces one record and two log lines, which is the observable signature of a correct handler.

One event has four places to be lost before it becomes work An event producer sends an event to a rule filter, then to an action grant, then to a destination. Three destinations are shown: Functions, Streaming and Notifications. Dashed branches show a filter miss, a denied action, a handler failure that goes to a detached failure destination, and a poison message that reaches a queue dead-letter path. A footer separates event, work, history and broadcast. One event, four failure points Each arrow has a different owner and different evidence. Producer resource change CloudEvents envelope Rule filter eventTypes and data compartment scope Action grant cloudEvents to functions-family Function handler runs idempotent record Acknowledge one event, one record duplicate tolerated No match no invocation, no log Action denied no container start Handler fails failure record written Failure destination queue, stream or topic Queue dead-letter after delivery count Event a fact, fan-out no backlog Queue work that waits visibility and DLQ Stream history and replay ordered per partition Topic broadcast to people retry, no replay An event is a fact, a queue is work, a stream is history, a topic is broadcast.

Figure 5 follows one event until it is either recorded or parked. The filter, the action grant, the handler result and the destination are four independent places to lose it. The footer is the decision rule: choose the contract first, then the service.

If the trigger needs three clauses to explain, it is doing two jobs. A bucket event that starts a resizer and a queue consumer that paces uploads are different contracts with different retry owners. Split them before the retry behavior becomes the design.

Test a Synthetic Request and a Denied Caller

Lab

Test a Synthetic Request and a Denied Caller

Status: design-only. No Oracle Cloud account, credential or billable resource was used, and these steps were not executed. Versions: Terraform CLI 1.17.1, oracle/oci 9.12.1, checked against vendor documentation on 6 November 2026.

Prerequisites. A sandbox tenancy with Functions, API Gateway and Events available in one region, a VCN with a private regional subnet and a service gateway, one OCIR repository, one Object Storage bucket, one queue for failure records, and permission to read function logs, gateway logs and rule metrics. Keep memory small and timeouts short so the lab stays cheap.

Setup. The handler returns its own name, the configured release marker and the event id it received. Before any side effect it writes one idempotency record keyed by that id. The business logic stays trivial; the lab tests identity and delivery, not code.

ObjectLab valueWhy it matters
Applicationprivate subnet, service gateway, one shapeseparates routing from code
Function256 MB, 30-second sync timeout, explicit digesta slow handler hides retry timing
Imageimmutable tag plus digestthe release record can name one build
Gatewayone deployment, one route, one auth modeisolates the invocation hop
Event ruleone event type, one action, one functionfilter and grant are visible
Queueone failure destination, delivery counta record is evidence, not work
  1. Pin Terraform 1.17.1 and provider 9.12.1, run init, and read the schema for the function and deployment resources. Confirm that the image fields live under source_details before writing any configuration.
  2. Build the image in CI, tag it with the commit, push it to the repository in the function's region, and record the resolved digest in the release record. Never retag an existing image for a new release.
  3. Apply the application first, then the function with the digest, then the gateway and deployment. Read both back: the function reports its digest and the deployment reports its route.
  4. Invoke the function directly with a signed request and a small JSON body. Expect the release marker from the promoted build, not from the newest commit in the repository.
  5. Call the same function through the deployment route. Expect the same marker and a gateway access log entry; a different marker means the route points at another function.
  6. Remove the gateway grant, call again and expect a gateway failure with no function log. Restore the grant and allow for propagation before judging the policy.
  7. Keep the gateway grant but remove one data permission the handler needs, such as reading the bucket. Expect the function to start and then fail downstream, with a container log that names the denied call.
  8. Create a rule with condition_details for one Object Storage event type and one Functions action. Upload a matching object and expect one invocation, one idempotency record and no failure record.
  9. Upload an object that does not match the filter and expect no invocation. Then disable the rule, upload a matching object and expect no delivery while the function stays healthy; this separates a filter problem from a grant problem.
  10. Simulate a redelivery by invoking the handler twice with the same event JSON. Expect two log lines and one idempotency record. One record means the key is right; two records mean the side effect runs before the key is checked.
  11. Invoke in detached mode with a failure destination and make the handler fail. Expect an accepted response and one failure record in the queue that names the error, which proves the outcome path is wired.
  12. Set the function back to the previous digest, invoke through the gateway and expect the previous marker without a rebuild. This is the rollback test, and it fails if the previous digest was never recorded.

Expected observation. A sequence, not a duration: a direct call and a gateway call that return the same release marker, a denial with no function log, a downstream denial with a container log, one event with one record, two attempts with one record, one failure record that names the failed execution, and a rollback that returns the previous marker.

Failure checks. The lab fails if a denied caller still starts the function, if a duplicate event creates a second record, if a non-matching event invokes the function, if the failure destination receives a record for a successful invocation, or if rollback requires a new image build.

Cleanup. Delete the rule, then the deployment, the gateway and the function. Only then delete the queue and stream used as destinations, followed by the application; leave the shared VCN and service gateway in place. Keep the release record and the last good digest until the rollback window closes.

Evidence to keep. Function OCID, application OCID, image digest, gateway and deployment names, the gateway, execution and event policy statements, one redacted log line per outcome, and the failure-record count.

Next in the Series

In OCI Vault: Keys, Secrets, Principals and Rotation Evidence, we'll explore Treat secret storage and Terraform artifact persistence as distinct controls.