Back to Terraform

Alibaba Cloud Provider: RAM, STS, OIDC and Regional Scope

November 6, 2026 Wasil Zafar 21 min read

Configure aliyun/alicloud with an appropriate short-lived identity and explicit account/endpoint boundaries

Table of Contents

  1. Map the Account and RAM Trust Boundary
  2. Choose a Supported Short-Lived Authentication Flow
  3. Check International and Regional Product Availability
  4. Pin Alicloud and Inspect Current Resource Schemas
  5. Verify the Caller Before a Billable Plan

Map the Account and RAM Trust Boundary

An Alibaba Cloud account is the outer boundary, and everything else lives inside it. Billing, real-name verification, resource ownership and the account ID all belong to that account. RAM is not a second account: it is the identity system inside one account, and the account ID is written into every ARN a RAM principal carries.

Three identity shapes cover three different lifetimes. The root login exists to recover the account, not to run Terraform. A RAM user is a permanent identity with a permanent AccessKey. A RAM role is a permission set that another principal assumes for a bounded session.

A role is two policies, and only one of them is about permissions. The trust policy answers who may assume the role: an account, a service, or an OIDC provider. The permission policy answers what the resulting session may do. A broad permission policy behind a narrow trust policy has a small audience; a broad trust policy behind a narrow permission policy has a large one, and the role name rarely warns you.

STS is the exchange, not a fourth kind of identity. The caller presents a credential, STS checks the trust policy and returns a temporary AccessKey pair plus a security token with an expiry. The provider signs every request with that triple and refreshes it only when the credential source can refresh.

The session name is the audit handle. A role session carries a name, and the provider sends "terraform" when the configuration omits one. Set a name per pipeline so an audit record distinguishes the nightly apply from a human debugging the same role.

The account ID is part of the address. A role ARN reads acs:ram::<account-id>:role/<name>, so a configuration copied between accounts does not silently retarget. It asks for a role in the account named in the ARN, which is a feature as long as the account ID in the file is the one you meant.

Cross-account access is a pair of agreements. The target account's role trusts a principal in the source account, and the source principal's policy allows sts:AssumeRole on that ARN. Remove either side and the plan stops at authentication, before a single resource is read.

The provider's account argument is a hint, not a boundary. The account_id argument is optional and is auto-detected through GetCallerIdentity, because a few services need the number before they can build a request. It does not restrict which account the credential belongs to; only the credential does.

IdentityLifetimeLives inUse it for
Root accountpermanentthe account itselfbreak-glass recovery only
RAM userkey valid until rotatedone accountconsole humans, first bootstrap
RAM roleSTS session, minutes to hourstrust and permission policiesrunners, cross-account access
OIDC principalSTS session from an external tokenIdP trust on the roleexternal CI, ACK pods

A permanent key is the one thing no trust policy can narrow. An Alibaba Cloud root access key carries full account authority, has no session to expire and no policy to limit it. If one exists, disable it after the recovery procedure is documented; a pipeline should never hold it.

