Skip to main content

OCI Foundations & Security : OCI Resource Principals

Calculating read time…

Imagine you work at a big company. 🏢


Every time you need a file from the archive room, you have to walk there, show your ID, type your password, and sign a form.
Now imagine instead — your employee badge automatically opens every door you are authorised for. No password. No signing. Just walk in! 🪄
That is exactly what Resource Principals do for your OCI services.

01. The Problem Resource Principals Solve

When your code (running inside an OCI Notebook, a Function, or a Job) needs to call another OCI service — like reading from Object Storage or calling the Vision API — it needs to prove its identity to OCI first.

When Resource Principals are not available or are not selected, one common alternative is user API-key authentication:

  • Create a human user in OCI IAM 👤
  • Generate an API key for that user 🔑
  • Download the private key file .pem 📄
  • Copy that key file into every machine, notebook, and server 📋
  • Store the key file path in a config file ~/.oci/config ⚙️
  • Pray nobody accidentally leaks that key file online! 😰
❌ Why this old approach is dangerous:

  • A leaked key can expose the OCI resources and operations that the associated IAM user is authorized to access.
  • Oracle recommends rotating API signing keys every 90 days or less; this is a manual credential-lifecycle task.
  • When a team member leaves, you have to hunt down every place their key was copied
  • A stolen API signing key can remain usable until it is disabled or rotated, so treat it as a persistent credential.

For supported OCI workloads, Resource Principals remove the need to distribute a human user’s API signing key and OCI config file to the workload. OCI still provisions and refreshes authentication material behind the scenes; credentials for external systems may still be required.

02. 🎭 What Exactly is a Resource Principal?

A Resource Principal is a workload identity that OCI provides to a supported resource (for example, an OCI Data Science Notebook Session, a Data Science Job Run, or an OCI Function). The resource can act as an authorized principal when it calls other OCI services. Compute instances commonly use Instance Principals, a related resource-identity mechanism with its own setup and documentation; do not treat the terms as interchangeable in every context.

The supported resource has its own identity in OCI IAM. OCI provisions certificates and resource-principal token material for the resource, and the supported SDK or service integration uses that material to authenticate requests. The certificates are service-managed and rotated automatically. Your code does not need to copy a human user’s API signing key into the workload.

💡 Real-World Analogy — The Smart Employee Badge:

Think of Resource Principals like a smart employee badge that knows which resource it belongs to. 🪪

When a Notebook Session calls an OCI service, the SDK uses the resource identity and service-provided authentication material to sign and authenticate the request.

OCI manages the resource certificates and refreshable token material; your team does not distribute a human user's API key to the notebook.

When a resource is deleted or no longer matches its Dynamic Group rule, it can no longer continue obtaining credentials as that resource. However, do not assume that every previously issued or cached token disappears instantly; Data Science documents a 15-minute resource-principal token cache. 🎯

03. ⚙️ How Resource Principals Work — Under the Hood

Let's look at the exact sequence of events when your OCI Notebook Session uses a Resource Principal to call Object Storage:

  ┌─────────────────────────────────────────────────────────────────────────┐
  │          DATA SCIENCE RESOURCE PRINCIPAL AUTHENTICATION FLOW             │
  └─────────────────────────────────────────────────────────────────────────┘

  YOUR NOTEBOOK                 DATA SCIENCE RUNTIME          OCI IAM / SERVICE
  (Running Code)                (Resource Identity)          (Authorization)
  ───────────────               ────────────────────          ─────────────────

  1. Your code calls            2. Data Science supplies      3. The SDK uses the
     ads.set_auth                  resource-principal             resource identity
     ("resource_principal")  ───► token path and token ID  ───► and signing material
                                   through environment            to authenticate.
                                   variables such as
                                   OCI_RESOURCE_PRINCIPAL_RPT_PATH

                                                              4. OCI evaluates the
                                                                 Dynamic Group and
                                                                 applicable IAM policies.

  5. The SDK signs the         6. Object Storage checks
     request and calls    ───►   the requested operation
     Object Storage               against the granted
                                  permissions and returns data.
  ◄──────────────────────────────

