or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-apis.mdconfiguration.mddynamic-client.mdindex.mdleader-election.mdstreaming.mdutils.mdwatch.md

configuration.mddocs/

0

# Configuration

1

2

Multiple methods for loading Kubernetes cluster credentials and configuration, supporting kubeconfig files, in-cluster authentication, exec providers, OIDC, and various credential plugins. The configuration system automatically detects the appropriate authentication method and handles credential refresh.

3

4

## Capabilities

5

6

### Primary Configuration Functions

7

8

The main entry points for loading Kubernetes configuration in different environments.

9

10

```python { .api }

11

async def load_config(**kwargs):

12

"""

13

Unified configuration loader that automatically detects and loads appropriate config.

14

15

Tries in order:

16

1. Provided config_file or kube_config_path parameter

17

2. Default kubeconfig location (~/.kube/config)

18

3. In-cluster configuration (service account)

19

20

Parameters:

21

- config_file: str, path to kubeconfig file

22

- kube_config_path: str, alternative parameter name for config_file

23

- context: str, kubeconfig context to use

24

- client_configuration: Configuration, object to populate

25

- persist_config: bool, whether to set as default global config

26

"""

27

28

async def load_kube_config(config_file=None, context=None, client_configuration=None,

29

persist_config=True, **kwargs):

30

"""

31

Load configuration from kubeconfig file.

32

33

Parameters:

34

- config_file: str, path to kubeconfig file (default: ~/.kube/config)

35

- context: str, kubeconfig context to use (default: current-context)

36

- client_configuration: Configuration, object to populate

37

- persist_config: bool, whether to set as default global config

38

"""

39

40

def load_incluster_config(client_configuration=None, try_refresh_token=True):

41

"""

42

Load in-cluster configuration from service account mounted in pod.

43

44

Uses:

45

- /var/run/secrets/kubernetes.io/serviceaccount/token for authentication

46

- /var/run/secrets/kubernetes.io/serviceaccount/ca.crt for CA certificate

47

- KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT environment variables

48

49

Parameters:

50

- client_configuration: Configuration, object to populate

51

- try_refresh_token: bool, whether to refresh tokens automatically

52

"""

53

54

async def load_kube_config_from_dict(config_dict, context=None, client_configuration=None,

55

temp_file_path=None):

56

"""

57

Load configuration from dictionary representation of kubeconfig.

58

59

Parameters:

60

- config_dict: dict, kubeconfig as dictionary

61

- context: str, context name to use

62

- client_configuration: Configuration, object to populate

63

- temp_file_path: str, directory for temporary files

64

"""

65

```

66

67

### Client Creation Functions

68

69

Functions for creating ApiClient instances with pre-configured authentication.

70

71

```python { .api }

72

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

73

"""

74

Create new ApiClient from kubeconfig file.

75

76

Parameters:

77

- config_file: str, path to kubeconfig file

78

- context: str, kubeconfig context to use

79

- persist_config: bool, whether to set as default global config

80

81

Returns:

82

- ApiClient: Configured client ready for use

83

"""

84

85

def new_client_from_config_dict(config_dict, context=None, persist_config=True):

86

"""

87

Create new ApiClient from kubeconfig dictionary.

88

89

Parameters:

90

- config_dict: dict, kubeconfig as dictionary

91

- context: str, context name to use

92

- persist_config: bool, whether to set as default global config

93

94

Returns:

95

- ApiClient: Configured client ready for use

96

"""

97

```

98

99

### Context Management

100

101

Functions for discovering and managing kubeconfig contexts.

102

103

```python { .api }

104

def list_kube_config_contexts(config_file=None):

105

"""

106

List all available contexts in kubeconfig file.

107

108

Parameters:

109

- config_file: str, path to kubeconfig file (default: ~/.kube/config)

110

111

Returns:

112

- tuple: (contexts_list, current_context_dict)

113

- contexts_list: List of all context dictionaries

114

- current_context_dict: Currently active context dictionary

115

"""

116

```

