or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-kubernetes

Python client library for interacting with Kubernetes clusters through the Kubernetes API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/kubernetes@33.1.x

To install, run

npx @tessl/cli install tessl/pypi-kubernetes@33.1.0

0

# Kubernetes Python Client

1

2

The official Python client library for Kubernetes, providing comprehensive programmatic access to Kubernetes clusters through the Kubernetes API. This library enables developers to manage all Kubernetes resources including pods, services, deployments, and custom resources with full support for authentication, configuration management, and dynamic client capabilities.

3

4

## Package Information

5

6

- **Package Name**: kubernetes

7

- **Language**: Python

8

- **Installation**: `pip install kubernetes`

9

10

## Core Imports

11

12

```python

13

from kubernetes import client, config

14

```

15

16

For dynamic client operations:

17

18

```python

19

from kubernetes import dynamic

20

```

21

22

For watching resource changes:

23

24

```python

25

from kubernetes import watch

26

```

27

28

For streaming operations (exec, logs, port-forward):

29

30

```python

31

from kubernetes import stream

32

```

33

34

For utility functions:

35

36

```python

37

from kubernetes import utils

38

```

39

40

For leader election:

41

42

```python

43

from kubernetes import leaderelection

44

```

45

46

For networking operations:

47

48

```python

49

from kubernetes.client import NetworkingV1Api

50

```

51

52

For storage management:

53

54

```python

55

from kubernetes.client import StorageV1Api

56

```

57

58

For autoscaling:

59

60

```python

61

from kubernetes.client import AutoscalingV1Api, AutoscalingV2Api

62

```

63

64

## Basic Usage

65

66

```python

67

from kubernetes import client, config

68

69

# Load kubeconfig from default location or in-cluster config

70

config.load_kube_config() # or config.load_incluster_config()

71

72

# Create API client instance

73

v1 = client.CoreV1Api()

74

75

# List all pods in default namespace

76

pods = v1.list_namespaced_pod(namespace="default")

77

for pod in pods.items:

78

print(f"Pod: {pod.metadata.name}")

79

80

# Create a simple pod

81

pod_manifest = {

82

"apiVersion": "v1",

83

"kind": "Pod",

84

"metadata": {"name": "test-pod"},

85

"spec": {

86

"containers": [{

87

"name": "test-container",

88

"image": "nginx:latest",

89

"ports": [{"containerPort": 80}]

90

}]

91

}

92

}

93

94

# Create the pod

95

v1.create_namespaced_pod(namespace="default", body=pod_manifest)

96

```

97

98

## Architecture

99

100

The Kubernetes Python client is organized around several key components:

101

102

- **Generated API Classes**: Auto-generated client classes for all Kubernetes API groups (CoreV1Api, AppsV1Api, etc.)

103

- **Model Classes**: Python representations of all Kubernetes resources (V1Pod, V1Service, etc.)

104

- **Configuration**: Support for kubeconfig files and in-cluster authentication

105

- **Dynamic Client**: Generic client for any Kubernetes resource without pre-generated classes

106

- **Watch**: Event streaming for real-time resource monitoring

107

- **Stream**: Execute commands and stream logs from pods

108

- **Utils**: Helper functions for common operations like creating resources from YAML

109

110

## Capabilities

111

112

### Configuration and Authentication

113

114

Handles loading Kubernetes cluster configuration from kubeconfig files, in-cluster service accounts, or programmatic configuration, with support for various authentication methods including certificates, tokens, and cloud provider authentication.

115

116

```python { .api }

117

def load_kube_config(config_file=None, context=None, client_configuration=None, persist_config=True): ...

118

def load_incluster_config(): ...

119

def list_kube_config_contexts(config_file=None): ...

120

def new_client_from_config(config_file=None, context=None, persist_config=True): ...

121

```

122

123

[Configuration](./configuration.md)

124

125

### Core API Resources

126

127

Management of fundamental Kubernetes resources including pods, services, namespaces, config maps, secrets, and persistent volumes. These form the basic building blocks for all Kubernetes applications.

128

129

```python { .api }

130

class CoreV1Api:

131

def create_namespaced_pod(self, namespace: str, body: V1Pod, **kwargs) -> V1Pod: ...

132

def list_namespaced_pod(self, namespace: str, **kwargs) -> V1PodList: ...

133

def read_namespaced_pod(self, name: str, namespace: str, **kwargs) -> V1Pod: ...

134

def delete_namespaced_pod(self, name: str, namespace: str, **kwargs) -> V1Status: ...

135

def create_namespaced_service(self, namespace: str, body: V1Service, **kwargs) -> V1Service: ...

136

def list_namespaced_service(self, namespace: str, **kwargs) -> V1ServiceList: ...

137

```

