Oracle Cloud Infrastructure Python SDK

2.170.0 · active · verified Thu Apr 09

The Oracle Cloud Infrastructure Python SDK (oci) provides a comprehensive set of APIs to interact with OCI services, allowing Python applications to manage cloud resources. Currently at version 2.170.0, it receives frequent updates to support new services, features, and API versions.

Warnings

Install

Imports

Quickstart

This quickstart initializes an OCI IdentityClient using configuration loaded from the default `~/.oci/config` file. It then attempts to fetch the current authenticated user's details to verify connectivity and authentication. A missing configuration file or authentication failure will lead to an error message and exit, guiding the user on how to resolve it.

import oci
import os

try:
    # Load configuration from the default location (~/.oci/config)
    # The 'DEFAULT' profile is used if not explicitly specified.
    config = oci.config.from_file()
    # You can specify a different profile or file:
    # config = oci.config.from_file(file_location="~/.oci/config", profile_name="MY_PROFILE")
except oci.exceptions.ConfigFileNotFound:
    print("WARNING: OCI config file not found.")
    print("Please ensure your OCI config file is set up at ~/.oci/config and contains a 'DEFAULT' profile.")
    print("Alternatively, provide credentials via environment variables (e.g., OCI_CONFIG_FILE, OCI_PROFILE) or use Instance Principals for OCI instances.")
    exit(1) # Cannot proceed without configuration

# Initialize the IdentityClient for interacting with Identity services
identity_client = oci.identity.IdentityClient(config)

try:
    # The 'user' OCID is part of the loaded config (from the API key details).
    user_ocid = config["user"]
    
    # Get the current authenticated user's details
    user = identity_client.get_user(user_ocid).data
    print(f"Successfully authenticated as user: {user.name} (OCID: {user.id})")
    print(f"Region: {config['region']}")

    # Example of another common operation: List the root compartment details
    # root_compartment = identity_client.get_compartment(config["tenancy"]).data
    # print(f"Root Compartment: {root_compartment.name} (OCID: {root_compartment.id})")

except oci.exceptions.ServiceError as e:
    print(f"OCI Service Error encountered (Code: {e.code}): {e.message}")
    if e.code == "NotAuthenticated":
        print("Authentication failed. Please check your OCI configuration (~/.oci/config), API key, or credentials.")
    elif e.code == "InvalidParameter":
        print(f"The user OCID '{user_ocid}' might be invalid or you lack permissions to view it.")
    print("To troubleshoot, ensure the user OCID in your config file is correct and the API key is valid.")
    exit(1)
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    exit(1)

view raw JSON →