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.
| Evidence | Recorded in | What it proves | What it cannot prove |
|---|---|---|---|
| Immutable tag | release manifest | which pipeline run produced the image | which bytes the tag pointed at during apply |
| Image digest | release record and function block | the exact image the platform should run | that the pull succeeded |
| Archive object version | function source block | which archive was deployed | that the runtime matches the handler |
| Application shape | application resource | the processor family the image must target | that 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.
%%{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.
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.
| Compartment | Owns | Policy attached there | Cost of merging it |
|---|---|---|---|
| platform-network | VCN, subnets, service gateway, NSGs | network use for the runtime and the gateway | the function team can change routes |
| functions | application, function, config | function write for deployers, invoke for consumers | runtime grants blur with deployment |
| edge | gateway, deployment, certificate | gateway use of the functions compartment | consumers inherit deployer visibility |
| artifacts | OCIR repository and images | repository read for the platform | image pushes inherit function admin |
| events | rule, queue, stream, topic | rule management and action use | retry 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.
%%{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.
| Identity | Assumed by | Needs | Symptom when absent |
|---|---|---|---|
| Caller | client or application | use of the API and a valid token | 401 or 403 at the gateway |
| Gateway principal | API Gateway service | use functions-family in the functions compartment | gateway failure with no function log |
| Function principal | OCI Functions runtime | data actions named by target | handler starts, downstream call is denied |
| Event principal | Events service | use functions-family for the action | rule matches, no invocation |
| Deployer | pipeline group or user | function write, plus network read for the app | apply fails before the change lands |
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.
| Contract | Delivery | Retry owner | Ordering and replay | Poison path |
|---|---|---|---|---|
| Events to Functions | at least once | rule action | none, duplicates possible | retry budget, no rule DLQ |
| Detached invocation | accepted once, outcome recorded | delivery to the destination | none | success and failure destinations |
| OCI Queue | at least once | consumer visibility | none, backlog retained | dead-letter after delivery count |
| Streaming | at least once per consumer | consumer cursor | ordered per partition, replay window | consumer checkpoint |
| Notifications | at least once | topic subscription | none, no replay | subscription 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.
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
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.
| Object | Lab value | Why it matters |
|---|---|---|
| Application | private subnet, service gateway, one shape | separates routing from code |
| Function | 256 MB, 30-second sync timeout, explicit digest | a slow handler hides retry timing |
| Image | immutable tag plus digest | the release record can name one build |
| Gateway | one deployment, one route, one auth mode | isolates the invocation hop |
| Event rule | one event type, one action, one function | filter and grant are visible |
| Queue | one failure destination, delivery count | a record is evidence, not work |
- 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_detailsbefore writing any configuration. - 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Create a rule with
condition_detailsfor one Object Storage event type and one Functions action. Upload a matching object and expect one invocation, one idempotency record and no failure record. - 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.
- 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.
- 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.
- 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.