138

139

[Core Resources](./core-resources.md)

140

141

### Application Workloads

142

143

Management of application deployment patterns including deployments, replica sets, daemon sets, stateful sets, jobs, and cron jobs. These resources provide scalable and reliable application hosting patterns.

144

145

```python { .api }

146

class AppsV1Api:

147

def create_namespaced_deployment(self, namespace: str, body: V1Deployment, **kwargs) -> V1Deployment: ...

148

def list_namespaced_deployment(self, namespace: str, **kwargs) -> V1DeploymentList: ...

149

def patch_namespaced_deployment(self, name: str, namespace: str, body: object, **kwargs) -> V1Deployment: ...

150

def create_namespaced_stateful_set(self, namespace: str, body: V1StatefulSet, **kwargs) -> V1StatefulSet: ...

151

def create_namespaced_daemon_set(self, namespace: str, body: V1DaemonSet, **kwargs) -> V1DaemonSet: ...

152

```

153

154

[Application Workloads](./application-workloads.md)

155

156

### Dynamic Client Operations

157

158

Generic client for working with any Kubernetes resource without pre-generated classes. Enables operations on custom resources, API discovery, and flexible resource manipulation with runtime type resolution.

159

160

```python { .api }

161

class DynamicClient:

162

def __init__(self, client: ApiClient, cache_file: str = None, discoverer=None): ...

163

def get(self, resource: Resource, name: str = None, namespace: str = None, **kwargs) -> ResourceInstance: ...

164

def create(self, resource: Resource, body: dict = None, **kwargs) -> ResourceInstance: ...

165

def delete(self, resource: Resource, name: str = None, namespace: str = None, **kwargs) -> ResourceInstance: ...

166

def patch(self, resource: Resource, body: dict = None, **kwargs) -> ResourceInstance: ...

167

```

168

169

[Dynamic Client](./dynamic-client.md)

170

171

### Resource Watching

172

173

Event streaming capabilities for monitoring real-time changes to Kubernetes resources. Provides efficient watch operations that can be filtered and processed for automated responses to cluster state changes.

174

175

```python { .api }

176

class Watch:

177

def stream(self, func, *args, **kwargs): ...

178

def stop(self): ...

179

```

180

181

[Resource Watching](./resource-watching.md)

182

183

### Pod Streaming Operations

184

185

Execute commands in running pods, stream container logs, and establish port forwarding connections. Essential for debugging, log analysis, and establishing secure connections to pod services.

186

187

```python { .api }

188

def stream(ws_client, channel, *args, **kwargs): ...

189

def portforward(api_instance, name: str, namespace: str, ports: list, **kwargs): ...

190

```

191

192

[Streaming Operations](./streaming-operations.md)

193

194

### Utility Functions

195

196

Helper functions for common Kubernetes operations including creating resources from YAML files, parsing quantity values, and working with Kubernetes-specific data formats.

197

198

```python { .api }

199

def create_from_yaml(k8s_client, yaml_file: str, namespace: str = "default", **kwargs): ...

200

def create_from_dict(k8s_client, data: dict, namespace: str = "default", **kwargs): ...

201

def parse_quantity(quantity: str) -> float: ...

202

def parse_duration(duration: str) -> int: ...

203

```

204

205

[Utilities](./utilities.md)

206

207

### Custom Resources and API Extensions

208

209

Work with custom resource definitions, API extensions, and admission controllers. Enables extending Kubernetes with custom APIs and controllers while maintaining full client library support.

210

211

```python { .api }

212

class ApiextensionsV1Api:

213

def create_custom_resource_definition(self, body: V1CustomResourceDefinition, **kwargs) -> V1CustomResourceDefinition: ...

214

def list_custom_resource_definition(self, **kwargs) -> V1CustomResourceDefinitionList: ...

215

216

class CustomObjectsApi:

217

def create_namespaced_custom_object(self, group: str, version: str, namespace: str, plural: str, body: object, **kwargs) -> object: ...

218

def list_namespaced_custom_object(self, group: str, version: str, namespace: str, plural: str, **kwargs) -> object: ...

219

```

220

221

[Custom Resources](./custom-resources.md)

222

223

### RBAC and Security

224

225

Role-based access control management including roles, cluster roles, role bindings, service accounts, and security policies. Essential for implementing proper access controls and security policies in Kubernetes clusters.

