Typing Stubs for hvac
types-hvac provides static type annotations for the `hvac` library, the official Python client for HashiCorp Vault. It enables type checkers like MyPy and Pyright to analyze code using `hvac` for type correctness. The package version 2.4.0.20260408 offers accurate annotations for `hvac==2.4.*` and is part of the actively maintained typeshed project.
Warnings
- gotcha types-hvac is purely for static type checking. Installing it does not provide any runtime functionality; it only supplies type definitions for the `hvac` library. You must install `hvac` separately to use the client.
- gotcha The version of `types-hvac` aims to be compatible with specific major/minor versions of the `hvac` library (e.g., `types-hvac==2.4.0.*` for `hvac==2.4.*`). Using mismatched versions can lead to inaccurate or failing type checks, especially if the `hvac` API changes.
- breaking While `types-hvac` itself doesn't introduce runtime breaking changes, future major versions of `hvac` (e.g., `hvac==3.0.0`) are slated to include breaking changes, such as modifying the `certificate` parameter for `create_ca_certificate_role` and changing the default for `raise_on_deleted_version`.
Install
-
pip install hvac types-hvac
Imports
- Client
from hvac import Client
- VaultError
from hvac.exceptions import VaultError
Quickstart
import os
from hvac import Client
from hvac.exceptions import VaultError
# Ensure VAULT_ADDR and VAULT_TOKEN environment variables are set
# For example: export VAULT_ADDR='http://127.0.0.1:8200' VAULT_TOKEN='your_root_token'
client: Client | None = None
try:
vault_addr = os.environ.get('VAULT_ADDR', 'http://127.0.0.1:8200')
vault_token = os.environ.get('VAULT_TOKEN', 'your_vault_token')
client = Client(url=vault_addr, token=vault_token)
if client.is_authenticated():
print('Successfully authenticated to Vault.')
# Example: Write a secret
path = 'secret/data/my-application/config'
secret_data = {'username': 'testuser', 'password': 'testpassword'}
client.secrets.kv.v2.create_or_update_secret(path=path, secret=secret_data)
print(f'Secret written to {path}')
# Example: Read a secret
read_response = client.secrets.kv.v2.read_secret_version(path=path)
if read_response and 'data' in read_response and 'data' in read_response['data']:
print(f"Retrieved username: {read_response['data']['data']['username']}")
else:
print('Secret not found or invalid format.')
else:
print('Failed to authenticate to Vault.')
except VaultError as e:
print(f'Vault operation failed: {e}')
except Exception as e:
print(f'An unexpected error occurred: {e}')
finally:
if client:
# Ensure to close the client session if it manages connections
# In hvac, the underlying requests session is usually managed implicitly or can be closed if explicitly created
# For persistent clients, manual session closing might not be strictly necessary, but good practice for short-lived scripts.
pass
# To verify type checking, run a type checker (e.g., mypy, pyright) on this file.