Back to Terraform

Function Compute and Events: Application Artifacts, APIs and RAM Permissions

November 6, 2026 Wasil Zafar 26 min read

Wire serverless code and cloud events using release-specific resources and explicit identities

Table of Contents

  1. Choose the Current Function Compute API and Resource Model
  2. Build and Promote a Reproducible Code Artifact
  3. Trace API and Event Invocation Through RAM
  4. Select an EventBridge, Queue or OSS Trigger Contract
  5. Test One Event and One Denied Operation

Choose the Current Function Compute API and Resource Model

Provider 2.2.0 ships two Function Compute generations, and only one is current. The alicloud_fc_* family models a service that contains functions, while the alicloud_fcv3_* family models the function directly. The provider marks the legacy function resource deprecated and recommends FCV3 for new deployments.

The split is not cosmetic; it changes which object owns identity. In the legacy model the service carries the execution role and the log configuration, and each function inherits them. FCV3 has no service resource, so the function itself carries its role, logging and network settings.

The provider pin belongs in the same commit as the resource family. Terraform 1.17.1 and provider 2.2.0 are the tested pair here; a range such as >= 2.0 can resolve a later release with a different schema. The lock file records what the runner actually installed.

FCV3 arrived in provider 1.228.0 and keeps a familiar function vocabulary. Runtime, handler, memory, disk, timeout, concurrency and code are fields on one resource. The version and alias resources then give that function a release history.

Two resource generations are a migration boundary, not a compatibility layer. A plan can contain both families, but an FCV3 alias cannot point at a legacy service version. Decide per function, record the choice, and retire the old family instead of running both.

SurfaceLegacy modelFCV3 modelWhat review must catch
Containerservice holds functionsfunction is top levela plan that still creates a service
Execution roleon the serviceon the functionrole copied from the wrong generation
Releaseservice versionfunction version plus aliastrigger pinned to LATEST
API backendfunction_version 2.0function_version 3.0default left at 2.0
Loggingservice log_configfunction log_configlogs written to an old project

A default field can silently select the old generation. The API Gateway backend block accepts both generations, but function_version defaults to the legacy value. A 3.0 function addressed by a backend that still says 2.0 fails at invocation even though both resources applied cleanly.

Read last_update_status after apply. The function reports the result of its last create or update, and a failed update can leave the previous configuration serving. That field, not the green apply line, says whether the new artifact reached the function.

The version and alias are the release contract. A version freezes the function as it exists, and an alias gives that frozen version a stable name. Callers and triggers should use the alias, because a version id changes with every release.