117

118

### Configuration Classes

119

120

Core classes for managing configuration state and loading kubeconfig files.

121

122

```python { .api }

123

class KubeConfigLoader:

124

def __init__(self, config_dict, active_context=None, get_google_credentials=None,

125

config_base_path=None, config_persister=None):

126

"""

127

Kubeconfig file parser and processor.

128

129

Parameters:

130

- config_dict: dict, kubeconfig content as dictionary

131

- active_context: str, context name to use

132

- get_google_credentials: callable, Google Cloud credential provider

133

- config_base_path: str, base path for resolving relative file paths

134

- config_persister: callable, function to persist configuration changes

135

"""

136

137

def load_and_set(self, client_configuration):

138

"""Load kubeconfig and populate Configuration object."""

139

140

def _load_authentication(self):

141

"""Load authentication configuration for active context."""

142

143

def _load_cluster_info(self):

144

"""Load cluster connection information."""

145

146

class FileOrData:

147

def __init__(self, data=None, file_path=None, file_base_path=None):

148

"""

149

Utility for handling kubeconfig fields that can be inline data or file references.

150

151

Parameters:

152

- data: str, inline data content

153

- file_path: str, path to file containing data

154

- file_base_path: str, base path for resolving relative file paths

155

"""

156

157

def as_data(self):

158

"""Get data content as string."""

159

160

def as_bytes(self):

161

"""Get data content as bytes."""

162

163

class InClusterConfigLoader:

164

def __init__(self, token_filename=None, cert_filename=None, environ=None):

165

"""

166

In-cluster configuration loader for pods.

167

168

Parameters:

169

- token_filename: str, path to service account token file

170

- cert_filename: str, path to CA certificate file

171

- environ: dict, environment variables

172

"""

173

174

def load_and_set(self, client_configuration):

175

"""Load in-cluster config and populate Configuration object."""

176

```

177

178

### Authentication Providers

179

180

Support for various Kubernetes authentication mechanisms.

181

182

```python { .api }

183

class ExecProvider:

184

def __init__(self, exec_config):

185

"""

186

External credential provider (exec) support.

187

188

Parameters:

189

- exec_config: dict, exec configuration from kubeconfig

190

"""

191

192

def run(self, previous_response=None):

193

"""Execute credential provider and return credentials."""

194

195

class OpenIDRequestor:

196

def __init__(self, configuration, id_token_string):

197

"""

198

OpenID Connect (OIDC) authentication support.

199

200

Parameters:

201

- configuration: Configuration, client configuration

202

- id_token_string: str, OIDC ID token

203

"""

204

205

def refresh_oidc_token(self):

206

"""Refresh OIDC token using refresh token."""

207

```

208

209

### Exception Classes

210

211

Configuration-specific exception types for error handling.

212

213

```python { .api }

214

class ConfigException(Exception):

215

"""

216

Configuration-related errors including file parsing, authentication failures,

217

and invalid kubeconfig structure.

218

"""

219

def __init__(self, message):

220

"""Initialize with error message."""

221

```

222

223

### Constants

224

225

Important constants used throughout the configuration system.

226

227

```python { .api }

228

# Default kubeconfig file location

229

KUBE_CONFIG_DEFAULT_LOCATION: str = "~/.kube/config"

230

231

# In-cluster service account environment variables

232

SERVICE_HOST_ENV_NAME: str = "KUBERNETES_SERVICE_HOST"

233

SERVICE_PORT_ENV_NAME: str = "KUBERNETES_SERVICE_PORT"

234

235

# In-cluster service account file paths

236

SERVICE_TOKEN_FILENAME: str = "/var/run/secrets/kubernetes.io/serviceaccount/token"

237

SERVICE_CERT_FILENAME: str = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"

238

SERVICE_NAMESPACE_FILENAME: str = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"

239

```

240