The key insight: Data Science caches the resource-principal token for 15 minutes. Oracle documents that policy or Dynamic Group changes can take up to 15 minutes to be reflected in a Notebook Session. This is a cache/propagation detail; it should not be read as a guarantee that every token expires after exactly 15 minutes. 🔒

The Three Building Blocks of Resource Principals

  • 👥 Dynamic Group — A special kind of group in OCI IAM that contains resources (not people). You define matching rules such as “Notebook Sessions in this compartment” or “Job Runs in this compartment.” OCI evaluates those rules to determine resource membership.
  • 📋 IAM Policy — A permission statement that grants a Dynamic Group access to specific OCI services and resource types. For example, a Notebook Session group can be allowed to read from a particular Object Storage bucket.
  • 🔄 Resource Principal Token and SDK Signer — Data Science provides resource-principal token material to the supported runtime. For Notebook Sessions, Oracle documents environment variables including OCI_RESOURCE_PRINCIPAL_RPT_PATH and OCI_RESOURCE_PRINCIPAL_RPT_ID. The OCI SDK signer uses the available material; do not hard-code an undocumented metadata IP address.

04. 🏗️ Step-by-Step Setup — Enable Resource Principals for OCI Data Science

Step 1: Create a Dynamic Group

A Dynamic Group is a group whose members are defined by a matching rule, not by manual user additions. OCI Data Science documents separate resource types for Notebook Sessions, Job Runs, and Model Deployments. Create workload-specific groups so that a policy intended for a notebook or job does not automatically grant the same permissions to a model deployment.

📌 What do these rules do? Each rule identifies one kind of Data Science resource in the selected compartment. Oracle's setup tutorial shows that several resource-type rules can be placed in one Dynamic Group by selecting Match any rules defined below. In this example, the groups are separated so Notebook Sessions, Job Runs, and Model Deployments can receive different permissions.

  • Go to OCI Console → Identity & Security → Dynamic Groups.
  • Create DataScienceNotebookGroup for Notebook Sessions.
  • Create DataScienceJobRunGroup for Job Runs.
  • Create DataScienceModelDeploymentGroup for Model Deployments only when the deployment needs its own access to other OCI services.

Notebook Session Dynamic Group matching rule:

ALL {resource.type = 'datasciencenotebooksession', resource.compartment.id = 'ocid1.compartment.oc1..your_compartment_id'}

Data Science Job Run Dynamic Group matching rule:

ALL {resource.type = 'datasciencejobrun', resource.compartment.id = 'ocid1.compartment.oc1..your_compartment_id'}

Model Deployment Dynamic Group matching rule:

ALL {resource.type = 'datasciencemodeldeployment', resource.compartment.id = 'ocid1.compartment.oc1..your_compartment_id'}

Oracle's Data Science setup tutorial demonstrates one Dynamic Group with three matching rules. This example separates the rules as a least-privilege design choice: when multiple resource types are combined in one group, every matching resource receives the policies granted to that group.

Step 2: Create IAM Policies for the Dynamic Group

Creating the Dynamic Group only identifies who the resources are. Now we write policies to define what they are allowed to do. 📋

📌 What do the policies below do?

These statements grant the respective Notebook Session and Job Run groups the OCI permissions needed for the shown tasks. The resources authenticate with their Resource Principal identity instead of a copied human user's API signing key. Policies still control each target service and resource.

Important policy placement: Oracle's Data Science tenancy setup directs you to create the Dynamic Group policies in the tenancy (root) compartment. The policy statement can still grant access to resources in DataScienceCompartment. The policy's attachment location and its in compartment resource scope are different concepts.
-- Create IAM policies in the tenancy (root) compartment.
-- The policy statement's "in compartment" clause scopes the target resources.

-- 1. Notebook Sessions: read/write objects in one approved bucket
Allow dynamic-group DataScienceNotebookGroup to manage objects
  in compartment DataScienceCompartment
  where target.bucket.name = 'datalake-curated'

Allow dynamic-group DataScienceNotebookGroup to read buckets
  in compartment DataScienceCompartment

-- 2. Notebook Sessions: access the Data Science model catalog
Allow dynamic-group DataScienceNotebookGroup to manage data-science-models
  in compartment DataScienceCompartment

