or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-management.mdconfig-secrets.mdcontainer-management.mdcontext-management.mderror-handling.mdimage-management.mdindex.mdnetwork-management.mdplugin-management.mdswarm-services.mdsystem-events.mdvolume-management.md

context-management.mddocs/

0

# Context Management

1

2

Docker context management for connecting to different Docker hosts and orchestrators with persistent configuration and credential storage.

3

4

## Capabilities

5

6

### Context

7

8

Docker context representation that encapsulates connection information, TLS configuration, and orchestrator settings for Docker hosts.

9

10

```python { .api }

11

class Context:

12

def __init__(self, name, orchestrator=None, host=None, endpoints=None, tls=False):

13

"""

14

Create a new Docker context.

15

16

Args:

17

name (str): Context name

18

orchestrator (str): Orchestrator type ('swarm', 'kubernetes', etc.)

19

host (str): Docker host URL

20

endpoints (dict): Endpoint configuration

21

tls (bool): Enable TLS

22

"""

23

24

def set_endpoint(self, name='docker', host=None, tls_cfg=None, skip_tls_verify=False, def_namespace=None):

25

"""

26

Configure context endpoint.

27

28

Args:

29

name (str): Endpoint name (default: 'docker')

30

host (str): Host URL

31

tls_cfg (TLSConfig): TLS configuration

32

skip_tls_verify (bool): Skip TLS verification

33

def_namespace (str): Default namespace for Kubernetes

34

"""

35

36

def inspect(self):

37

"""

38

Get context metadata and configuration.

39

40

Returns:

41

dict: Context information including name, metadata, endpoints

42

"""

43

44

def save(self):

45

"""

46

Save context to disk for persistent storage.

47

"""

48

49

def remove(self):

50

"""

51

Remove context from disk.

52

"""

53

54

@classmethod

55

def load_context(cls, name):

56

"""

57

Load existing context from disk.

58

59

Args:

60

name (str): Context name

61

62

Returns:

63

Context: Context instance or None if not found

64

"""

65

66

# Properties

67

name: str # Context name

68

orchestrator: str # Orchestrator type

69

endpoints: dict # Endpoint configurations

70

tls_cfg: dict # TLS configurations

71

meta_path: str # Metadata storage path

72

tls_path: str # TLS certificate storage path

73

```

74

75

### ContextAPI

76

77

Context management operations for creating, listing, retrieving, and managing Docker contexts.

78

79

```python { .api }

80

class ContextAPI:

81

DEFAULT_CONTEXT: Context # Default context instance

82

83

@classmethod

84

def create_context(cls, name, orchestrator=None, host=None, tls_cfg=None, default_namespace=None, skip_tls_verify=False):

85

"""

86

Create a new Docker context.

87

88

Args:

89

name (str): Context name (required)

90

orchestrator (str): Orchestrator type ('swarm', 'kubernetes')

91

host (str): Docker host URL

92

tls_cfg (TLSConfig): TLS configuration

93

default_namespace (str): Default namespace for Kubernetes

94

skip_tls_verify (bool): Skip TLS verification

95

96

Returns:

97

Context: Created context instance

98

99

Raises:

100

MissingContextParameter: If name is not provided

101

ContextAlreadyExists: If context with name already exists

102

ContextException: If name is 'default' (reserved)

103

"""

104

105

@classmethod

106

def get_context(cls, name=None):

107

"""

108

Retrieve a context by name.

109

110

Args:

111

name (str): Context name (defaults to current context)

112

113

Returns:

114

Context: Context instance or None if not found

115

"""

116

117

@classmethod

118

def list_contexts(cls):

119

"""

120

List all available contexts.

121

122

Returns:

123

list: List of context dictionaries with metadata

124

"""

125

126

@classmethod

127

def remove_context(cls, name):

128

"""

129

Remove a context.

130

131

Args:

132

name (str): Context name to remove

133

134

Raises:

135

ContextNotFound: If context doesn't exist

136

ContextException: If trying to remove default context

137

"""

138

139

@classmethod

140

def get_current_context_name(cls):

141

"""

142

Get the name of the currently active context.

143

144

Returns:

145

str: Current context name

146

"""

147

```

148

149

## Usage Examples

150

151

### Basic Context Management

152

153