226

227

```python { .api }

228

class RbacAuthorizationV1Api:

229

def create_namespaced_role(self, namespace: str, body: V1Role, **kwargs) -> V1Role: ...

230

def create_cluster_role(self, body: V1ClusterRole, **kwargs) -> V1ClusterRole: ...

231

def create_namespaced_role_binding(self, namespace: str, body: V1RoleBinding, **kwargs) -> V1RoleBinding: ...

232

```

233

234

[RBAC and Security](./rbac-security.md)

235

236

### Leader Election

237

238

Distributed leader election for building highly available applications where only one instance should be active. Uses Kubernetes resources as coordination locks with automatic lease renewal and failover capabilities.

239

240

```python { .api }

241

class LeaderElection:

242

def __init__(self, election_config: Config): ...

243

def run(self) -> None: ...

244

245

class Config:

246

def __init__(self, lock, lease_duration: int, renew_deadline: int, retry_period: int, onstarted_leading: callable, onstopped_leading: callable = None): ...

247

248

class ConfigMapLock:

249

def __init__(self, name: str, namespace: str, identity: str): ...

250

```

251

252

[Leader Election](./leader-election.md)

253

254

### Networking

255

256

Network management including ingress controllers, network policies, and service networking. Provides control over HTTP/HTTPS routing, traffic policies, and network security within clusters.

257

258

```python { .api }

259

class NetworkingV1Api:

260

def create_namespaced_ingress(self, namespace: str, body: V1Ingress, **kwargs) -> V1Ingress: ...

261

def create_namespaced_network_policy(self, namespace: str, body: V1NetworkPolicy, **kwargs) -> V1NetworkPolicy: ...

262

def create_ingress_class(self, body: V1IngressClass, **kwargs) -> V1IngressClass: ...

263

```

264

265

[Networking](./networking.md)

266

267

### Storage Management

268

269

Advanced storage capabilities including storage classes, volume attachments, CSI drivers, and storage capacity management for persistent storage infrastructure.

270

271

```python { .api }

272

class StorageV1Api:

273

def create_storage_class(self, body: V1StorageClass, **kwargs) -> V1StorageClass: ...

274

def create_volume_attachment(self, body: V1VolumeAttachment, **kwargs) -> V1VolumeAttachment: ...

275

def create_csi_driver(self, body: V1CSIDriver, **kwargs) -> V1CSIDriver: ...

276

```

277

278

[Storage Management](./storage.md)

279

280

### Autoscaling

281

282

Horizontal Pod Autoscaler (HPA) management for automatic scaling based on CPU, memory, or custom metrics with advanced scaling behaviors and policies.

283

284

```python { .api }

285

class AutoscalingV1Api:

286

def create_namespaced_horizontal_pod_autoscaler(self, namespace: str, body: V1HorizontalPodAutoscaler, **kwargs) -> V1HorizontalPodAutoscaler: ...

287

288

class AutoscalingV2Api:

289

def create_namespaced_horizontal_pod_autoscaler(self, namespace: str, body: V2HorizontalPodAutoscaler, **kwargs) -> V2HorizontalPodAutoscaler: ...

290

```

291

292

[Autoscaling](./autoscaling.md)

293

294

## Common Resource Types

295

296

### V1Pod

297

```python { .api }

298

class V1Pod:

299

api_version: str

300

kind: str

301

metadata: V1ObjectMeta

302

spec: V1PodSpec

303

status: V1PodStatus

304

```

305

306

### V1Service

307

```python { .api }

308

class V1Service:

309

api_version: str

310

kind: str

311

metadata: V1ObjectMeta

312

spec: V1ServiceSpec

313

status: V1ServiceStatus

314

```

315

316

### V1Deployment

317

```python { .api }

318

class V1Deployment:

319

api_version: str

320

kind: str

321

metadata: V1ObjectMeta

322

spec: V1DeploymentSpec

323

status: V1DeploymentStatus

324

```

325

326

### V1ObjectMeta

327

```python { .api }

328

class V1ObjectMeta:

329

name: str

330

namespace: str

331

labels: dict

332

annotations: dict

333

creation_timestamp: datetime

334

uid: str

335

resource_version: str

336

```

337

338

## Exception Types

339

340

```python { .api }

341

class ApiException(Exception):

342

status: int

343

reason: str

344

body: str

345

headers: dict

346

347

class ConfigException(Exception):

348

pass

349

350

class FailToCreateError(Exception):

351

api_exceptions: list

352

```