-- 3. Notebook Sessions: call pretrained OCI Vision APIs
Allow dynamic-group DataScienceNotebookGroup to use ai-service-vision-family
  in tenancy

-- 4. Notebook Sessions: call OCI Language APIs
Allow dynamic-group DataScienceNotebookGroup to use ai-service-language-family
  in tenancy

-- 5. Notebook Sessions: invoke OCI Generative AI chat
Allow dynamic-group DataScienceNotebookGroup to use generative-ai-chat
  in tenancy

-- 6. Data Science Job Runs: retrieve secrets from OCI Vault
-- Oracle's Data Science Jobs guide specifies manage secret-family for this job pattern.
Allow dynamic-group DataScienceJobRunGroup to manage secret-family
  in compartment DataScienceCompartment

-- 7. Data Science Job Runs: write job logs to OCI Logging
Allow dynamic-group DataScienceJobRunGroup to use log-content
  in compartment DataScienceCompartment

Allow dynamic-group DataScienceJobRunGroup to use log-groups
  in compartment DataScienceCompartment

-- 8. Model Deployments: add separate, narrowly scoped policies only for
-- the exact resources the deployed model must access (for example, a bucket
-- or Logging). Do not reuse the notebook/job policy set by default.
✅ Principle of Least Privilege — Always grant minimum required access:

Only grant the permissions your notebooks actually need. If your notebook only reads data and never writes, use read objects not manage objects. This limits the blast radius if something ever goes wrong! 🛡️

05. 💻 Step 3 — Use Resource Principals in Your Code

Now the beautiful part — using Resource Principals in Python is straightforward. In an OCI Data Science Notebook Session, the ADS SDK can be configured with ads.set_auth(auth="resource_principal"). For a plain OCI Python SDK client, obtain the resource-principal signer and pass it to that client explicitly.

Method 1: Using OCI ADS SDK (Recommended for Data Science)

📌 What does the code below do?

This code configures ADS to use the Notebook Session's Resource Principal. For Pandas access to Object Storage, pass ADS default_signer() as storage_options. A separate OCI SDK client still needs the Resource Principal signer passed explicitly.

import ads
import pandas as pd
import oci
from ads.common.auth import default_signer

# ── THE ONE MAGIC LINE ──────────────────────────────────────────────────────
# This tells OCI: "Use the Resource Principal of this Notebook Session"
# No human user API signing key or OCI config file is copied into this Notebook Session.
ads.set_auth(auth="resource_principal")
# ───────────────────────────────────────────────────────────────────────────

# Now use it to read Parquet data from Object Storage
print("📥 Reading data from Object Storage using Resource Principal...")
df = pd.read_parquet(
    "oci://datalake-curated@your_namespace/sales/year=2026/month=04/",
    storage_options=default_signer()
)
print(f"✅ Loaded {len(df):,} rows — no password needed! 🎉")

# Use it to call OCI Object Storage SDK
signer     = oci.auth.signers.get_resource_principals_signer()
os_client  = oci.object_storage.ObjectStorageClient({}, signer=signer)
namespace  = os_client.get_namespace().data
print(f"\n✅ Connected to Object Storage!")
print(f"   Namespace: {namespace}")
print("   Auth type: Resource Principal (user API key not copied into workload)")

Output:

📥 Reading data from Object Storage using Resource Principal...
✅ Loaded 124,901 rows — no password needed! 🎉

✅ Connected to Object Storage!
   Namespace: ocitenancyexample
   Auth type: Resource Principal (no user API signing key in this workload)

Method 2: Using the OCI SDK Directly

📌 What does the code below do?

This code uses the OCI Python SDK's Resource Principal signer. The signer obtains the resource's service-managed authentication material and signs requests for the client. You do not copy or manage a human user's API signing key in the notebook. The target OCI service still evaluates IAM policies for each operation.

import oci

# Get the Resource Principal signer
# The SDK reads the resource-principal token and signing material
# supplied by the OCI runtime; no metadata IP is hard-coded here.
signer = oci.auth.signers.get_resource_principals_signer()

