OpenShift Python Client

0.13.2 · active · verified Tue Apr 14

The `openshift` library, corresponding to `openshift-restclient-python` on GitHub, provides a Python client for interacting with the OpenShift and Kubernetes APIs. It leverages a dynamic client to generically interact with all resources on the server, including Custom Resource Definitions and those defined by aggregated API servers. Currently at version 0.13.2, the library maintains an active release cadence with several updates per year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an OpenShift or Kubernetes cluster using `kubeconfig` or in-cluster configuration and then use the `openshift.dynamic.DynamicClient` to list projects (or namespaces as a fallback). It's crucial to have a valid `kubeconfig` file (e.g., at `~/.kube/config`) or appropriate in-cluster permissions for the client to authenticate successfully.

import os
from kubernetes import config
from openshift.dynamic import DynamicClient

try:
    # Attempt to load kubeconfig from default locations or KUBECONFIG env var
    kube_config_path = os.environ.get('KUBECONFIG', os.path.expanduser('~/.kube/config'))
    k8s_client = config.new_client_from_config(config_file=kube_config_path)
except Exception as e:
    print(f"Could not load kubeconfig: {e}. Attempting in-cluster config...")
    try:
        # Fallback to in-cluster configuration if outside kubeconfig fails
        k8s_client = config.load_incluster_config()
    except config.ConfigException as e_incluster:
        print(f"Could not load in-cluster config: {e_incluster}. Please ensure KUBECONFIG is set or run inside a cluster.")
        exit(1)

# Instantiate the DynamicClient with the Kubernetes client
dyn_client = DynamicClient(k8s_client)

# Example: List all Projects
# In OpenShift, 'Project' is a custom resource that typically corresponds to a Kubernetes Namespace.
# You might need 'Project' (OpenShift API) or 'Namespace' (Kubernetes API).
# This example tries for OpenShift's Project if available, otherwise Kubernetes Namespace.

try:
    # Try to get the 'Project' resource (OpenShift specific)
    projects_resource = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')
    print("Listing OpenShift Projects:")
    for project in projects_resource.get().items:
        print(f"  - {project.metadata.name}")
except Exception as e:
    print(f"Could not list OpenShift Projects (resource 'project.openshift.io/v1, Project' might not exist or be accessible): {e}")
    try:
        # Fallback to listing Kubernetes Namespaces
        namespaces_resource = dyn_client.resources.get(api_version='v1', kind='Namespace')
        print("Listing Kubernetes Namespaces instead:")
        for namespace in namespaces_resource.get().items:
            print(f"  - {namespace.metadata.name}")
    except Exception as e_ns:
        print(f"Could not list Kubernetes Namespaces either: {e_ns}")

view raw JSON →