File: README.md

package info (click to toggle)
python-openshift 0.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 332 kB
  • sloc: python: 1,824; makefile: 20; sh: 14
file content (492 lines) | stat: -rw-r--r-- 14,172 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
OpenShift python client
======================

[![Build Status](https://travis-ci.com/openshift/openshift-restclient-python.svg?branch=master)](https://travis-ci.com/openshift/openshift-restclient-python)
[![Coverage Status](https://coveralls.io/repos/github/openshift/openshift-restclient-python/badge.svg?branch=master)](https://coveralls.io/github/openshift/openshift-restclient-python?branch=master)

Python client for the [Kubernetes](https://kubernetes.io/) and [OpenShift](http://openshift.redhat.com/) 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](#installation)
* [Usage](#usage)
* [Examples](#examples)
  * [Create a Service](#create-a-service)
  * [Create a Route](#create-a-route)
  * [List Projects](#list-projects)
  * [Custom Resources](#custom-resources)
  * [OpenShift Login with username and password](#openshift-login-with-username-and-password)
* [Available Methods for Resources](#available-methods-for-resources)
  * [Get](#get)
  * [Create](#create)
  * [Delete](#delete)
  * [Patch](#patch)
  * [Replace](#replace)
  * [Watch](#watch)
* [Community, Support, Discussion](#community-support-discussion)
* [Code of Conduct](#code-of-conduct)

# Installation

From source:

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

From [PyPi](https://pypi.python.org/pypi/openshift/) directly:

```
pip install openshift
```

Using [Dockerfile](Dockerfile):

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

# Usage

The OpenShift client depends on the [Kubernetes Python
client](https://github.com/kubernetes-incubator/client-python.git), 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](https://github.com/kubernetes-client/python/blob/master/kubernetes/client/configuration.py)
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](https://github.com/kubernetes-client/python-base/blob/master/config/kube_config.py)
that returns an API client to be used with any API object.
There are plenty of [Kubernetes Client
examples](https://github.com/kubernetes-client/python/tree/master/examples) to
examine other ways of accessing Kubernetes Clusters.

# Examples

## Create a Service

```python
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:

```python
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:

```python
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:

```python
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

```python
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`

```python
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.

```python
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)`

```python
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)`

```python
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.

```python
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)`

```python
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)`

```python
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)`

```python
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](https://github.com/openshift/openshift-restclient-python/issues).

## Code of Conduct

Participation in the Kubernetes community is governed by the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).