# Now pass this signer to ANY OCI service client
# Notice: the config dict is empty {} — no keys, no files needed!
object_storage_client = oci.object_storage.ObjectStorageClient(
    config={},
    signer=signer
)

ai_vision_client = oci.ai_vision.AIServiceVisionClient(
    config={},
    signer=signer
)

ai_language_client = oci.ai_language.AIServiceLanguageClient(
    config={},
    signer=signer
)

gen_ai_client = oci.generative_ai_inference.GenerativeAiInferenceClient(
    config={},
    signer=signer,
    service_endpoint="https://inference.generativeai.ap-mumbai-1.oci.oraclecloud.com"
)

print("✅ OCI service client objects created with a Resource Principal signer.")
print("   No user API signing key or OCI config file is embedded in this workload.")
print("   IAM policies are still required for each target service and operation. 🔒")

Output:

✅ OCI service client objects created with a Resource Principal signer.
   No user API signing key or OCI config file is embedded in this workload.
   IAM policies are still required for each target service and operation. 🔒

06. 🌍 Real-World Examples — Resource Principals in Action

Example 1: Notebook reads data + calls OCI GenAI using Resource Principal

📌 What does the code below do?

This is a complete real-world example: an OCI Notebook Session reads customer reviews from Object Storage, then passes them to OCI Generative AI for sentiment analysis — all using Resource Principal authentication. No human user API signing key is embedded in this notebook workload. 🤖📄
import oci
import ads
import pandas as pd
import json
from ads.common.auth import default_signer

# ── Step 1: Authenticate using Resource Principal (one line!)
ads.set_auth(auth="resource_principal")
signer = oci.auth.signers.get_resource_principals_signer()

# ── Step 2: Load customer reviews from Object Storage
print("📥 Loading customer reviews from Object Storage...")
df = pd.read_csv(
    "oci://datalake-raw@your_namespace/reviews/customer_reviews_april.csv",
    storage_options=default_signer()
)
print(f"   Loaded {len(df)} reviews")

# ── Step 3: Create OCI Generative AI client using Resource Principal
gen_ai_client = oci.generative_ai_inference.GenerativeAiInferenceClient(
    config={},
    signer=signer,
    service_endpoint="https://inference.generativeai.ap-mumbai-1.oci.oraclecloud.com"
)

# ── Step 4: Analyse each review using OCI GenAI
print("\n🤖 Analysing reviews with OCI Generative AI...")
results = []

for idx, row in df.head(5).iterrows():   # process first 5 for demo
    review_text = row["review"]

    # Build the prompt for GenAI
    prompt = f"""Analyse this customer review and respond in JSON only:
Review: "{review_text}"

Respond with this exact JSON format:
{{"sentiment": "Positive/Negative/Neutral", "score": 0.0-1.0, "key_issue": "brief summary"}}"""

    # Call OCI GenAI — authenticated via Resource Principal automatically!
    response = gen_ai_client.chat(
        oci.generative_ai_inference.models.ChatDetails(
            compartment_id="ocid1.compartment.oc1..your_compartment_id",
            serving_mode=oci.generative_ai_inference.models.OnDemandServingMode(
                model_id="meta.llama-3.3-70b-instruct"
            ),
            chat_request=oci.generative_ai_inference.models.GenericChatRequest(
                messages=[
                    oci.generative_ai_inference.models.UserMessage(
                        content=[oci.generative_ai_inference.models.TextContent(text=prompt)]
                    )
                ],
                max_tokens=150,
                temperature=0.0
            )
        )
    )

    # Parse the JSON response
    reply_text = response.data.chat_response.choices[0].message.content[0].text
    analysis   = json.loads(reply_text)
    analysis["review"] = review_text[:60] + "..."
    results.append(analysis)

    print(f"   Review {idx+1}: {analysis['sentiment']} ({analysis['score']:.2f})")

# ── Step 5: Save results back to Object Storage using Resource Principal
results_df = pd.DataFrame(results)
results_df.to_parquet(
    "oci://datalake-curated@your_namespace/review_sentiment/results.parquet",
    storage_options=default_signer()
)
print(f"\n✅ Analysis complete! Results saved to Object Storage.")
print("   No human user API signing key was copied into this workload. 🔐")

Output:

