Oracle Cloud Infrastructure Python SDK
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
- gotcha When performing 'list' operations (e.g., `list_instances`, `list_buckets`), methods typically return only the first page of results. To retrieve all items, you must explicitly use paginators.
- gotcha The most common issue is misconfiguration of the OCI SDK. This includes missing `~/.oci/config` file, incorrect profile name, invalid API key paths, or incorrect tenancy/user OCIDs.
- gotcha OCI API calls can raise `oci.exceptions.ServiceError` for issues like authentication failures, permission errors, or invalid parameters. Not catching this specific exception can lead to unhandled runtime errors.
- breaking The default retry strategy for API calls changed from a fixed retry count to an exponential backoff strategy in versions greater than 2.24.0. This might alter the retry behavior of existing applications.
Install
-
pip install oci
Imports
- config
import oci.config
- IdentityClient
from oci.identity import IdentityClient
- ObjectStorageClient
from oci.object_storage import ObjectStorageClient
- ServiceError
from oci.exceptions import ServiceError
- Paginators
import oci.pagination
Quickstart
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)