• Stars
    star
    205
  • Rank 190,178 (Top 4 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python client for the OpenShift API

OpenShift python client

Build Status Coverage Status

Python client for the Kubernetes and OpenShift APIs.

There are two ways this project interacts with the Kubernetes and OpenShift APIs. The first, now deprecated, is to use models and functions generated with swagger from the API spec. The second, new approach, is to use a single model and client to generically interact with all resources on the server. The dynamic client also works with resources that are defined by aggregated API servers or Custom Resource Definitions.

Table of Contents

Installation

From source:

git clone https://github.com/openshift/openshift-restclient-python.git
cd openshift-restclient-python
python setup.py install

From PyPi directly:

pip install openshift

Using Dockerfile:

docker build -t openshift-restclient-python -f Dockerfile .

Usage

The OpenShift client depends on the Kubernetes Python client, and as part of the installation process, the Kubernetes (K8s) client is automatically installed.

In the case you are using Docker, you will likely need to share your .kube/config with the openshift-restclient-python container:

docker run -it -v $HOME/.kube/config:/root/.kube/config:z openshift-restclient-python python

To work with the dynamic client, you will need an instantiated Kubernetes client object. The Kubernetes client object requires a Kubernetes Config that can be set in the Config class or using a helper utility. All of the examples that follow make use of the new_client_from_config() helper utility provided by the Kubernetes Client Config that returns an API client to be used with any API object. There are plenty of Kubernetes Client examples to examine other ways of accessing Kubernetes Clusters.

Examples

Create a Service

import yaml
from kubernetes import client, config
from openshift.dynamic import DynamicClient

k8s_client = config.new_client_from_config()
dyn_client = DynamicClient(k8s_client)

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

service = """
kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 9376
"""

service_data = yaml.load(service)
resp = v1_services.create(body=service_data, namespace='default')

# resp is a ResourceInstance object
print(resp.metadata)

Create a Route

Now, we create a Route object, and associate it with the Service from our previous example:

import yaml
from kubernetes import client, config
from openshift.dynamic import DynamicClient

k8s_client = config.new_client_from_config()
dyn_client = DynamicClient(k8s_client)

v1_routes = dyn_client.resources.get(api_version='route.openshift.io/v1', kind='Route')

route = """
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: frontend
spec:
  host: www.example.com
  to:
    kind: Service
    name: my-service
"""

route_data = yaml.load(route)
resp = v1_routes.create(body=route_data, namespace='default')

# resp is a ResourceInstance object
print(resp.metadata)

List Projects

The following uses the dynamic client to list Projects the user can access:

from kubernetes import client, config
from openshift.dynamic import DynamicClient

k8s_client = config.new_client_from_config()
dyn_client = DynamicClient(k8s_client)

v1_projects = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')

project_list = v1_projects.get()

for project in project_list.items:
    print(project.metadata.name)

Custom Resources

In the following example, we first create a Custom Resource Definition for foos.bar.com, then create an Foo resource, and finally get a list of Foo resources:

import yaml
from kubernetes import client, config
from openshift.dynamic import DynamicClient

k8s_client = config.new_client_from_config()
dyn_client = DynamicClient(k8s_client)

custom_resources = dyn_client.resources.get(
  api_version='apiextensions.k8s.io/v1beta1',
  kind='CustomResourceDefinition'
)

# Define the Foo Resource
foo_crd = """
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
  name: foos.bar.com
spec:
  group: bar.com
  names:
    kind: Foo
    listKind: FooList
    plural: foos
    shortNames:
    - foo
    singular: foo
  scope: Namespaced
  version: v1beta1
"""
custom_resources.create(body=yaml.load(foo_crd))

foo_resources = None
while not foo_resources:
  try:
    # Notice the re-instantiation of the dynamic client as a new resource has been created.
    dyn_client = DynamicClient(k8s_client)
    foo_resources = dyn_client.resources.get(api_version='bar.com/v1beta1', kind='Foo')
  except:
    pass

# Create the Foo Resource
foo_resource_cr = """
kind: Foo
apiVersion: bar.com/v1beta1
metadata:
  name: example-foo
  namespace: default
spec:
  version: 1
"""
foo_resources.create(body=yaml.load(foo_resource_cr))

for item in foo_resources.get().items:
  print(item.metadata.name)

OpenShift Login with username and password

from kubernetes import client
from openshift.dynamic import DynamicClient
from openshift.helper.userpassauth import OCPLoginConfiguration
 
apihost = 'https://api.cluster.example.com:6443'
username = 'demo-user'
password = 'insecure'
 
kubeConfig = OCPLoginConfiguration(ocp_username=username, ocp_password=password)
kubeConfig.host = apihost
kubeConfig.verify_ssl = True
kubeConfig.ssl_ca_cert = './ocp.pem' # use a certificate bundle for the TLS validation
 
# Retrieve the auth token
kubeConfig.get_token()
 
print('Auth token: {0}'.format(kubeConfig.api_key))
print('Token expires: {0}'.format(kubeConfig.api_key_expires))
 
k8s_client = client.ApiClient(kubeConfig)
 
dyn_client = DynamicClient(k8s_client)
v1_projects = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')
project_list = v1_projects.get()
 
for project in project_list.items:
    print(project.metadata.name)
 
# Renew the auth token
kubeConfig.get_token()
 
print('Auth token: {0}'.format(kubeConfig.api_key))
print('Token expires: {0}'.format(kubeConfig.api_key_expires))

Available Methods for Resources

The generic Resource class supports the following methods, though every resource kind does not support every method.

Get

get(name=None, namespace=None, label_selector=None, field_selector=None, **kwargs)

Query for a resource in the cluster. Will return a ResourceInstance object or raise a NotFoundError

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

# Gets the specific Service named 'example' from the 'test' namespace
v1_services.get(name='example', namespace='test')

# Lists all Services in the 'test' namespace
v1_services.get(namespace='test')

# Lists all Services in the cluster (requires high permission level)
v1_services.get()

# Gets all Services in the 'test' namespace with the 'app' label set to 'foo'
v1_services.get(namespace='test', label_selector='app=foo')

# Gets all Services except for those in the 'default' namespace
v1_services.get(field_selector='metadata.namespace!=default')

get(body=None, namespace=None, **kwargs)

Query for a resource in the cluster. Will return a ResourceInstance object or raise a NotFoundError

For List kind resources (ie, the resource name ends in List), the get implementation is slightly different. Rather than taking a name, they take a *List kind definition and call get for each definition in the list.

v1_service_list = dyn_client.resources.get(api_version='v1', kind='ServiceList')

body = {
    'kind': 'ServiceList',
    'apiVersion': 'v1',
    'items': [
        'metadata': {'name': 'my-service'},
        'spec': {
            'selector': {'app': 'MyApp'},
            'ports': [{
                'protocol': 'TCP',
                'port': '8080',
                'targetPort': '9376'
            }]
        }
    ],
    # More definitions would go here
}
# Gets the specified Service(s) from the 'test' namespace
v1_service_list.get(body=body, namespace='test')

# Lists all Services in the 'test' namespace
v1_service_list.get(namespace='test')

# Lists all Services in the cluster (requires high permission level)
v1_service_list.get()

Create

create(body=None, namespace=None, **kwargs)

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

body = {
    'kind': 'Service',
    'apiVersion': 'v1',
    'metadata': {'name': 'my-service'},
    'spec': {
        'selector': {'app': 'MyApp'},
        'ports': [{
            'protocol': 'TCP',
            'port': '8080',
            'targetPort': '9376'
        }]
    }
}

# Creates the above service in the 'test' namespace
v1_services.create(body=body, namespace='test')

The create implementation is the same for *List kinds, except that each definition in the list will be created separately.

If the resource is namespaced (ie, not cluster-level), then one of namespace, label_selector, or field_selector is required.

If the resource is cluster-level, then one of name, label_selector, or field_selector is required.

Delete

delete(name=None, namespace=None, label_selector=None, field_selector=None, **kwargs)

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

# Deletes the specific Service named 'example' from the 'test' namespace
v1_services.delete(name='my-service', namespace='test')

# Deletes all Services in the 'test' namespace
v1_services.delete(namespace='test')

# Deletes all Services in the 'test' namespace with the 'app' label set to 'foo'
v1_services.delete(namespace='test', label_selector='app=foo')

# Deletes all Services except for those in the 'default' namespace
v1_services.delete(field_selector='metadata.namespace!=default')

delete(body=None, namespace=None, **kwargs)

For List kind resources (ie, the resource name ends in List), the delete implementation is slightly different. Rather than taking a name, they take a *List kind definition and call delete for each definition in the list.

v1_service_list = dyn_client.resources.get(api_version='v1', kind='ServiceList')

body = {
    'kind': 'ServiceList',
    'apiVersion': 'v1',
    'items': [
        'metadata': {'name': 'my-service'},
        'spec': {
            'selector': {'app': 'MyApp'},
            'ports': [{
                'protocol': 'TCP',
                'port': '8080',
                'tardeletePort': '9376'
            }]
        }
    ],
    # More definitions would go here
}
# deletes the specified Service(s) from the 'test' namespace
v1_service_list.delete(body=body, namespace='test')

# Deletes all Services in the 'test' namespace
v1_service_list.delete(namespace='test')

Patch

patch(body=None, namespace=None, **kwargs)

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

body = {
    'kind': 'Service',
    'apiVersion': 'v1',
    'metadata': {'name': 'my-service'},
    'spec': {
        'selector': {'app': 'MyApp2'},
    }
}

# patchs the above service in the 'test' namespace
v1_services.patch(body=body, namespace='test')

The patch implementation is the same for *List kinds, except that each definition in the list will be patched separately.

Replace

replace(body=None, namespace=None, **kwargs)

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

body = {
    'kind': 'Service',
    'apiVersion': 'v1',
    'metadata': {'name': 'my-service'},
    'spec': {
        'selector': {'app': 'MyApp2'},
        'ports': [{
            'protocol': 'TCP',
            'port': '8080',
            'targetPort': '9376'
        }]
    }
}

# replaces the above service in the 'test' namespace
v1_services.replace(body=body, namespace='test')

The replace implementation is the same for *List kinds, except that each definition in the list will be replaced separately.

Watch

watch(namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None)

v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

# Prints the resource that triggered each event related to Services in the 'test' namespace
for event in v1_services.watch(namespace='test'):
    print(event['object'])

Community, Support, Discussion

If you have any problem with the package or any suggestions, please file an issue.

Code of Conduct

Participation in the Kubernetes community is governed by the CNCF Code of Conduct.

More Repositories

1

origin

Conformance test suite for OpenShift
Go
8,372
star
2

source-to-image

A tool for building artifacts from source and injecting into container images
Go
2,379
star
3

openshift-ansible

Install and config an OpenShift 3.x cluster
Python
2,136
star
4

osin

Golang OAuth2 server library
Go
1,832
star
5

installer

Install an OpenShift 4.x cluster
1,312
star
6

okd

The self-managing, auto-upgrading, Kubernetes distribution for everyone
HCL
1,276
star
7

origin-server

OpenShift 2 (deprecated)
Ruby
885
star
8

openshift-docs

OpenShift 3 and 4 product and community documentation
HTML
687
star
9

microshift

A small form factor OpenShift/Kubernetes optimized for edge computing
Go
528
star
10

geard

geard is no longer maintained - see OpenShift 3 and Kubernetes
Go
407
star
11

hypershift

Hyperscale OpenShift - clusters with hosted control planes
Go
347
star
12

console

OpenShift Cluster Console UI
TypeScript
334
star
13

openshift-ansible-contrib

Additional roles and playbooks for OpenShift installation and management
Python
284
star
14

training

Shell
280
star
15

pipelines-tutorial

A step-by-step tutorial showing OpenShift Pipelines
Shell
272
star
16

jenkins

Shell
260
star
17

release

Release tooling for OpenShift
Shell
229
star
18

ansible-service-broker

Ansible Service Broker
Go
226
star
19

hive

API driven OpenShift cluster provisioning and management
Go
222
star
20

rhc

OpenShift 2 Client Tools (deprecated)
Ruby
220
star
21

machine-config-operator

Go
218
star
22

jenkins-client-plugin

Java
218
star
23

cluster-monitoring-operator

Manage the OpenShift monitoring stack
Go
218
star
24

library

Examples and Components for deploying into OpenShift
Go
163
star
25

openshift-tools

A public repository of scripts used by OpenShift Operations for various purposes
Python
161
star
26

enhancements

Enhancements tracking repository for OKD
Go
156
star
27

generic-admission-server

A library for writing admission webhooks based on k8s.io/apiserver
Go
153
star
28

oc

The OpenShift Command Line, part of OKD
Go
150
star
29

origin-aggregated-logging

JavaScript
142
star
30

machine-api-operator

Machine API operator
Go
137
star
31

origin-web-console

Web Console for the OpenShift Application Platform
JavaScript
123
star
32

svt

Shell
117
star
33

imagebuilder

Builds Dockerfile using the Docker client (with squashing! and secrets!)
Go
116
star
34

client-go

Go client for OpenShift
Shell
104
star
35

compliance-operator

Operator providing OpenShift cluster compliance checks
Go
100
star
36

telemeter

Prometheus push federation
Go
96
star
37

assisted-service

Go
90
star
38

cluster-network-operator

Create and manage cluster networking configuration
Go
85
star
39

cincinnati

Rust
84
star
40

vagrant-openshift

Ruby
83
star
41

cluster-logging-operator

Operator to support logging subsystem of OpenShift
Go
83
star
42

openshift-pep

Public Project Enhancement Proposals for the OpenShift product. Tracks and maintains high level architectural documents related to future OpenShift changes.
82
star
43

jenkins-plugin

Java
81
star
44

sriov-network-operator

SR-IOV Network Operator
Go
81
star
45

origin-metrics

Shell
78
star
46

openshift-restclient-java

Java
78
star
47

must-gather

A client tool for gathering information about an operator managed component.
Shell
77
star
48

api

Canonical location of the OpenShift API definition.
Go
75
star
49

sdn

Go
73
star
50

cluster-version-operator

Go
72
star
51

library-go

Helpers for going from apis and clients to useful runtime constructs
Go
72
star
52

os

Shell
71
star
53

cluster-etcd-operator

Operator to manage the lifecycle of the etcd members of an OpenShift cluster
Go
70
star
54

cluster-node-tuning-operator

Manage node-level tuning by orchestrating the tuned daemon.
Go
69
star
55

openshift-sdn

Go
69
star
56

openshift-origin-design

Design repository for all things OpenShift
SCSS
68
star
57

autoheal

Autoheals based on monitoring alerts
Go
66
star
58

elasticsearch-operator

Go
66
star
59

cluster-kube-apiserver-operator

The kube-apiserver operator installs and maintains the kube-apiserver on a cluster
Go
65
star
60

oadp-operator

OADP Operator
Go
64
star
61

openshift-java-client

Java Client for the OpenShift REST API
Java
63
star
62

rosa

Go
61
star
63

ovn-kubernetes

Kubernetes integration for OVN
Go
61
star
64

community

Community organizational documentations and process for OKD
61
star
65

federation-dev

Dev preview of federation
Shell
59
star
66

cluster-ingress-operator

The Cluster Ingress Operator manages highly available network ingress for OpenShift
Go
59
star
67

oc-mirror

Lifecycle manager for internet-disconnected OpenShift environments
Go
58
star
68

openshift-client-python

A python library for interacting with OpenShift via the OpenShift client binary.
Python
56
star
69

cincinnati-graph-data

Release node and upgrade edge metadata for Cincinnati graphs.
Python
56
star
70

router

Ingress controller for OpenShift
Go
55
star
71

cluster-image-registry-operator

The image registry operator installs+maintains the internal registry on a cluster
Go
55
star
72

cluster-operator

Go
52
star
73

local-storage-operator

Operator for local storage
Go
51
star
74

tektoncd-pipeline-operator

tektoncd-pipeline operator for Kubernetes to manage installation, updation and uninstallation of tekton-cd pipelines.
Go
51
star
75

pipelines-catalog

A repository for OpenShift Pipelines tasks
Python
50
star
76

openshift-azure

Azure Red Hat Openshift
Go
49
star
77

cloud-credential-operator

Manage cloud provider credentials as Kubernetes CRDs
Go
48
star
78

assisted-installer

Go
48
star
79

verification-tests

Blackbox test suite for OpenShift.
Gherkin
47
star
80

community.okd

OKD/Openshift collection for Ansible
Python
45
star
81

service-idler

A controller for idling and unidling groups of scalable Kubernetes resources
Go
44
star
82

ruby-hello-world

Hello world ruby sample for OpenShift v3
Ruby
44
star
83

managed-cluster-config

Static deployable artifacts for managed OSD clusters
HTML
42
star
84

cluster-authentication-operator

OpenShift operator for the top level Authentication and OAuth configs.
Go
41
star
85

image-registry

OpenShift cluster image registry
Go
40
star
86

console-operator

The console operator installs and maintains the web console on a cluster
Go
38
star
87

sriov-cni

An SRIOV CNI plugin
Go
38
star
88

openshift-extras

Unofficial tools for use with OpenShift
Ruby
38
star
89

runbooks

Runbooks for Alerts on OCP
Shell
37
star
90

cluster-kube-controller-manager-operator

The kube-controller-manager operator installs and maintains the kube-controller-manager on a cluster
Go
37
star
91

cluster-kube-descheduler-operator

An operator to run descheduler on OpenShift.
Go
37
star
92

assisted-test-infra

Python
36
star
93

windows-machine-config-operator

Windows MCO for OpenShift that handles addition of Windows nodes to the cluster
Go
36
star
94

insights-operator

Go
36
star
95

service-ca-operator

Controller to mint and manage serving certificates for Kubernetes services
Go
36
star
96

openshift-jee-sample

A sample app to be deployed on openshift environments
HTML
35
star
97

cluster-autoscaler-operator

Manage Kubernetes cluster-autoscaler deployments
Go
35
star
98

certman-operator

Operator to Manage Let's Encrypt certificates for OpenShift Clusters
Go
35
star
99

python-interface

Python
35
star
100

cluster-dns-operator

The Cluster DNS Operator manages cluster DNS services for OpenShift
Go
35
star