📥 Loading customer reviews from Object Storage...
   Loaded 2,847 reviews

🤖 Analysing reviews with OCI Generative AI...
   Review 1: Positive (0.96)
   Review 2: Negative (0.88)
   Review 3: Neutral  (0.61)
   Review 4: Positive (0.91)
   Review 5: Negative (0.95)

✅ Analysis complete! Results saved to Object Storage.
   No human user API signing key was copied into this workload. 🔐

Example 2: Data Science Job reads secrets from OCI Vault

📌 What does the code below do?

This code runs inside an OCI Data Science Job (an automated batch job). It needs a database password to connect to Oracle Autonomous Database. Instead of hardcoding the password in the code, it reads it securely from OCI Vault using Resource Principal authentication. Like asking the company's secure safe for a key, rather than keeping the key in your pocket! 🔐
import oci
import base64

# Resource Principal auth — works inside a Data Science Job too!
signer = oci.auth.signers.get_resource_principals_signer()

# Create a Vault client using Resource Principal
vault_client = oci.vault.VaultsClient(config={}, signer=signer)
secrets_client = oci.secrets.SecretsClient(config={}, signer=signer)

# The OCID of the secret stored in OCI Vault
# (Store your DB password here ONCE, then reference it by OCID)
db_password_secret_id = "ocid1.vaultsecret.oc1..your_secret_id"
db_username_secret_id = "ocid1.vaultsecret.oc1..your_username_secret_id"

# Fetch the secret value from Vault — Resource Principal handles auth!
print("🔐 Fetching database credentials from OCI Vault...")

password_bundle = secrets_client.get_secret_bundle(db_password_secret_id)
db_password = base64.b64decode(
    password_bundle.data.secret_bundle_content.content
).decode("utf-8")

username_bundle = secrets_client.get_secret_bundle(db_username_secret_id)
db_username = base64.b64decode(
    username_bundle.data.secret_bundle_content.content
).decode("utf-8")

print(f"✅ Credentials fetched from Vault!")
print(f"   Username : {db_username}")
print(f"   Password : {'*' * len(db_password)}  (hidden for security)")

# Now connect to the database using the fetched credentials
import oracledb
connection = oracledb.connect(
    user=db_username,
    password=db_password,
    dsn="your_adb_connection_string"
)
print(f"\n✅ Connected to Autonomous Database!")
print(f"   No passwords were hardcoded in this script. 🎉")

Output:

🔐 Fetching database credentials from OCI Vault...
✅ Credentials fetched from Vault!
   Username : admin_user
   Password : **************  (hidden for security)

✅ Connected to Autonomous Database!
   No passwords were hardcoded in this script. 🎉

Example 3: Verify Your Resource Principal is Working

📌 What does the code below do?

This is a quick diagnostic script you can run in any notebook to confirm that Resource Principal authentication is working correctly. It prints your notebook's identity, what compartment it belongs to, and whether the auth token is valid — like checking if your badge scanner is working! 🔍
import oci
import os

print("🔍 Resource Principal Diagnostic Tool")
print("=" * 50)

# Data Science Notebook Sessions expose the resource-principal token path.
rpt_path = os.environ.get("OCI_RESOURCE_PRINCIPAL_RPT_PATH")
rpt_id = os.environ.get("OCI_RESOURCE_PRINCIPAL_RPT_ID")
print(f"\nRPT path available : {'✅ YES' if rpt_path else '❌ NOT EXPOSED'}")
print(f"RPT ID available   : {'✅ YES' if rpt_id else 'Not exposed in this runtime'}")

signer = None
try:
    signer = oci.auth.signers.get_resource_principals_signer()
    print("\n✅ Resource Principal signer created successfully!")
    print(f"   Region  : {signer.region}")
    print(f"   Tenancy : {signer.tenancy_id}")
except Exception as e:
    print(f"\n❌ Signer creation failed: {str(e)}")
    print("   Confirm that this OCI resource supports Resource Principals and that")
    print("   the resource-principal runtime variables and SDK are available.")