Choose the Current Function Compute API and Resource Model
%%{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
    A["New function or existing service?"] -->|"new"| B["alicloud_fcv3_function
function carries role and logging"] A -->|"existing"| C["Legacy alicloud_fc_service
plus alicloud_fc_function"] C --> C1{"Migrate this release?"} C1 -->|"no"| P["Pin the provider and schema
keep the legacy pair together"] C1 -->|"yes"| B B --> D["alicloud_fcv3_function_version
freeze code and configuration"] D --> E["alicloud_fcv3_alias
stable qualifier for callers"] E --> F{"Who invokes it?"} F -->|"API Gateway"| G["fc_service_config
function_version 3.0"] F -->|"trigger"| H["fcv3_trigger
qualifier = alias"] G --> OK["Release record names
version, alias and artifact"] H --> OK G -.->|"default left at 2.0"| X1["Backend fails at invocation
resources applied cleanly"] H -.->|"qualifier LATEST"| X2["Promotion does not move traffic"] P -.->|"mixed generations"| X3["Alias cannot target
a legacy service version"] 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 A primary; class B,C,D,E,G,H secondary; class F,C1 warn; class OK ok; class P warn; class X1,X2,X3 danger;

Figure 1 is a decision, not a catalogue. New functions start on FCV3; existing services either stay pinned or migrate as a unit; API Gateway and trigger qualifiers are checked against the same alias.

Two Function Compute resource models under one pinned provider The provider release and lock file are shared. The legacy model places a function inside a service that owns the execution role and logging. The FCV3 model places role, logging and code on the function itself, with a version and alias above it. A crimson footer warns that a 2.0 API Gateway backend default against a 3.0 function fails at invocation. Two generations, one function boundary The provider still ships both. New work starts on the right. PROVIDER 2.2.0 Terraform 1.17.1 pinned aliyun/alicloud 2.2.0 lock file committed schema read after init A floating range can resolve a later schema. Read the installed schema, not a tutorial. LEGACY FC Service role, logging, network the inherited boundary Function code, runtime, handler inside the service Service version the legacy release unit FCV3 Function code, runtime, role, logging no service wrapper Function version immutable snapshot Alias stable qualifier, optional weight Triggers and API backends name the alias. A 2.0 backend default against a 3.0 function fails at invocation, not at plan.

The boundary to review is the function, its version and its alias. Everything that invokes the function should name the alias, and everything that changes the function should produce a new version. That single rule removes most of the ambiguity between the two generations.

Build and Promote a Reproducible Code Artifact

An artifact is built before Terraform runs, and Terraform only records where it landed. A zip or container image is produced by CI, stored under an identifier, and referenced by the function. If the identifier is mutable, the plan cannot tell two releases apart.

Three artifact forms leave different evidence. The table maps what the pipeline hands over to what the function can prove later.

Artifact formFunction fieldIdentifier recordedFailure when mutable
Zip uploaded to OSScode blockbucket, object key, CRC-64same key overwritten, plan unchanged
Inline base64 zipzip_filebase64 payload in statediff is unreadable and state grows
Custom containercustom_container_configimage string, resolved digesttag moves, function keeps old digest

The OSS object is the better default for a reviewed release. A content-addressed key such as a commit or build id makes the reference unique, and the function keeps the bucket and object name in state. Reusing that key without a checksum is a silent replacement.

The checksum turns an object name into an artifact identity. FCV3 accepts a CRC-64 checksum beside the bucket and object, and the provider exposes a checksum data source for local files. Without it, Terraform compares names, not bytes.

The provider documents a code-update edge that a release process must not ignore. The code block applies during create and update, but an isolated code change may not trigger an action. Promote through a version and verify the plan rather than trusting a no-op apply.

Promotion is publish, then move a pointer. The version resource snapshots the function, and the alias resource points a stable name at a version, optionally with weights for a canary. Triggers, API backends and callers all address the alias, and a trigger qualifier is ForceNew, so settle the alias before the first trigger exists.

A version has no field that names the artifact it captured. The version record carries a version id and a description, not the OSS key or checksum. Join it to the release record in the pipeline, or the next rollback is a guess.

Rollback is an alias update, not a rebuild. Move the alias back to the previous version and keep the artifact that version was built from. Rebuilding an old commit during an incident tests the build system at the worst moment.

Two writers on the code block produce drift. If the pipeline updates the function code while Terraform owns the resource, the next apply reverts the deploy. Give the code field one owner, and put the boundary in the ownership table rather than an ignore rule nobody reviews.

Build and Promote a Reproducible Code Artifact
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    S["Commit and build id"] --> B["CI builds the zip
outside Terraform"] B --> C["CRC-64 checksum
and content-addressed key"] C --> U["OSS object
immutable by convention"] U --> F["alicloud_fcv3_function
code block names bucket, key, checksum"] F --> V["alicloud_fcv3_function_version
immutable snapshot"] V --> A["alicloud_fcv3_alias
version id and optional weight"] A --> Q["Trigger or API qualifier
names the alias"] Q --> OK["Requests report
the promoted version"] C -.->|"same key reused"| X1["Plan sees the same name
old bytes keep serving"] F -.->|"code edited alone"| X2["Provider may not trigger
an update, verify the plan"] A -.->|"alias still on LATEST"| X3["Rollback has no
version to return to"] Q -.->|"trigger pinned to a version id"| X4["Promotion leaves the
trigger on old code"] 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 S,C primary; class B,U,F secondary; class V,A,Q,OK ok; class X1,X2,X3,X4 danger;

Figure 2 separates the build from the release pointer. The checksum identifies the bytes, the version freezes the configuration, and the alias decides which frozen version receives traffic. A failure at any arrow has a different remedy.

A container release has the same shape with a different identifier. The custom container block accepts an image reference, and the function reports the resolved digest it actually runs. Record that digest, not only the tag the pipeline pushed.

Trace API and Event Invocation Through RAM

A single request crosses at least three authorization decisions. The caller must be allowed to reach the endpoint, the invoking service must be allowed to call the function, and the function must be allowed to reach its data. They are granted to different principals and fail with different evidence.

Four identities appear in a working deployment. The table is the review artefact: each row has a different holder and a different scope.

IdentityAssumed byNeedsScopeSymptom when absent
Caller or appclientapp authorization on the APIone API and stage401 or 403 at the gateway, no function log
Invocation roleAPI Gateway, EventBridge, OSS or MNSfc:InvokeFunction on the functionone function or aliasinvocation refused before the container starts
Execution roleFunction Computedata actions used by codenamed buckets, logstores, tablesfunction runs, downstream call returns 403
Deployerpipeline principalFC write actions and ram:PassRolethe stack's functions and rolesapply fails before or during function update

API Gateway authentication is not RAM. An APP-authorized API checks the app key and its attachment; an anonymous API checks nothing at the gateway. Neither decision grants the backend permission to invoke the function.

The API Gateway role is assumed by the gateway, not by your code. Its trust policy names the API Gateway service principal for the account, and its permission policy needs the invoke action on the target function. A role that trusts Function Compute instead will not be assumable by the gateway.

The provider description of that role is broader than the role's job. It says the field governs both invocation and function access, which reads as if one role did both. Keep the gateway role and the function execution role separate; only the second is passed to your code as temporary credentials.

EventBridge uses a service-linked role instead of a trigger role. The AliyunServiceRoleForEventBridgeSendToFC role is created for the EventBridge service and carries the invoke permission. If it is missing, the rule can exist and still deliver nothing.

Native event sources use a trigger-level role. An OSS trigger assumes a role trusted by OSS and carrying the OSS notification policy, while an MNS topic trigger uses AliyunMNSNotificationRole. The trigger, not the function, is where that grant belongs.

The explicit execution role is the only identity your code inherits. Function Compute assumes it at invocation and exposes temporary credentials through the context. Give it the specific bucket, logstore or table actions the handler uses, and nothing from the invocation path.

Passing a role is a separate permission from using it. The deployer needs the pass-role action on each role it attaches, conditioned on the Function Compute service. An apply that fails on role passing is not a missing function permission.

A cross-account API is two agreements. The target account's role trusts the source account's API Gateway principal and allows invocation; the source backend names that role's ARN. Remove either side and the call stops at the gateway.

Read the refusal location before editing a policy. A gateway rejection, a refused invocation and a downstream denial name three different holders. The presence or absence of a function log separates them faster than the policy text.

Invocation chain and execution chain are authorized by different roles The invocation lane runs from a caller through API Gateway, an invocation role and the function edge. The execution lane runs from the function through its execution role to OSS or a logstore. A failure strip maps a gateway rejection with no function log, a refused invocation with no container start, and a downstream denial with a container log. Two chains, three roles The caller is allowed in. The function is allowed out. INVOCATION PATH Caller or app app key, or anonymous gateway decision only not a RAM grant API Gateway assumes the backend role trust: apigateway principal needs fc:InvokeFunction Invocation role scoped to one function or one alias EventBridge uses an SLR Function edge invocation admitted runtime starts log begins here request assume invoke EXECUTION PATH Function code runs as the function role receives temporary creds no access keys in code Execution role trust: fc.aliyuncs.com policy: bucket, logstore attached to the function Downstream API OSS object read or write logstore write Tablestore or VPC service assume call One role for both chains lets the caller read data. Where the refusal appears Gateway 401 or 403 no function log Invocation 403 no container start Downstream 403 container log exists No event at all rule, SLR or filter The invocation role calls the function. The execution role calls the data.

Figure 3 draws the two chains separately. The invocation chain ends at the function edge, and the execution chain starts inside the container. A single role across both chains grants the caller the function's data access.

A missing container log is evidence, not a logging bug. If the request never reached the function, the invocation was refused before the runtime started. Look at the gateway or trigger first, not at the handler.

Select an EventBridge, Queue or OSS Trigger Contract

A trigger choice is a choice about who owns the retry. EventBridge rules, MNS topics and native OSS triggers retry in different places, with different budgets and different poison paths. Name the owner before choosing the product.

Event or queue is a boundary about work, not transport. An event says something happened and may fan out to several consumers; a queue holds work until a consumer is ready. A function behind an event should be idempotent and fast, while backlog and pacing belong to a queue.

ContractDeliveryRetry ownerOrderingPoison path
EventBridge ruleat least onceEventBridge target policynonedead-letter queue
MNS topic triggerat least onceMNS notify strategynoneretry exhaustion, then discard
Native OSS triggerat least onceFunction Compute triggernone per objectno trigger DLQ
Async invocationat least onceFunction Compute async policynoneasync destination
Timerper scheduleFunction Compute triggerschedule ordermissed run, no payload

The EventBridge trigger can create its own rule. Function Compute creates a rule named after the function and trigger on the default bus, which makes the trigger the owner of the filter. Declaring a second rule for the same event duplicates the invocation rather than adding reliability.

EventBridge trigger configuration carries the retry policy. The run options include a retry strategy, an error-tolerance choice, a dead-letter queue and an optional batch window. Set them on the trigger when the trigger owns the rule, or on the rule when you own it.

The async flag is named for async but documents the reverse meaning. The trigger schema describes true as synchronous invocation and false as asynchronous, with asynchronous as the default. Read the field from the schema and test the path instead of trusting the name.

Async invocation has a second retry budget. Function Compute retries a failed asynchronous invocation up to three times by default, configurable from zero to eight, and the trigger-level policy may also apply. Two budgets mean two counts; the test must say which one it expects.

A logic error in an async handler does not reach the trigger dead-letter queue. The failure is delivered to the asynchronous invocation destination configured on the function. A DLQ that stays empty after a failed async handler is behaving as documented, not silently broken.

MNS topic delivery is push with a tag filter. The trigger registers the function as a subscriber, filters on the message tag, and chooses a JSON or stream event shape. Retry is a notify strategy, not a function setting.

Native OSS and EventBridge-based OSS triggers are different contracts. The native trigger requires the bucket and function in one region, supports one prefix and suffix pair, and emits the OSS event template. The EventBridge variant supports CloudEvents or raw data, multiple patterns and cross-region routing.

Prefix and suffix overlap is rejected at creation. Two triggers on one bucket cannot share an event type with the same match range, and an unset prefix matches everything. Give source and output objects disjoint prefixes or the second trigger fails to create.

A timer has no event source role. It runs on a cron expression and does not need an invocation role, which makes it the cleanest way to test the execution path in isolation. Its failure is a missed or overlapping run, not a lost message.

One event has four places to be lost before acknowledgement An event bus sends an event to a filter, then to an invocation grant, then to a handler, then to acknowledgement. Dashed branches show a filter miss, a denied invocation with no container log, a retry budget that ends in a dead-letter queue, and an asynchronous failure that goes to the async destination instead. A footer separates native OSS triggers from EventBridge-based OSS triggers. One event, four failure points Each arrow is a separate owner with separate evidence. Event bus event published id and source Filter pattern matched or dropped Invocation grant role or SLR allows fc:InvokeFunction Handler runs as execution role, writes record Acknowledge one record, empty dead-letter queue No match no invocation, no log Invocation denied no container start Handler fails retry budget starts Dead-letter queue after retries exhausted Async destination logic error goes here Native OSS trigger same region, one prefix and suffix pair OSS event template only, no CloudEvents EventBridge-based OSS trigger cross-region routing, multiple patterns CloudEvents or raw data, shared rule budget An event is a fact, a queue is work, and a retry budget belongs to exactly one of them.

Figure 4 follows one event until it is acknowledged or parked. The filter, the invocation grant, the handler result and the retry budget are four independent places to lose it. The footer keeps the two OSS contracts apart.

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. Split them before the retry behaviour becomes the design.

Test One Event and One Denied Operation

Lab

Test One Event and One Denied Operation

Status: design-only. No Alibaba Cloud account, credential or billable resource was used, and these steps were not executed. Versions: Terraform CLI 1.17.1, aliyun/alicloud 2.2.0, verified 6 November 2026.

Prerequisites. A sandbox account with Function Compute and EventBridge activated, one OSS bucket in the function region, one MNS topic, one MNS queue for the dead-letter target, an API Gateway group, two RAM roles for invocation and execution, and permission to read function logs, gateway logs and rule metrics. Cost stays bounded by a small memory setting and a short timeout.

Setup. The handler returns its function name, qualifier and a version marker from an environment variable, and writes one idempotency record keyed by the event id before it can fail. Keep the logic trivial; the lab tests identity and delivery, not business code.

ObjectLab valueWhy it matters
Function128 MB, 3 s timeout, explicit execution rolea slow handler hides retry timing
Artifactcontent-addressed OSS key plus checksumversion id joins to one build
Aliaslive, points at the published versioncallers never name LATEST
API backend3.0, event function, alias qualifiera 2.0 default is the negative control
EventBridgecustom bus, one filter, DLQfilter, retry and poison are visible
MNS topicone tag filter, backoff retrythe queue boundary is separate
  1. Pin Terraform 1.17.1 and provider 2.2.0, run init, and read the schema for the FCV3 resources. Confirm the legacy function is marked deprecated before writing either family.
  2. Build the zip in CI, compute its CRC-64, and upload it under a key derived from the commit. Apply the function and record the OSS key and checksum outside state.
  3. Publish a version and point the alias at it. Read back the version id and confirm the trigger or API qualifier names the alias, not a version id and not LATEST.
  4. Call the alias through API Gateway and expect the version marker from the promoted build. Compare the marker with the release record, not with the latest commit in the repository.
  5. Remove the invoke permission from the API Gateway role and call again. Expect a refusal with no function invocation log; restore the grant and allow propagation before judging the role.
  6. Restore the invoke grant but remove one execution-role permission the handler uses. Expect the function to start, then fail on the downstream call; the container log now exists.
  7. Publish one EventBridge event that matches the filter and expect one invocation, one idempotency record and an empty DLQ. Read the event id from the log, not from the payload.
  8. Publish an event that does not match and expect no invocation. Disable the rule, publish a matching event, and expect no delivery while the function stays healthy; re-enable it and expect delivery, which separates a filter problem from a permission problem.
  9. Make the handler write the record and then fail. Expect more than one invocation with one record; one attempt means the retry path was not exercised, and two records means the key is wrong.
  10. Send one MNS message with a non-matching tag and one with a matching tag. Expect one silent message and one invocation, then let a permanently failing message exhaust the notify strategy and expect no further invocations.
  11. Move the alias back to the previous version and call again. Expect the old marker without a rebuild; this is the rollback test, and it fails if the trigger or API names a version id.
  12. Destroy in reverse dependency order and list functions, versions, aliases, triggers, rules, topics and roles instead of assuming cleanup.

Expected observation. A sequence, not a duration: a successful call with the promoted marker, a refusal with no container log, a container log with a downstream denial, one event with one record, two attempts with one record, and a rollback that returns the previous marker.

Failure checks. The lab fails if a denied caller still starts the function, if a retry creates a second record, if a non-matching event invokes the function, if the DLQ receives a message the handler acknowledged, or if the alias rollback changes the marker only after a new apply.

Cleanup. Delete the trigger and rule before the event bus, the alias before the version, the version before the function, and the function before the roles it assumed. Keep the release record and the last good artifact until the rollback window closes.

Evidence to keep. Function name, version id, alias, OSS key and checksum, the execution and invocation role ARNs, one redacted log line per outcome, and the DLQ message count.

References (verified 6 November 2026):

  • alicloud_fcv3_function: https://registry.terraform.io/providers/aliyun/alicloud/2.2.0/docs/resources/fcv3_function
  • alicloud_fcv3_function_version: https://registry.terraform.io/providers/aliyun/alicloud/2.2.0/docs/resources/fcv3_function_version
  • alicloud_fcv3_alias: https://registry.terraform.io/providers/aliyun/alicloud/2.2.0/docs/resources/fcv3_alias
  • alicloud_fcv3_trigger: https://registry.terraform.io/providers/aliyun/alicloud/2.2.0/docs/resources/fcv3_trigger
  • alicloud_api_gateway_api: https://registry.terraform.io/providers/aliyun/alicloud/2.2.0/docs/resources/api_gateway_api
  • EventBridge trigger configuration: https://www.alibabacloud.com/help/en/functioncompute/api-fc-2023-03-30-struct-eventbridgetriggerconfig
  • Trigger retry and fault tolerance: https://www.alibabacloud.com/help/en/functioncompute/advanced-features-of-triggers

Next in the Series

In Alibaba Security and Operations: KMS, ActionTrail and CloudMonitor, we'll explore Coordinate secret/encryption ownership with verified audit and monitoring signals.