Back to Terraform

OCI Provider: Tenancy, Compartments, Regions and Principals

November 6, 2026 Wasil Zafar 24 min read

Choose explicit Oracle Cloud identity and compartment boundaries for local and automated runs

Table of Contents

  1. Map OCIDs and Compartment Ownership Before Provider Configuration
  2. Choose Authentication for the Actual Runner
  3. Give Dynamic Groups and IAM Policies an Administrative Owner
  4. Check Region Subscription, Service Limits and Aliases
  5. Prove the Caller and Compartment Before Provisioning

Map OCIDs and Compartment Ownership Before Provider Configuration

A tenancy is the account, and its OCID doubles as the root compartment. Oracle Cloud does not separate "account" from "top-level container": billing, the realm, the home region and every child compartment hang off that one identifier. That is why IAM operations ask for a compartment even when you mean the whole tenancy.

An OCID is an address, not a credential. The documented shape is ocid1.<resource type>.<realm>.[region].<unique id>. Global objects such as tenancies and compartments leave the region segment empty, while a compute instance carries the region it was created in. The shape is a quick sanity check when an identifier arrives from another environment.

The private key is the part that must never travel with the identifier. API-key authentication pairs the user OCID and key fingerprint with a PEM private key; the fingerprint identifies the public half and is not itself a secret, while the key and its passphrase are. A configuration that reads the key into a variable also writes it into the plan file.

Compartments answer "who may act and who pays", not "what can talk to what". A compartment is the unit for IAM policy, quotas, budgets and cost reporting. Two resources in different compartments can still share a network path if policy allows it, and the network boundary is enforced by security lists, NSGs and route tables rather than by the compartment line.

Hierarchy is shallow on purpose. A tenancy allows 6,000 compartments and six levels of nesting, and a name only has to be unique inside its parent. Deleted compartments are retained for 90 days, keep their OCID, and are renamed with a random suffix, so a policy statement that names a deleted compartment is rewritten by IAM.

Ownership is a design decision, not a Terraform output. Decide before the first apply which compartment owns the workload, which owns shared networking, which owns the state bucket, and which team may attach policies to each. The same HCL against a different compartment is a different security change even when the plan looks identical.

The root compartment is an administration surface, not a workload home. A resource created there inherits every tenancy-wide grant, so its blast radius is the whole account. Keep IAM, break-glass users and the first bootstrap policy there; put instances, buckets and databases in named child compartments.

Give every identifier a human-readable neighbour. Store the tenancy and compartment OCIDs as variables named for the environment and owner, and record the display path beside them. An OCID proves nothing about intent; the label is what lets a reviewer catch a production plan pointed at a sandbox.