# Optional service check: this tests the specific Object Storage permission/path.
if signer is not None:
    try:
        os_client = oci.object_storage.ObjectStorageClient(config={}, signer=signer)
        ns = os_client.get_namespace().data
        print(f"\n✅ Object Storage namespace call succeeded: {ns}")
    except oci.exceptions.ServiceError as e:
        print(f"\n⚠️ Object Storage test failed — HTTP {e.status}: {e.message}")
        print("   This may be a service permission or endpoint issue; signer creation succeeded.")

print("\n" + "=" * 50)
print("📋 If a check failed:")
print("   1. Verify the Dynamic Group matching rule for this resource type.")
print("   2. Verify the required IAM policy and target compartment/bucket scope.")
print("   3. For Data Science Notebook Sessions, allow up to 15 minutes for policy or")
print("      Dynamic Group changes to be reflected because the RP token is cached.")

Output (when working correctly):

🔍 Resource Principal Diagnostic Tool
==================================================

RPT path available : ✅ YES
RPT ID available   : ✅ YES

✅ Resource Principal signer created successfully!
   Region  : ap-mumbai-1
   Tenancy : ocid1.tenancy.oc1..exampletenancyid

✅ Object Storage namespace call succeeded: ocitenancyexample

==================================================
📋 If a check failed:
   1. Verify the Dynamic Group matching rule for this resource type.
   2. Verify the required IAM policy and target compartment/bucket scope.
   3. For Data Science Notebook Sessions, allow up to 15 minutes for policy or
      Dynamic Group changes to be reflected because the RP token is cached.

07. 🖥️ Step 4 — What About Local Development? (Laptop / PC)

Resource Principals work only in OCI resources that support this authentication method. When you develop on your local laptop, there is no OCI Data Science resource-principal runtime material available. Here is how to handle both environments gracefully:

📌 What does the code below do?

This helper detects the documented Data Science Notebook Session resource-principal token path. In that environment it uses Resource Principal; on a local laptop it falls back to the regular OCI config file. Other OCI runtimes can have their own Resource Principal setup and should use the flow documented for that service.

import oci
import os

def get_smart_auth():
    """
    Use Resource Principal inside a supported OCI runtime;
    use the local OCI config file for laptop development.
    """
    # Data Science Notebook Sessions expose OCI_RESOURCE_PRINCIPAL_RPT_PATH.
    # This helper specifically detects the documented Data Science
    # Notebook Session resource-principal token path.
    is_inside_oci = bool(os.environ.get("OCI_RESOURCE_PRINCIPAL_RPT_PATH"))

    if is_inside_oci:
        print("🔑 Auth mode: Resource Principal (running inside supported OCI resource)")
        config = {}
        signer = oci.auth.signers.get_resource_principals_signer()
    else:
        print("🔑 Auth mode: OCI config/API key (running locally on laptop)")
        config = oci.config.from_file()   # reads ~/.oci/config
        signer = None  # the SDK builds the API-key signer from the config

    return config, signer


# Use it anywhere in your code
config, signer = get_smart_auth()

if signer is None:
    os_client = oci.object_storage.ObjectStorageClient(config=config)
else:
    os_client = oci.object_storage.ObjectStorageClient(config={}, signer=signer)

namespace = os_client.get_namespace().data
print(f"✅ Connected to Object Storage! Namespace: {namespace}")

Output (inside OCI Notebook):

🔑 Auth mode: Resource Principal (running inside supported OCI resource)
✅ Connected to Object Storage! Namespace: ocitenancyexample

Output (on local laptop):

🔑 Auth mode: Config file (running locally on laptop)
✅ Connected to Object Storage! Namespace: ocitenancyexample

This helper covers the two environments shown here: a Data Science Notebook Session and a local laptop. Other OCI resource types should use their own documented authentication setup. 🎉

08. 📊 Resource Principal vs Other Auth Methods — Comparison

  ┌────────────────────────────┬────────────────────────────┬──────────────────┬──────────────────────┐
  │ FEATURE                    │ Resource Principal         │ API Key + Config │ Instance Principal   │
  ├────────────────────────────┼────────────────────────────┼──────────────────┼──────────────────────┤
  │ User-managed key file      │ Not required               │ Required         │ Not required         │
  │ Where it works             │ Supported OCI resources    │ Local or OCI     │ OCI Compute instance │
  │ Works on laptop            │ No                         │ Yes              │ No                   │
  │ Credential management      │ Service-managed material   │ User-managed key │ Service-managed      │
  │ Data Science RP cache      │ 15 minutes for Notebook    │ Not applicable   │ Different mechanism │
  │                            │ Session token               │                  │                      │
  │ Best fit                   │ Data Science, Functions    │ Local development│ Compute instances    │
  └────────────────────────────┴────────────────────────────┴──────────────────┴──────────────────────┘

