Typing Stubs for hvac

2.4.0.20260408 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates basic `hvac` client initialization and secret interaction with type hints. It requires the `VAULT_ADDR` and `VAULT_TOKEN` environment variables to be set for successful authentication. The `types-hvac` package provides the type information for `Client` and other `hvac` objects, allowing static analysis tools to verify the code's type safety.

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.

view raw JSON →