0
# Core Client Operations
1
2
Direct Vault operations providing complete control over HTTP requests and responses. These methods form the foundation for all Vault interactions and support both high-level operations and low-level API access.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Create and configure Vault client instances with authentication, networking, and connection parameters.
9
10
```python { .api }
11
class Client:
12
def __init__(
13
self,
14
url: str = None, # Vault server URL (default: http://localhost:8200 or VAULT_ADDR)
15
token: str = None, # Authentication token (or from VAULT_TOKEN env)
16
cert: tuple = None, # Client certificate tuple (cert_path, key_path)
17
verify: bool | str = None, # TLS verification: True, False, or CA bundle path
18
timeout: int = 30, # Request timeout in seconds
19
proxies: dict = None, # HTTP proxy configuration
20
allow_redirects: bool = True, # Follow HTTP redirects
21
session: requests.Session = None, # Custom requests session
22
adapter: Adapter = None, # HTTP adapter (default: JSONAdapter)
23
namespace: str = None, # Vault namespace for Enterprise
24
**kwargs # Additional adapter arguments
25
):
26
"""
27
Initialize Vault client with connection and authentication settings.
28
29
Environment variables:
30
- VAULT_ADDR: Default URL if url not provided
31
- VAULT_TOKEN: Default token if token not provided
32
- VAULT_CACERT: CA certificate file path
33
- VAULT_CAPATH: CA certificate directory path
34
- VAULT_CLIENT_CERT: Client certificate file path
35
- VAULT_CLIENT_KEY: Client private key file path
36
"""
37
```
38
39
### Basic CRUD Operations
40
41
Core operations for reading, writing, listing, and deleting secrets and configuration data.
42
43
```python { .api }
44
def read(self, path: str, wrap_ttl: str = None) -> dict | None:
45
"""
46
Read data from specified Vault path.
47
48
Args:
49
path: Vault path to read from (without /v1/ prefix)
50
wrap_ttl: TTL for response wrapping (e.g., "1h", "30m")
51
52
Returns:
53
Response dict with data, or None if path doesn't exist
54
55
Raises:
56
InvalidPath: Path not found (404)
57
Forbidden: Insufficient permissions (403)
58
"""
59
60
def list(self, path: str) -> dict | None:
61
"""
62
List secrets at specified path.
63
64
Args:
65
path: Vault path to list (without /v1/ prefix)
66
67
Returns:
68
Response dict with keys list, or None if path doesn't exist
69
"""
70
71
def write(self, *args, **kwargs) -> dict:
72
"""
73
Write data to Vault path (legacy method with kwargs restrictions).
74
75
Note: Deprecated parameter usage - use write_data() for unrestricted keys.
76
"""
77
78
def write_data(
79
self,
80
path: str,
81
*,
82
data: dict = None,
83
wrap_ttl: str = None
84
) -> dict:
85
"""
86
Write data to specified Vault path.
87
88
Args:
89
path: Vault path to write to (without /v1/ prefix)
90
data: Data dictionary to write
91
wrap_ttl: TTL for response wrapping
92
93
Returns:
94
Response dict from Vault
95
"""
96
97
def delete(self, path: str) -> None:
98
"""
99
Delete data at specified path.
100
101
Args:
102
path: Vault path to delete (without /v1/ prefix)
103
"""
104
```
105
106
### Authentication Management
107
108
Methods for managing authentication state and token operations.
109
110
```python { .api }
111
def is_authenticated(self) -> bool:
112
"""
113
Check if client is properly authenticated.
114
115
Returns:
116
True if authenticated, False otherwise
117
"""
118
119
def login(self, url: str, use_token: bool = True, **kwargs) -> dict:
120
"""
121
Perform authentication request.
122
123
Args:
124
url: Authentication endpoint URL
125
use_token: Whether to store returned token automatically
126
**kwargs: Authentication parameters
127
128
Returns:
129
Authentication response
130
"""
131
132
def logout(self, revoke_token: bool = False) -> None:
133
"""
134
Clear authentication and optionally revoke token.
135
136
Args:
137
revoke_token: Whether to revoke the token before clearing
138
"""
139
140
def auth_cubbyhole(self, token: str) -> dict:
141
"""
142
Authenticate using wrapped token from cubbyhole.
143
144
Args:
145
token: Wrapped response token
146
147
Returns:
148
Unwrapped authentication response
149
"""
150
```
151
152
### Token Operations
153
154
Direct token management methods for advanced token workflows.
155
156
```python { .api }
157
def lookup_token(
158
self,
159
token: str = None,
160
accessor: bool = False,
161
wrap_ttl: str = None
162
) -> dict:
163
"""
164
Look up token information.
165
166
Args:
167
token: Token to look up (None for self lookup)
168
accessor: Whether token parameter is an accessor
169
wrap_ttl: TTL for response wrapping
170
171
Returns:
172
Token information
173
"""
174
175
def revoke_token(
176
self,
177
token: str,
178
orphan: bool = False,
179
accessor: bool = False
180
) -> None:
181
"""
182
Revoke specified token.
183
184
Args:
185
token: Token or accessor to revoke
186
orphan: Revoke without revoking child tokens
187
accessor: Whether token parameter is an accessor
188
"""
189
190
def renew_token(
191
self,
192
token: str,
193
increment: int = None,
194
wrap_ttl: str = None
195
) -> dict:
196
"""
197
Renew specified token.
198
199
Args:
200
token: Token to renew
201
increment: Renewal increment in seconds
202
wrap_ttl: TTL for response wrapping
203
204
Returns:
205
Renewal response with new TTL
206
"""
207
```
208
209
### Policy Operations
210
211
HCL policy document retrieval and parsing.
212
213
```python { .api }
214
def get_policy(self, name: str, parse: bool = False) -> str | dict | None:
215
"""
216
Retrieve policy document by name.
217
218
Args:
219
name: Policy name
220
parse: Whether to parse HCL to dict (requires pyhcl)
221
222
Returns:
223
Policy document as HCL string, parsed dict, or None if not found
224
225
Raises:
226
ImportError: If parse=True but pyhcl not available
227
"""
228
```
229
230
### Client Properties
231
232
Configuration and status properties for runtime client management.
233
234
```python { .api }
235
@property
236
def adapter(self) -> Adapter:
237
"""HTTP adapter instance handling requests."""
238
239
@adapter.setter
240
def adapter(self, adapter: Adapter) -> None:
241
"""Set new adapter and update all API instances."""
242
243
@property
244
def url(self) -> str:
245
"""Vault server base URL."""
246
247
@url.setter
248
def url(self, url: str) -> None:
249
"""Update Vault server URL."""
250
251
@property
252
def token(self) -> str:
253
"""Current authentication token."""
254
255
@token.setter
256
def token(self, token: str) -> None:
257
"""Set authentication token."""
258
259
@property
260
def session(self) -> requests.Session:
261
"""Requests session object."""
262
263
@session.setter
264
def session(self, session: requests.Session) -> None:
265
"""Set custom requests session."""
266
267
@property
268
def allow_redirects(self) -> bool:
269
"""HTTP redirect following setting."""
270
271
@allow_redirects.setter
272
def allow_redirects(self, allow_redirects: bool) -> None:
273
"""Configure redirect following."""
274
275
# Status Properties (read-only)
276
@property
277
def seal_status(self) -> dict:
278
"""Vault seal status information."""
279
280
@property
281
def ha_status(self) -> dict:
282
"""High availability and leader status."""
283
284
@property
285
def key_status(self) -> dict:
286
"""Encryption key status information."""
287
288
@property
289
def rekey_status(self) -> dict:
290
"""Rekey operation progress."""
291
292
@property
293
def generate_root_status(self) -> dict:
294
"""Root token generation progress."""
295
```
296
297
## Usage Examples
298
299
### Basic Client Setup
300
301
```python
302
import hvac
303
304
# Basic setup with defaults
305
client = hvac.Client()
306
307
# Custom configuration
308
client = hvac.Client(
309
url='https://vault.company.com:8200',
310
verify='/path/to/ca.pem',
311
timeout=60,
312
namespace='production'
313
)
314
315
# Environment-based setup (recommended)
316
# VAULT_ADDR=https://vault.company.com:8200
317
# VAULT_TOKEN=s.xyz123
318
# VAULT_CACERT=/etc/vault/ca.pem
319
client = hvac.Client()
320
```
321
322
### Secret Operations
323
324
```python
325
# Write secret data
326
response = client.write_data(
327
'secret/myapp/config',
328
data={
329
'database_url': 'postgres://...',
330
'api_key': 'secret123'
331
}
332
)
333
334
# Read secret
335
secret = client.read('secret/myapp/config')
336
if secret:
337
data = secret['data']
338
print(f"Database URL: {data['database_url']}")
339
340
# List secrets in path
341
secrets = client.list('secret/myapp')
342
if secrets:
343
print(f"Available secrets: {secrets['data']['keys']}")
344
345
# Delete secret
346
client.delete('secret/myapp/config')
347
```
348
349
### Authentication Workflows
350
351
```python
352
# Check authentication status
353
if not client.is_authenticated():
354
print("Authentication required")
355
356
# Token lookup and validation
357
token_info = client.lookup_token()
358
print(f"Token TTL: {token_info['data']['ttl']}")
359
360
# Token renewal
361
renewal = client.renew_token(client.token, increment=3600)
362
print(f"New TTL: {renewal['auth']['lease_duration']}")
363
364
# Clean logout
365
client.logout(revoke_token=True)
366
```