For OCI Data Science Notebook Sessions, Oracle recommends Resource Principal authentication. For other workloads, use the identity method documented for that resource type—for example, Instance Principals for OCI Compute instances. Resource Principal authentication is not a local-laptop credential method.

09. 🔧 Troubleshooting Common Resource Principal Issues

Problem 1: "NotAuthenticated" or "401 Unauthorized"

  • 🔍 Check: Is your Notebook Session in the right compartment?
    Your Dynamic Group rule must match the compartment where the notebook lives.
  • 🔍 Check: Does the Dynamic Group exist?
    Go to Identity → Dynamic Groups and confirm it is listed.
  • 🔍 Check: Does the resource type match?
    For Notebook Sessions, use resource.type = 'datasciencenotebooksession'

Problem 2: "NotAuthorized" or "403 Forbidden"

  • 🔍 Check: Does your IAM Policy reference the correct Dynamic Group name? Names are case-sensitive!
  • A policy attached to a parent compartment can apply to resources in its child compartments; a policy attached to a child compartment does not grant access upward to its parent. Check both the statement scope and where the policy is attached.
  • 🔍 Check: Does the policy grant sufficient access?
    read objects vs manage objects — make sure the verb is correct.

Problem 3: Works in Notebook but Not in Job

💡 Remember:

Notebook Sessions and Job Runs are different resource types. A Notebook Session rule uses datasciencenotebooksession; a Job Run rule uses datasciencejobrun. Create the appropriate matching rule in the Dynamic Group that represents the workload, and grant each group only the policies it needs. ✅

Oracle documents a 15-minute resource-principal token cache for Notebook Sessions, so allow up to 15 minutes after a policy or Dynamic Group change before testing again.

Quick Debug Checklist

📌 What does the code below do?

This is a one-stop debug script that checks your Resource Principal setup and tells you exactly what is missing or wrong. Run it at the very start of any new notebook to confirm everything is configured correctly before writing any actual code! 🩺
import oci
import os

print("🩺 Resource Principal Health Check")
print("=" * 55)

# Data Science Notebook Sessions document these two resource-principal variables.
rpt_path = os.environ.get("OCI_RESOURCE_PRINCIPAL_RPT_PATH")
rpt_id = os.environ.get("OCI_RESOURCE_PRINCIPAL_RPT_ID")
print(f"1️⃣  RPT path available : {'✅ YES' if rpt_path else '❌ NOT EXPOSED'}")
print(f"2️⃣  RPT ID available   : {'✅ YES' if rpt_id else 'Not exposed in this runtime'}")

signer = None
try:
    signer = oci.auth.signers.get_resource_principals_signer()
    print("3️⃣  Signer creation    : ✅ SUCCESS")
    print(f"   Region  : {signer.region}")
    print(f"   Tenancy : {signer.tenancy_id}")
except Exception as e:
    print(f"3️⃣  Signer creation    : ❌ FAILED — {str(e)[:120]}")

if signer is not None:
    try:
        os_client = oci.object_storage.ObjectStorageClient(config={}, signer=signer)
        ns = os_client.get_namespace().data
        print(f"4️⃣  Object Storage     : ✅ SUCCESS (namespace: {ns})")
    except oci.exceptions.ServiceError as e:
        print(f"4️⃣  Object Storage     : ⚠️ FAILED — HTTP {e.status}: {e.message[:80]}")
else:
    print("4️⃣  Object Storage     : SKIPPED (signer is unavailable)")

print("=" * 55)
print("📋 For failures, check the resource-type matching rule, policy scope, and service permission.")
print("   Data Science Notebook Session RP tokens are cached for 15 minutes.")

Output (fully healthy setup):