```python

154

from docker.context import Context, ContextAPI

155

156

# Create a new context

157

ctx = ContextAPI.create_context(

158

name='production',

159

host='tcp://prod.example.com:2376',

160

tls_cfg=True

161

)

162

163

# List all contexts

164

contexts = ContextAPI.list_contexts()

165

for context in contexts:

166

print(f"Context: {context['Name']}")

167

print(f"Host: {context['Endpoints']['docker']['Host']}")

168

169

# Get current context

170

current = ContextAPI.get_context()

171

print(f"Current context: {current.name}")

172

173

# Switch to a different context

174

prod_ctx = ContextAPI.get_context('production')

175

if prod_ctx:

176

print(f"Using production context: {prod_ctx.endpoints}")

177

```

178

179

### Context with TLS Configuration

180

181

```python

182

from docker.context import ContextAPI

183

from docker.tls import TLSConfig

184

185

# Create TLS configuration

186

tls_config = TLSConfig(

187

client_cert=('/path/to/client-cert.pem', '/path/to/client-key.pem'),

188

ca_cert='/path/to/ca.pem',

189

verify=True

190

)

191

192

# Create secure context

193

secure_ctx = ContextAPI.create_context(

194

name='secure-remote',

195

host='tcp://secure.example.com:2376',

196

tls_cfg=tls_config

197

)

198

199

print(f"Created secure context: {secure_ctx.name}")

200

print(f"Endpoints: {secure_ctx.endpoints}")

201

```

202

203

### Kubernetes Context

204

205

```python

206

from docker.context import ContextAPI

207

208

# Create Kubernetes context

209

k8s_ctx = ContextAPI.create_context(

210

name='k8s-cluster',

211

orchestrator='kubernetes',

212

host='https://k8s.example.com:6443',

213

default_namespace='production'

214

)

215

216

# Inspect the context

217

metadata = k8s_ctx.inspect()

218

print(f"Context metadata: {metadata}")

219

```

220

221

### Context Error Handling

222

223

```python

224

from docker.context import ContextAPI

225

from docker.errors import (

226

ContextAlreadyExists,

227

ContextNotFound,

228

MissingContextParameter,

229

ContextException

230

)

231

232

try:

233

# Create context

234

ctx = ContextAPI.create_context(name='test-context')

235

print(f"Created context: {ctx.name}")

236

237

except MissingContextParameter as e:

238

print(f"Missing parameter: {e.param}")

239

240

except ContextAlreadyExists as e:

241

print(f"Context already exists: {e.name}")

242

# Get existing context instead

243

ctx = ContextAPI.get_context(e.name)

244

245

except ContextException as e:

246

print(f"Context operation failed: {e.msg}")

247

248

# Safe context retrieval

249

try:

250

ctx = ContextAPI.get_context('nonexistent')

251

if ctx:

252

print(f"Found context: {ctx.name}")

253

else:

254

print("Context not found")

255

256

except ContextNotFound as e:

257

print(f"Context not found: {e.name}")

258

259

# Remove context safely

260

try:

261

ContextAPI.remove_context('test-context')

262

print("Context removed successfully")

263

264

except ContextNotFound as e:

265

print(f"Cannot remove - context not found: {e.name}")

266

267

except ContextException as e:

268

print(f"Cannot remove context: {e.msg}")

269

```

270

271

### Advanced Context Operations

272

273

```python

274

from docker.context import Context, ContextAPI

275

276

# Load context from disk

277

ctx = Context.load_context('production')

278

if ctx:

279

print(f"Loaded context: {ctx.name}")

280

print(f"Meta path: {ctx.meta_path}")

281

print(f"TLS path: {ctx.tls_path}")

282

283

# Create context with multiple endpoints

284

multi_ctx = Context(

285

name='multi-endpoint',

286

endpoints={

287

'docker': {

288

'Host': 'tcp://docker.example.com:2376',

289

'SkipTLSVerify': False

290

},

291

'kubernetes': {

292

'Host': 'https://k8s.example.com:6443',

293

'DefaultNamespace': 'default'

294

}

295

}

296

)

297

298

# Configure additional endpoint

299

multi_ctx.set_endpoint(

300

name='swarm',

301

host='tcp://swarm.example.com:2377',

302

skip_tls_verify=False

303

)

304

305

# Save context

306

multi_ctx.save()

307

```

308

309

### Using Contexts with Docker Client

310

311

```python

312

import docker

313

from docker.context import ContextAPI

314

315

# Get production context

316

prod_ctx = ContextAPI.get_context('production')

317

if prod_ctx:

318

# Use context configuration to create client

319

endpoint = prod_ctx.endpoints.get('docker', {})

320

client = docker.DockerClient(

321

base_url=endpoint.get('Host'),

322

tls=not endpoint.get('SkipTLSVerify', True)

323

)

324

325

# Use client with production context

326

containers = client.containers.list()

327

print(f"Production containers: {len(containers)}")

328

```