Map OCIDs and Compartment Ownership Before Provider Configuration
%%{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
account and root compartment
one OCID, one realm"] --> D["Identity domain
users and groups
Default plus additional"] T --> C1["Compartment: platform
shared network and keys"] C1 --> C2["Compartment: app-prod
workload resources"] C1 --> C3["Compartment: app-dev
same shape, lower blast radius"] D --> G["Group
human principal"] D --> DG["Dynamic group
matching rule, not a role"] G --> P["Policy attached to one compartment
allow verb resource-type in location"] DG --> P P --> C2 P --> C3 C2 --> R["Regional and AD resources
VCN, instances, volumes"] C3 --> R T -.->|"not a workload home"| X["Resources in the root compartment
account-wide blast radius"] 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 primary; class D,C1,C2,C3 secondary; class G,DG,P,R ok; class X danger;

Figure 1 separates ownership from authorization. The tenancy owns, the compartment scopes, the identity domain supplies the principal, and the policy — attached to one compartment — decides which verbs that principal may use there. None of those arrows is a network path.

An OCID is an address, while the signing key is the credential An OCID broken into version, resource type, realm, optional region and unique suffix. A teal panel lists the identifiers that belong with the configuration, and a crimson panel lists the key material that belongs in a credential store. A navy footer states that the fingerprint identifies the public key but is not the key. One identifier, one secret, two different handling rules Read the OCID as an address. Treat the private key as a live credential. OCID ocid1 resource type realm region opaque unique suffix The region segment is empty for tenancies and compartments; an instance carries it. KEEP WITH THE CONFIGURATION tenancy OCID and compartment OCID region name and provider version key fingerprint and user OCID the human path for each identifier identifiers are addresses, not passwords KEEP IN A CREDENTIAL STORE the PEM private key and its passphrase a security token or its token file resource principal token material anything a plan file would persist rotate on exposure, not on a calendar The fingerprint identifies the public key. It is not the key. An OCID in a repository is normal. A private key in a repository is an incident.

Figure 2 splits the identifier from the signing material. The OCID can live in the repository and the plan because it names a place; the key, passphrase and token cannot, because they authorize a caller. The fingerprint sits on the identifier side even though it is derived from the key pair.

Scope objectWhat it boundsIdentifier shapeWhat it does not decide
Tenancyaccount, realm, home region, root compartmentocid1.tenancy.oc1..…which region a resource lands in
Compartmentpolicy, quota, budget, resource ownershipocid1.compartment.oc1..…network reachability
Regionendpoint, service catalog, regional quotaus-ashburn-1 or its three-letter keywhich AD holds a volume
Availability domaindatacenter isolation for instances and volumestenancy-prefixed name such as Uocm:PHX-AD-1fault-domain anti-affinity
Fault domainhardware grouping inside one ADFAULT-DOMAIN-1 style nameregion placement

The table is the boundary checklist for the rest of this part. Each row answers a different question, and a plan that satisfies one row can still fail the next. The facts on this page were checked against Oracle's documentation on 6 November 2026, with Terraform 1.17.1 and provider oracle/oci 9.12.1 pinned.

Choose Authentication for the Actual Runner

No single authentication method fits a laptop, a compute instance and a pod. The provider selects a flow with the auth argument, defaulting to API key. Each value changes which credentials must exist before Terraform starts, and choosing the wrong one usually appears as an authentication error that looks like a bad key.

API keys are the compatibility path, not the target state. APIKey needs the tenancy OCID, user OCID, fingerprint and either a key path or the key itself. It works anywhere the network reaches the API, has no expiry, and therefore survives the laptop, the ticket and the contractor. Use it for bootstrap and for a human who must create the principal that replaces it.

A security token is a session with a one-hour ceiling. Token-based CLI login writes a profile with a security_token_file, and the provider reads it with SecurityToken plus the same profile name. Oracle's configuration page warns that the token expires after one hour, which suits interactive work and not an apply that may outlive it.

An instance principal removes the key from the runner. With InstancePrincipal the provider asks the instance metadata service for a short-lived certificate and signs as the instance. The matching right lives in a dynamic group in the tenancy, not in a file on disk. The provider still needs a region, because the instance does not imply which service endpoint to call.

A resource principal is the Functions version of the same idea. The platform injects the resource principal session token, the private PEM path and the region, and ResourcePrincipal consumes them. Since provider 5.0.0 a region in the provider block overrides the injected region, so a function can be pointed at another region deliberately — which is also a way to break it accidentally.

OKE workload identity is bound to a cluster, namespace and service account. OKEWorkloadIdentity lets a pod sign as the identity it projects, without a node-level key or a dynamic-group rule that covers the node. It suits an in-cluster controller and does not replace the node pool's own principal.

Precedence explains the credential nobody configured. When a value is absent from the provider block, the provider falls back to the environment, then a named profile, then the DEFAULT profile. A stale OCI_REGION exported in a shell can therefore override the profile a reviewer approved, which is why the pipeline should set the region in the block.

Two error families point at different owners. A 401 NotAuthenticated response means the signature or token was not accepted: refresh it, or fix the key path. 404 NotAuthorizedOrNotFound means the identity was accepted but the policy does not grant the verb in that compartment, and OCI deliberately will not confirm whether the resource exists.

Methodauth valuePrerequisite on the runnerLifetimeTypical failure
API keyAPIKeyuser OCID, fingerprint, key path, tenancy OCIDuntil rotatedkey outlives the person or leaks
Security tokenSecurityTokennamed profile with a token file, regionone hourtoken expires mid-apply
Instance principalInstancePrincipalinstance in a matching dynamic groupshort-lived certificaterule does not include the instance
Resource principalResourcePrincipalinjected RPST, PEM, regionplatform-managedprovider region overrides the injected one
OKE workload identityOKEWorkloadIdentityOKE workload with a service accountprojected tokenworkload not granted by policy
Choose Authentication for the Actual Runner
%%{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 -->|"laptop or generic CI"| L{"Session shorter than one hour?"}
    L -->|"yes, interactive"| ST["SecurityToken
profile and token file"] L -->|"no, unattended"| AK["APIKey
user OCID, fingerprint, key"] W -->|"compute instance"| IP["InstancePrincipal
dynamic group matches the instance"] W -->|"Functions"| RP["ResourcePrincipal
RPST, PEM and region"] W -->|"OKE pod"| OK["OKEWorkloadIdentity
cluster, namespace, service account"] ST --> C{"Call accepted?"} AK --> C IP --> C RP --> C OK --> C C -->|"token expired"| X1["401 NotAuthenticated
sign in again"] C -->|"principal not matched"| X2["404 NotAuthorizedOrNotFound
instance outside the dynamic group"] C -->|"policy gap"| X3["404 NotAuthorizedOrNotFound
verb missing in the compartment"] C -->|"yes"| Y["Plan continues
tenancy 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,L,C secondary; class IP,RP,OK,Y ok; class ST warn; class AK,X1,X2,X3 danger;

Figure 3 makes the runner the first question, not the credential type. A laptop, an instance, a function and a pod each have a supported answer, and each answer fails in a different place. The two 404 branches are the ones that send people to the wrong file: the fix is a policy or a matching rule, never a new key.

Give Dynamic Groups and IAM Policies an Administrative Owner

Identity domains hold users and groups, while compartments hold resources. Every tenancy includes a Default domain in the root compartment, plus any additional domains an administrator creates. A group is therefore addressed as domain plus name, and a policy still attaches to a compartment and still authorizes actions on the resources inside it.

Qualify the group in the statement. When more than one domain exists, write Default/terraform-runners rather than a bare group name, so the policy does not depend on which domain resolves first. Dynamic groups are managed in the same domain surface, and the policy subject names the group while the compartment stays in the location clause.

A dynamic group is a matching rule, and membership is not a role. Rules match a compartment OCID, an instance OCID, a resource type, or a tag, and an instance joins or leaves as it matches or stops matching. One instance can belong to at most five dynamic groups. A new member gains nothing until a policy names the group.

Rule changes take about an hour to propagate. Oracle documents that window for an updated matching rule. A runner launched just after a fix may fail for an hour, and the cause is neither the key nor the region. Plan the bootstrap window instead of widening the policy to make the error disappear.

Policies only allow, and the implicit deny is the default. There is no deny statement that subtracts from a broad grant. A tenancy-wide manage all-resources cannot be narrowed by a later, more specific statement, so the only correction is to remove or replace the broad statement. Treat a wildcard as a decision that needs an owner.

Attachment decides who can edit, and location decides who is affected. A policy attached to a compartment can be changed by anyone with manage policies there, and its statements inherit down the tree. A statement that names a deeper compartment from a higher attachment must use the colon path, such as platform:app-prod.

Bootstrap belongs to a human; steady state belongs to the pipeline. The group, dynamic group and first policy that make a runner possible should be created by an administrator outside the pipeline. If the same runner can manage policies in the tenancy, a bad plan can grant itself any permission and the "who approved this" trail collapses.

Write the owner into the object. A policy description naming the team and the change ticket is the cheapest audit trail OCI offers. It also exposes the orphan: a policy that nobody claims is usually a policy that can be deleted.

VerbWhat it addsWho it suitsRisk if granted broadly
inspectlist resources and metadata, no user contentauditors, inventory jobsreveals names and topology
readinspect plus user-defined metadata and contentinternal audit, read-only plansexposes configuration detail
useread plus work with existing resourcesday-to-day operatorscan change behaviour without creating
managefull control, including create, delete and policy updateadministrators onlycan rewrite access and destroy state
ObjectCreated byAttached toMay be edited byFailure if wrong
Compartmenttenancy administratorparent compartmentmanage compartments therewrong parent changes inheritance
Dynamic groupidentity administratortenancy identity domainmanage dynamic-groupsrule matches the wrong instances
Policybootstrap owner, then platform teamtenancy or a compartmentmanage policies at that attachmentrunner cannot grant itself; or can
Workload grantplatform teamworkload compartmentsame teamblast radius exceeds the workload

The two rights are deliberately separate. Creating a dynamic group is an identity action; creating an instance is a resource action; and a policy is the bridge between them. A team can own the workload and still have no authority to widen its own principal, which is the property worth preserving.

Check Region Subscription, Service Limits and Aliases

A region is subscribed by the tenancy before a provider can use it. Trial, free-tier and pay-as-you-go tenancies are limited to one subscribed region, while universal-credit tenancies can subscribe to all commercial regions. The provider can read the subscription list, but subscribing is a tenancy action performed in the console or through the API.

The home region is where global identity lives. Compartments, policies, users, groups and dynamic groups are cross-region objects, and identity domains have a home region that can be replicated. Some services and limits are anchored to the home region, so a plan run from a second region can still change objects that every region sees.

Region is set once, on the provider. Most resources have no region argument: the endpoint is derived from the provider configuration, and a second region means a second provider block with an alias. An alias is not a namespace; it is a separate configuration with its own region, and every resource must opt into it explicitly.

Global objects must not be multiplied by a regional loop. A for_each over regions that includes a compartment or a policy will try to create the same global object once per alias. Compartments and IAM belong in a single unaliased root; only regional resources should be fanned out across aliases.

Availability domain names are tenancy-specific and randomized. OCI prefixes AD names with a customer-specific string, so the PHX-AD-1 label can map to different datacenters in two tenancies. Address an AD by the name the data source returns; do not carry a name between tenancies, and do not index the list by position because the order can change.

Fault domains are the third level of placement. Each AD contains three fault domains, and a fault domain is an anti-affinity group inside that AD. Omitting one lets OCI choose, which is fine for a single instance and wrong for a pair that must not share hardware. The fault-domain data source currently accepts the tenancy as its compartment.

Volumes and instances must share an AD. A block volume attaches only to an instance in the same availability domain, and a regional subnet is the recommended way to avoid AD-specific network placement. This is the failure a correct IAM policy cannot save: the request is authorized and still impossible.

Quota is a regional, sometimes compartment-scoped, ceiling. The limits data source reports how much of a named limit is available, used and effectively quotable in a compartment; a quota policy can lower the effective value, and an unsupported limit returns 404. Check the number before the plan, not after the first capacity error.

Identity is global, placement is regional and availability-domain specific Three panels. The tenancy panel holds global IAM objects. The region panel holds the endpoint, catalog and regional quota, and requires a subscription. The availability domain panel holds instances and volumes and contains three fault domains. A crimson strip explains that a volume cannot attach across availability domains, and an amber strip explains that availability-domain names carry a tenancy prefix and that list order can change. One tenancy, one region, one availability domain Each layer answers a different question, and the last one cannot be fixed by IAM. TENANCY / GLOBAL compartments and policies users, groups, dynamic groups identity domain home region tag namespaces same object in every region REGION service endpoint VCNs, buckets, load balancers regional service limits must be subscribed first one provider block each AVAILABILITY DOMAIN instances and block volumes volume attaches in the same AD three fault domains inside tenancy-prefixed AD names order is not stable An availability domain name carries a tenancy prefix, and the list order can change. Read the name from the data source, then address it by name rather than by position. A volume in one availability domain cannot attach to an instance in another. The request can be fully authorized and still fail, because placement is not a permission. Compartment is cross-region. Region is not. Availability domain is narrower still.

Figure 4 follows one request down the placement stack. The tenancy decides identity and policy, the region decides endpoint and catalog, and the availability domain decides whether the volume can attach at all. Reading a failure at the wrong layer is how a placement problem becomes a policy rewrite.

Resource kindScopeExampleConsequence for a plan
IAM and compartmentsglobalpolicy, group, compartmentcreate once, never per region
Network and storageregionalVCN, bucket, load balancerneeds a subscribed region
Compute and block volumeavailability domaininstance, volumemust share an AD to attach
Network subnetregional or ADregional subnet preferredAD-specific subnet pins placement

Prove the Caller and Compartment Before Provisioning

The plan should fail before the first billable create. Terraform 1.17.1 offers two mechanisms with different consequences: a check block reports a warning and still exits zero, while a precondition on a resource that creates nothing stops the plan. Use the precondition for facts that make the run invalid, and a check only for drift you want to observe.

Read the tenancy and the compartment, not your hopes. The tenancy data source returns the name and home region key, and the compartment data source returns the parent, state and an accessibility flag. Comparing the parent against the expected compartment turns "the OCID looks right" into a value the plan can reject.

The region subscription is evidence too. Listing subscriptions and asserting the selected region's status catches the tenancy that never subscribed to the region in the variable. It also records which region is the home region, which matters for the identity changes that follow.

One denied read proves more than a green plan. Choose a sibling compartment where the runner has no grant and read a policy or instance list there. Expect NotAuthorizedOrNotFound with a 404 status: OCI will not confirm existence to a caller that may not see it. Keep that line; it is the negative evidence an auditor asks for.

Publish a suffix, never a key. A six-character tail is enough to match the record to the console and useless to an attacker. Output the tenancy suffix, compartment suffix, region name, provider version and the denial message; keep the full OCIDs in the private runbook and the key material nowhere near the repository.

Sanitize before you archive. A plan file contains variable values, so a key passed as a variable is in it even when the output is marked sensitive. Delete plan files, local state and the provider cache from the evidence bundle, and record what was deleted alongside what was kept.

Lab

Prove the Caller and Compartment Before Provisioning

Status: design-only. No Oracle Cloud tenancy, credential or billable resource was used, and none of these steps were executed. Every identifier below is a placeholder you supply: the sandbox tenancy, the target compartment, the expected parent and the denied sibling.

Prerequisites. Terraform CLI 1.17.1, provider oracle/oci 9.12.1, a credential with read access to the target compartment, and one sibling compartment where that credential has no grant. Cost is zero: identity, compartment, subscription and limit reads create nothing.

GateExpected resultEvidence to keep
Tenancyresolved tenancy equals the expected OCIDtenancy suffix and home region key
Compartmentparent equals the expected parent, state is activecompartment suffix and parent suffix
Regionselected region is subscribed, home region recordedregion name and subscription status
Placementat least one availability domain is returnedAD name and fault-domain count
Denialthe omitted read returns a 404 denialmessage text and non-zero exit
  1. Run terraform version and confirm 1.17.1, then confirm the provider resolves to 9.12.1 rather than a newer range.
  2. Set the expected tenancy, compartment and parent OCIDs as variables; do not read them from whichever shell is active.
  3. Add the tenancy read and the compartment read, and output only the two suffixes plus the parent suffix.
  4. Add the subscription read, filter for the selected region, and assert that its status is ready.
  5. Add the availability-domain read and record one AD name; do not select it by list index.
  6. Wrap the assertions in preconditions on a terraform_data resource, so a mismatch stops the plan with your message.
  7. Plan with the correct values. Expect one state-only resource to add, no remote writes, and the expected suffixes.
  8. Point the provider at an unsubscribed region and plan again. Expect your subscription message, not an endpoint error.
  9. Restore the region, change the expected parent, and expect your compartment message before anything is created.
  10. Read the sibling compartment's policies, expect a 404 denial, then remove that step so the healthy plan stays green.
  11. Sanitize the record: keep the suffixes, region, versions and denial line; delete plan files, local state, the token and the provider cache.

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

Failure check. If a wrong-region plan succeeds, look for a resource with its own region argument or a provider alias that bypassed the default. If the denial step succeeds, the policy is wider than the test assumed, and the sibling is not actually outside the grant.

Evidence to keep. A reviewer should be able to reproduce the decision from the tenancy suffix, the compartment parent, the region status, the AD name and the denial line, without ever seeing a live credential or the private key path.

Next in the Series

In OCI Networking: VCNs, Gateways, NSGs and Private Service Access, we'll explore Trace private and public traffic through Oracle-specific routing and security objects.