🩺 Resource Principal Health Check
=======================================================

1️⃣  RPT path available : ✅ YES
2️⃣  RPT ID available   : ✅ YES
3️⃣  Signer creation    : ✅ SUCCESS
   Region  : ap-mumbai-1
   Tenancy : ocid1.tenancy.oc1..exampletenancyid
4️⃣  Object Storage     : ✅ SUCCESS (namespace: ocitenancyexample)

=======================================================
📋 For failures, check the resource-type matching rule, policy scope, and service permission.
   Data Science Notebook Session RP tokens are cached for 15 minutes.

10. 🏆 Benefits of Resource Principals — A Full Summary

  WITHOUT Resource Principals       WITH Resource Principals
  ──────────────────────────        ─────────────────────────
  ❌ User API key files in workloads ✅ No user API key file in the OCI resource
  ❌ Shared user credentials        ✅ Each supported resource has its own identity
  ❌ Manual key lifecycle           ✅ Service-managed RP credentials
  ❌ Manual API-key rotation        ✅ Certificates rotated by OCI
  ❌ API-key leak risk              ✅ No user key copied into workload
  ❌ Shared user attribution        ✅ Resource identity in supported audit events
  ❌ Remove copied user keys       ✅ Remove resource/group eligibility
  ❌ Config copied to each host    ✅ Dynamic Group rules identify resources
  ❌ Separate local/OCI setup       ✅ Explicit helper for both setups

11. ✅ Best Practices for Resource Principals

  • 🎯 Prefer Resource Principals where the OCI workload supports them — avoid copying human user API signing keys into notebooks, jobs, or functions. Use the authentication method documented for each resource type.
  • 🏗️ One Dynamic Group per use case — create separate Dynamic Groups for dev, staging, and production. Each gets different IAM policies with different permission levels.
  • Use OCI Audit to review recorded API activity and the principal associated with supported requests. Audit coverage and available event details depend on the service and operation; do not assume that Audit captures every low-level data read or application-level action.
  • 🔐 Never grant admin access to notebooks — use the minimum permissions required. Notebooks should read data and call AI services — they should never manage IAM or billing.
  • 🧪 Test with the health check script first — run the diagnostic script at the top of every new notebook before writing any logic. Catches permission issues before you waste time debugging.
❌ Things to never do with Resource Principals:

  • Never grant manage all-resources in tenancy to a Dynamic Group — that is admin access for your entire cloud!
  • Never use Resource Principals on a local laptop — they won't work and will confuse you
  • Never skip the Dynamic Group and try to grant policies directly to individual resources
  • Never assume policy changes take effect immediately — for Data Science Notebook Sessions, Oracle documents a 15-minute resource-principal token cache.

12. Additional References

These Oracle references describe the Data Science authentication, Dynamic Group, IAM policy, and Object Storage patterns used in this article.

13. 📝 Quick Summary — What We Learned

  • The Problem → API key files are risky, manual to manage, and easy to leak
  • What Resource Principals are → Automatic identities assigned to OCI resources (not people)
  • How they work → OCI provisions resource identity and authentication material; the SDK uses the Resource Principal signer. Data Science Notebook Session tokens are cached for 15 minutes.
  • Three Building Blocks → Dynamic Group + IAM Policy + Resource Principal token and SDK signer.
  • Setup Steps → Create Dynamic Group with matching rule → Write IAM Policy → Use get_resource_principals_signer() in code
  • One Magic Line → ads.set_auth(auth="resource_principal") configures ADS; direct OCI SDK clients still need the Resource Principal signer passed to them.
  • Smart Fallback → Detect documented runtime indicators such as OCI_RESOURCE_PRINCIPAL_RPT_PATH for Data Science Notebook Sessions, and use the local OCI config only outside a supported OCI runtime.
  • Benefits → No user API key copied into the workload, service-managed credential material, and resource-specific IAM permissions. Changes still observe the documented token cache.

Resource Principals provide a strong security improvement for supported OCI workloads. 🏆
A Dynamic Group, carefully scoped IAM policies, and the appropriate SDK signer let your Data Science code call OCI services without distributing a human user’s API signing key to the runtime. 🔒✨

Comments