241

## Usage Examples

242

243

### Basic Configuration Loading

244

245

```python

246

import asyncio

247

from kubernetes_asyncio import client, config

248

249

async def basic_config():

250

# Automatically detect and load appropriate configuration

251

await config.load_config()

252

253

# Use the loaded configuration

254

v1 = client.CoreV1Api()

255

pods = await v1.list_pod_for_all_namespaces()

256

print(f"Found {len(pods.items)} pods")

257

await v1.api_client.close()

258

259

asyncio.run(basic_config())

260

```

261

262

### Specific Configuration File

263

264

```python

265

async def specific_config():

266

# Load specific kubeconfig file and context

267

await config.load_kube_config(

268

config_file="/path/to/custom/kubeconfig",

269

context="production-cluster"

270

)

271

272

v1 = client.CoreV1Api()

273

namespaces = await v1.list_namespace()

274

print(f"Cluster has {len(namespaces.items)} namespaces")

275

await v1.api_client.close()

276

```

277

278

### In-Cluster Configuration

279

280

```python

281

async def incluster_config():

282

# For applications running inside Kubernetes pods

283

try:

284

config.load_incluster_config()

285

print("Using in-cluster configuration")

286

except config.ConfigException:

287

# Fallback to kubeconfig file

288

await config.load_kube_config()

289

print("Using kubeconfig file")

290

291

v1 = client.CoreV1Api()

292

# ... use client

293

await v1.api_client.close()

294

```

295

296

### Multiple Contexts

297

298

```python

299

async def multiple_contexts():

300

# List available contexts

301

contexts, active_context = config.list_kube_config_contexts()

302

303

print("Available contexts:")

304

for context in contexts:

305

name = context['name']

306

cluster = context['context']['cluster']

307

user = context['context']['user']

308

print(f" {name}: cluster={cluster}, user={user}")

309

310

print(f"Current context: {active_context['name']}")

311

312

# Switch to different context

313

await config.load_kube_config(context="staging-cluster")

314

```

315

316

### Custom Configuration Object

317

318

```python

319

async def custom_config():

320

# Create custom configuration

321

configuration = client.Configuration()

322

323

# Load into custom configuration object

324

await config.load_kube_config(client_configuration=configuration)

325

326

# Use with specific client

327

api_client = client.ApiClient(configuration)

328

v1 = client.CoreV1Api(api_client)

329

330

try:

331

nodes = await v1.list_node()

332

print(f"Cluster has {len(nodes.items)} nodes")

333

finally:

334

await api_client.close()

335

```

336

337

### Client Factory Pattern

338

339

```python

340

async def client_factory():

341

# Create pre-configured clients

342

api_client = config.new_client_from_config(

343

config_file="/path/to/kubeconfig",

344

context="production"

345

)

346

347

# Use with any API

348

v1 = client.CoreV1Api(api_client)

349

apps_v1 = client.AppsV1Api(api_client)

350

351

try:

352

pods = await v1.list_pod_for_all_namespaces()

353

deployments = await apps_v1.list_deployment_for_all_namespaces()

354

print(f"Found {len(pods.items)} pods and {len(deployments.items)} deployments")

355

finally:

356

await api_client.close()

357

```

358

359

### Programmatic Configuration

360

361

```python

362

async def programmatic_config():

363

# Build configuration from environment or secrets

364

configuration = client.Configuration()

365

configuration.host = "https://kubernetes.example.com:6443"

366

configuration.api_key = {"authorization": "Bearer " + token}

367

configuration.ssl_ca_cert = "/path/to/ca.crt"

368

369

# Create client with custom configuration

370

api_client = client.ApiClient(configuration)

371

v1 = client.CoreV1Api(api_client)

372

373

try:

374

# Test connection

375

version = await client.VersionApi(api_client).get_code()

376

print(f"Connected to Kubernetes {version.git_version}")

377

finally:

378

await api_client.close()

379

```