Oracle Cloud Infrastructure CLI

3.78.0 · active · verified Sat Apr 11

The Oracle Cloud Infrastructure CLI (oci-cli) is a command-line interface that allows users to interact with Oracle Cloud Infrastructure services. Built on the OCI Python SDK, it provides equivalent functionality to the OCI Console, plus additional commands and scripting capabilities. The current version is 3.78.0, and it is actively maintained by Oracle with frequent updates and new feature releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the underlying OCI Python SDK to list compartments within your Oracle Cloud Infrastructure tenancy. Before running, ensure you have configured your OCI CLI by running `oci setup config` in your terminal to create the `~/.oci/config` file and API keys. The script loads this configuration for authentication.

# First, ensure your OCI configuration file (~/.oci/config) is set up.
# You can generate one interactively using: oci setup config
#
# Then, use the OCI Python SDK (installed with oci-cli):

import oci
import os

# Load the OCI config from the default location and profile
# (or specify path and profile like oci.config.from_file("/path/to/config", "YOUR_PROFILE"))
try:
    config = oci.config.from_file(os.environ.get('OCI_CONFIG_FILE', '~/.oci/config'), os.environ.get('OCI_PROFILE', 'DEFAULT'))
except oci.exceptions.ConfigFileNotFound as e:
    print(f"Error: OCI config file not found. Please run 'oci setup config' or set OCI_CONFIG_FILE and OCI_PROFILE environment variables. {e}")
    exit(1)

# Create an IdentityClient
identity_client = oci.identity.IdentityClient(config)

# Get the tenancy OCID from the config
tenancy_id = config["tenancy"]

# List compartments in the tenancy
try:
    list_compartments_response = identity_client.list_compartments(compartment_id=tenancy_id, compartment_id_in_subtree=True)
    print("Listing Compartments:")
    for compartment in list_compartments_response.data:
        print(f"  Name: {compartment.name}, ID: {compartment.id}, Lifecycle State: {compartment.lifecycle_state}")
except oci.exceptions.ServiceError as e:
    print(f"Error listing compartments: {e}")
    if e.code == 'NotAuthenticated':
        print("Please check your API key and fingerprint in ~/.oci/config.")
    elif e.code == 'AuthRequired':
        print("Authentication failed. Ensure your API key is correctly configured and has necessary permissions.")

view raw JSON →