Map the Account and RAM Trust Boundary
%%{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
    ROOT["Alibaba Cloud account
billing, real-name, ownership
root login is break-glass only"] --> U["RAM user
permanent identity
long-lived AccessKey"] ROOT --> R["RAM role
assumed for a session
no permanent secret"] ROOT --> O["OIDC provider
external IdP trust
RRSA, GitHub, GitLab"] U --> P["RAM permission policy
what the identity may call"] R --> T["Role trust policy
who may assume it"] R --> P O --> T T --> S["STS
AccessKey pair and security token
fixed expiry"] S --> PR["Provider session
region, account, endpoint"] P --> RES["Regional resources
VPC, ECS, OSS, RDS"] PR --> RES ROOT -.->|"no access key"| X["Root access key
permanent, cannot be scoped"] 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 ROOT primary; class U,R,O secondary; class P,T,S,PR ok; class RES secondary; class X danger;

Figure 1 keeps ownership and authorization in separate lanes. The account owns, the RAM identity acts, the trust policy admits the role, and the permission policy limits the session. Region is deliberately absent: it changes where a request lands, not who may send it.

Account, identity, policy and placement as four gates Four panels in sequence. The account owns billing and resources, the RAM identity is a user, role or OIDC principal, the policy pair decides who may assume and what may be called, and placement decides the regional endpoint. A crimson footer states that a root access key is permanent and cannot be scoped. One request crosses four independent gates A token proves identity. RAM proves permission. The endpoint decides placement. ACCOUNT owns billing and every resource account ID sits in every ARN root login is recovery only IDENTITY RAM user: key until rotated RAM role: assumed for a session OIDC: external IdP token POLICY trust policy: who may assume permission policy: what may be called both are required neither is optional PLACEMENT region sets the product endpoint catalog and quota vary by region endpoint override must match region Root access key: permanent, full-account authority, no session and no trust policy. Do not create one for Terraform. Use the console with MFA for recovery and a role for automation. A valid token proves authentication, not authorization. The same session can read one resource and be denied the next call in the same account.

Figure 2 separates the four gates a single request crosses. The account is a namespace with an owner, the identity is who the token names, the policy pair is what RAM permits, and placement is where the API call lands. A plan can satisfy three and fail the fourth.

Choose a Supported Short-Lived Authentication Flow

The credential variables were renamed, and many tutorials still show the old names. Releases from provider 1.228.0 read the ALIBABA_CLOUD_ family and document the older ALICLOUD_ names as deprecated. Copying an export line from an old post is a compatibility decision, not a neutral one.

PurposeCurrent variableDeprecated alias
Access key IDALIBABA_CLOUD_ACCESS_KEY_IDALICLOUD_ACCESS_KEY
Access key secretALIBABA_CLOUD_ACCESS_KEY_SECRETALICLOUD_SECRET_KEY
STS tokenALIBABA_CLOUD_SECURITY_TOKENALICLOUD_SECURITY_TOKEN
RegionALIBABA_CLOUD_REGIONALICLOUD_REGION
Account IDALIBABA_CLOUD_ACCOUNT_IDALICLOUD_ACCOUNT_ID

The chain has six rungs, and three of them are short-lived. Static keys, a shared profile, an ECS instance role, an assumed role, an OIDC-assumed role, and a sidecar credential URI. The provider walks the chain in a documented order and stops at the first source that yields a credential.

Static keys belong to bootstrap, not to a runner. A key pair is valid until someone rotates it, survives offboarding, and appears in any log or state file that captured it. Use it to create the role that will replace it, then delete it.

An ECS instance role takes the key off the disk. The provider calls the metadata service at 100.100.100.200 and receives an STS credential for the attached role. The trust policy then names the ECS service rather than a person, and the instance carries an attachment instead of a secret.

The assume-role block keeps a base credential and swaps the session. The base can be a key, a profile, or an instance role; the provider calls AssumeRole and signs with the returned token. Its policy argument can only narrow the role, never widen it.

OIDC removes the base credential entirely. With assume_role_with_oidc, the provider presents a token from an external identity provider and receives STS credentials for the role. The trust policy names that provider and its claim conditions, so a token from another repository or namespace is refused.

The token file is the difference between a plan and a half-finished apply. An inline token is exchanged once at provider configuration; a token file is re-read and the role re-assumed before the session expires. The provider documents InvalidSecurityToken.Expired for an apply that outlives an inline token.

The sidecar is a credential source, not a secret store. A credentials_uri points at a local service that returns STS credentials, and the provider asks again before they expire. The refresh depends on an RFC3339 expiry in the response; without that field the credential is read once and the apply inherits its deadline.

Session length has two ceilings. The assume-role block accepts 900 to 43,200 seconds, but the request cannot exceed the role's maximum session duration. The OIDC block stops at 3,600 seconds, so a long apply needs the token file rather than a longer session.

FlowSecret at restRefreshBest forTypical failure
Static keypermanent key pairnonefirst bootstrap onlykey leaks and outlives the runner
Shared profilekey pair in a filenonea workstation with the CLIthe wrong profile wins
ECS instance rolenone on diskmetadata serviceTerraform on ECSinstance has no role attached
Assume rolea base credentialSTS sessioncross-account runnerstrust policy omits the caller
OIDC rolenone, only a token filere-assumed from the fileexternal CI, ACK podsinline token expires mid-apply
Sidecar URInone in the workspaceURI re-read before expiryplatform-managed runnersresponse lacks an expiry field
Choose a Supported Short-Lived Authentication Flow
%%{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
    S["terraform plan starts"] --> W{"Where does the runner execute?"}
    W -->|"ECS instance"| E["Attached instance RAM role
metadata service issues STS"] W -->|"ACK pod with RRSA"| O["Projected service account token
written to a file"] W -->|"laptop or generic CI"| H{"External OIDC token available?"} H -->|"yes"| O2["assume_role_with_oidc
token file, no access key"] H -->|"no"| A["Base credential plus assume_role
a static base key is the risk"] E --> T["STS session
AccessKey pair and security token"] O --> O2 O2 --> T A --> T T --> C{"Request accepted?"} C -->|"session expired"| X1["InvalidSecurityToken.Expired
inline token was not refreshed"] C -->|"trust policy mismatch"| X2["AssumeRole denied
principal not trusted by the role"] C -->|"policy gap"| X3["Product API returns Forbidden
role lacks the action"] C -->|"yes"| OK["Plan continues
account and region fixed"] 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 primary; class W,H,C secondary; class E,O,O2,A,T,OK ok; class X1,X2,X3 danger;

Figure 3 ends in three different failures on purpose. An expired token, a trust-policy mismatch and a permission gap all stop the plan, but each is fixed in a different place. Read which one fired before editing the policy.

Check International and Regional Product Availability

An account belongs to a site before it belongs to a region. The China site and the International site are separate account systems with separate consoles, billing and account IDs, and account_type tells the provider which one it is addressing. An account is registered on one site, and its credential is not a login for the other.

Region choice is a product decision, not a latency setting. Instance families, managed services, quotas and price lists differ by region, and a service present in one region may be absent or invitation-only in the next. A valid region with a missing product fails at the first API call, not at configuration.

The endpoint is derived, and the override is a trap. The provider builds each product endpoint from the region, and the endpoints block can replace one. Provider documentation warns that an overridden endpoint must stay consistent with the configured region, which makes the override a deliberate exception rather than a default.

Global services and regional resources answer different questions. RAM and STS are reached through global endpoints, while VPC, ECS, RDS and OSS are regional. A role can therefore be valid everywhere while the bucket or switch you want exists in exactly one place.

Quota is regional and per service. A plan that fits one region can fail in another for a quota nobody requested, and some quotas are per account rather than per region. Check the quota beside the region, not after the first failure.

Activation and permission are different failures with similar wording. A product that was never activated returns an error that reads like a permission problem, and a policy that omits one action returns an error that names the action. Read the message before widening the policy.

LayerWhat it decidesHow to confirm itWhat it does not tell you
Sitewhich account system owns the IDthe account type and the console you signed in towhich region has the product
Regionplacement, catalog, quota, pricethe regions data source and the product catalogwhether your identity may act there
Endpointwhich API host answersthe provider default or an overridewhether the product is activated
Zonedatacenter inside the regionthe zones data sourcewhether the product is offered there

Mainland regions add a compliance gate. A public web service needs an ICP filing, the account needs completed real-name verification, and some products require an application rather than a checkbox. Budget days for the first deployment there, not minutes.

Record the evidence next to the resource. A comment that names the site, the region and the activation step is worth more than a variable default nobody can trace. The next person to change the region should see what the region was chosen for.

Pin Alicloud and Inspect Current Resource Schemas

A floating requirement resolves a different binary in the next plan. A range such as >= 2.0 is a promise about a minimum, not about behaviour, and provider 2.x has already renamed fields that older examples still use. Pin provider 2.2.0 and Terraform 1.17.1 in the configuration, then commit the lock file that records what was downloaded.

The lock file is the part reviews forget. The init step writes it, version control should keep it, and it must carry hashes for every platform your runners use. A laptop and a Linux runner can otherwise resolve different packages from the same constraint.

Schema inspection is an offline read, not a plan. After init, terraform providers schema -json prints every resource, argument and deprecation the installed binary knows. Compare that output with the configuration before the first plan against a real account.

Deprecated fields still work in 2.2.0, which is exactly the risk. The RAM policy resource still accepts document, and the role still accepts name, but both have documented replacements. A configuration that keeps them passes today and breaks at a release boundary nobody scheduled.

ObjectDeprecated fieldCurrent fieldSince
RAM policydocumentpolicy_document1.114.0
RAM policynamepolicy_name1.114.0
RAM roledocumentassume_role_policy_document1.252.0
RAM rolenamerole_name1.252.0

Least privilege starts with the action list. RAM actions are service-prefixed, such as vpc:DescribeVpcs, and a policy that grants every action on every resource is a different review class from one that names the reads a plan needs. Add writes per resource, keep the session policy narrower than the role, and treat a wildcard as a finding rather than a convenience.

Policy versions are a bounded resource. A RAM policy holds at most five versions, and destroying it deletes every non-default version first. Rotation is off by default, so the update that would create a sixth version fails unless the documented rotation strategy is set.

Service activation is part of the schema contract. Some resources create a service-linked role or call a product API the account has never opened. The first apply then fails on activation rather than syntax, so record that step beside the resource that needs it.

Pinned provider resolution compared with a floating range The left panel shows an exact 2.2.0 pin, a lock file, a schema read and a plan that only uses fields the installed binary knows. The right panel shows a floating minimum resolving a later release, a churning lock file and a plan that fails on a renamed argument. A navy footer states that the schema read is the evidence between init and plan. Pin the release, then read the schema it installed A floating minimum is a different binary on a different day. PINNED: 2.2.0 required_providers pins 2.2.0 init writes the lock file providers schema -json is read plan uses fields that exist vs FLOATING: >= 2.0 a later release resolves the lock file churns between machines a renamed field drifts from the schema the plan fails at the argument The schema is the evidence between init and plan. Read it once per upgrade, and keep the pinned version and the lock file together.

Figure 4 puts the pin and the schema read on the same path. The pinned release makes the schema stable, and the schema read makes the configuration honest about which arguments still exist. A floating range skips both and moves the failure into a plan someone else runs.

Verify the Caller Before a Billable Plan

The provider exposes identity, but it does not assert your intent. The caller-identity data source returns the account ID, the principal ARN and the identity type that the configured credential actually resolved to. None of that is compared with your expectation unless the configuration compares it.

Two reads cover account and region. alicloud_caller_identity answers who, and alicloud_regions with the current flag answers where. Together they turn "this alias should be staging" into values a precondition can check.

A precondition is a gate; a check block is advice. A terraform_data resource creates nothing remote, so a failing precondition on it stops the plan with your message before the first billable create. A check block prints a warning and still exits zero.

Output the account suffix and the region, never the token. The identity read contains no secret of its own, but the ARN carries the full account ID. Show a suffix in CI logs and keep the full value in the break-glass record.

A valid token is not an authorization proof. Authentication says the credential exists; authorization is a separate decision made by RAM at the moment of the call. The cheapest evidence is a read you expect to be denied, returning a denial before anything is created.

Lab

Verify the Caller Before a Billable Plan

Status: design-only. No Alibaba Cloud account, credential or billable resource was used, and none of these steps were executed. Every identifier is a placeholder you replace: the sandbox account, the expected region and the denied read are values you nominate.

Prerequisites. Terraform CLI 1.17.1, provider 2.2.0, a RAM identity with read access to the sandbox account, and one read that the identity is deliberately not granted. Cost is zero: identity reads and denied calls create nothing.

Setup. One directory, no modules: a version file, a provider block with an explicit region, a data file with the two identity reads, a guard built on terraform_data, and one non-sensitive output.

GateExpected resultEvidence to keep
Accountresolved account ID equals the variableaccount suffix and identity type
Regioncurrent region ID equals the variableregion ID and provider version
Denialthe omitted read returns a RAM denialmessage text and exit code
  1. Run terraform version and confirm 1.17.1, then terraform providers and confirm 2.2.0 resolved rather than a newer range.
  2. Set the expected account ID and region as variables; never read them from whichever shell happens to be active.
  3. Read caller identity and the current region, then output only the account suffix, the region and the identity type.
  4. Add the guard: compare both reads in preconditions on the state-only resource.
  5. Plan with the correct values. Expect one resource to add, no remote call beyond reads, and the expected suffix and region.
  6. Point the provider region at a second region and plan again. Expect your region message, not an API error.
  7. Restore the region and change the expected account ID. Expect your account message before any resource is created.
  8. Remove one read from the role's policy, plan, and expect a RAM denial with a non-zero exit and no create.
  9. Sanitize the record: keep the identity type, account suffix, region, both version numbers and the denial line; delete plan files, local state and the provider cache.

Expected observation. The correct run shows one state-only resource, the expected suffix and region, and a clean exit. Each wrong run stops at the gate that owns the mistake, and the message names the account, the region or the denied action.

Failure check. If a wrong-region plan succeeds, look for a resource with its own region argument or an endpoint override that bypasses the provider default. If the denial step succeeds, the policy is wider than the test assumed.

Evidence to keep. A reviewer should be able to reproduce the decision from the identity type, the account suffix, the region and the denial line, without ever seeing a live credential.

Next in the Series

In Alibaba Networking: VPCs, VSwitches, Routing and Security Boundaries, we'll explore Trace cloud-specific network objects and private service paths with deliberate egress ownership.