The Task provides a Python environment where you can import the openshift module (aliased as oc) to interact with your cluster.
Core Concepts
Context and Timeouts
Use oc.project('name') to set the project context for all subsequent oc commands and oc.timeout(seconds) to limit execution time.
Selecting Resources
Use oc.selector('resource_type') to query resources.
.qnames(): Returns a list of qualified names (e.g., ['pod/xyz', 'pod/abc'])..objects(): Returns an iterator of APIObject instances representing the current state of the resources.
Interacting with APIObjects
An APIObject provides convenience methods for resource interaction:
.name(): Returns the resource name..print_logs(...): Prints logs with specified arguments like timestamps or tail..model: Returns a Model instance representing the underlying resource definition.
Navigating with Model objects
Model objects allow for safe, deep navigation of resource attributes using dot notation. If a field does not exist, it returns the oc.Missing singleton instead of raising an error. This allows you to avoid boilerplate existence checks.
Note: When checking for existence, compare against the oc.Missing singleton (e.g., if field is not oc.Missing:).
import openshift as oc
# Set context and timeout
with oc.project('my-project'), oc.timeout(600):
# Select pods and iterate over them
for pod_obj in oc.selector('pods').objects():
print(f"Analyzing {pod_obj.name()}")
# Access the underlying model for deep navigation
pod_model = pod_obj.model
# Safe dot-notation navigation
for owner in pod_model.metadata.ownerReferences:
if owner.kind is not oc.Missing:
print(f"Owned by: {owner.kind}")