CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-hvac

HashiCorp Vault API client for Python with comprehensive authentication, secrets management, and system administration capabilities

Pending
Overview
Eval results
Files

client.mddocs/

Core Client Operations

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.

Capabilities

Client Initialization

Create and configure Vault client instances with authentication, networking, and connection parameters.

class Client:
    def __init__(
        self,
        url: str = None,                    # Vault server URL (default: http://localhost:8200 or VAULT_ADDR)
        token: str = None,                  # Authentication token (or from VAULT_TOKEN env)
        cert: tuple = None,                 # Client certificate tuple (cert_path, key_path)
        verify: bool | str = None,          # TLS verification: True, False, or CA bundle path
        timeout: int = 30,                  # Request timeout in seconds
        proxies: dict = None,               # HTTP proxy configuration
        allow_redirects: bool = True,       # Follow HTTP redirects
        session: requests.Session = None,   # Custom requests session
        adapter: Adapter = None,            # HTTP adapter (default: JSONAdapter)
        namespace: str = None,              # Vault namespace for Enterprise
        **kwargs                            # Additional adapter arguments
    ):
        """
        Initialize Vault client with connection and authentication settings.
        
        Environment variables:
        - VAULT_ADDR: Default URL if url not provided
        - VAULT_TOKEN: Default token if token not provided  
        - VAULT_CACERT: CA certificate file path
        - VAULT_CAPATH: CA certificate directory path
        - VAULT_CLIENT_CERT: Client certificate file path
        - VAULT_CLIENT_KEY: Client private key file path
        """

Basic CRUD Operations

Core operations for reading, writing, listing, and deleting secrets and configuration data.

def read(self, path: str, wrap_ttl: str = None) -> dict | None:
    """
    Read data from specified Vault path.
    
    Args:
        path: Vault path to read from (without /v1/ prefix)
        wrap_ttl: TTL for response wrapping (e.g., "1h", "30m")
        
    Returns:
        Response dict with data, or None if path doesn't exist
        
    Raises:
        InvalidPath: Path not found (404)
        Forbidden: Insufficient permissions (403)
    """

def list(self, path: str) -> dict | None:
    """
    List secrets at specified path.
    
    Args:
        path: Vault path to list (without /v1/ prefix)
        
    Returns:
        Response dict with keys list, or None if path doesn't exist
    """

def write(self, *args, **kwargs) -> dict:
    """
    Write data to Vault path (legacy method with kwargs restrictions).
    
    Note: Deprecated parameter usage - use write_data() for unrestricted keys.
    """

def write_data(
    self, 
    path: str, 
    *, 
    data: dict = None, 
    wrap_ttl: str = None
) -> dict:
    """
    Write data to specified Vault path.
    
    Args:
        path: Vault path to write to (without /v1/ prefix)
        data: Data dictionary to write
        wrap_ttl: TTL for response wrapping
        
    Returns:
        Response dict from Vault
    """

def delete(self, path: str) -> None:
    """
    Delete data at specified path.
    
    Args:
        path: Vault path to delete (without /v1/ prefix)
    """

Authentication Management

Methods for managing authentication state and token operations.

def is_authenticated(self) -> bool:
    """
    Check if client is properly authenticated.
    
    Returns:
        True if authenticated, False otherwise
    """

def login(self, url: str, use_token: bool = True, **kwargs) -> dict:
    """
    Perform authentication request.
    
    Args:
        url: Authentication endpoint URL
        use_token: Whether to store returned token automatically
        **kwargs: Authentication parameters
        
    Returns:
        Authentication response
    """

def logout(self, revoke_token: bool = False) -> None:
    """
    Clear authentication and optionally revoke token.
    
    Args:
        revoke_token: Whether to revoke the token before clearing
    """

def auth_cubbyhole(self, token: str) -> dict:
    """
    Authenticate using wrapped token from cubbyhole.
    
    Args:
        token: Wrapped response token
        
    Returns:
        Unwrapped authentication response
    """

Token Operations

Direct token management methods for advanced token workflows.

def lookup_token(
    self, 
    token: str = None, 
    accessor: bool = False, 
    wrap_ttl: str = None
) -> dict:
    """
    Look up token information.
    
    Args:
        token: Token to look up (None for self lookup)
        accessor: Whether token parameter is an accessor
        wrap_ttl: TTL for response wrapping
        
    Returns:
        Token information
    """

def revoke_token(
    self, 
    token: str, 
    orphan: bool = False, 
    accessor: bool = False
) -> None:
    """
    Revoke specified token.
    
    Args:
        token: Token or accessor to revoke
        orphan: Revoke without revoking child tokens
        accessor: Whether token parameter is an accessor
    """

def renew_token(
    self, 
    token: str, 
    increment: int = None, 
    wrap_ttl: str = None
) -> dict:
    """
    Renew specified token.
    
    Args:
        token: Token to renew
        increment: Renewal increment in seconds
        wrap_ttl: TTL for response wrapping
        
    Returns:
        Renewal response with new TTL
    """

Policy Operations

HCL policy document retrieval and parsing.

def get_policy(self, name: str, parse: bool = False) -> str | dict | None:
    """
    Retrieve policy document by name.
    
    Args:
        name: Policy name
        parse: Whether to parse HCL to dict (requires pyhcl)
        
    Returns:
        Policy document as HCL string, parsed dict, or None if not found
        
    Raises:
        ImportError: If parse=True but pyhcl not available
    """

Client Properties

Configuration and status properties for runtime client management.

@property
def adapter(self) -> Adapter:
    """HTTP adapter instance handling requests."""

@adapter.setter  
def adapter(self, adapter: Adapter) -> None:
    """Set new adapter and update all API instances."""

@property
def url(self) -> str:
    """Vault server base URL."""

@url.setter
def url(self, url: str) -> None:
    """Update Vault server URL."""

@property
def token(self) -> str:
    """Current authentication token."""

@token.setter
def token(self, token: str) -> None:
    """Set authentication token."""

@property
def session(self) -> requests.Session:
    """Requests session object."""

@session.setter
def session(self, session: requests.Session) -> None:
    """Set custom requests session."""

@property
def allow_redirects(self) -> bool:
    """HTTP redirect following setting."""

@allow_redirects.setter
def allow_redirects(self, allow_redirects: bool) -> None:
    """Configure redirect following."""

# Status Properties (read-only)
@property
def seal_status(self) -> dict:
    """Vault seal status information."""

@property
def ha_status(self) -> dict:
    """High availability and leader status."""

@property
def key_status(self) -> dict:
    """Encryption key status information."""

@property
def rekey_status(self) -> dict:
    """Rekey operation progress."""

@property
def generate_root_status(self) -> dict:
    """Root token generation progress."""

Usage Examples

Basic Client Setup

import hvac

# Basic setup with defaults
client = hvac.Client()

# Custom configuration
client = hvac.Client(
    url='https://vault.company.com:8200',
    verify='/path/to/ca.pem',
    timeout=60,
    namespace='production'
)

# Environment-based setup (recommended)
# VAULT_ADDR=https://vault.company.com:8200
# VAULT_TOKEN=s.xyz123
# VAULT_CACERT=/etc/vault/ca.pem
client = hvac.Client()

Secret Operations

# Write secret data
response = client.write_data(
    'secret/myapp/config',
    data={
        'database_url': 'postgres://...',
        'api_key': 'secret123'
    }
)

# Read secret
secret = client.read('secret/myapp/config')
if secret:
    data = secret['data']
    print(f"Database URL: {data['database_url']}")

# List secrets in path
secrets = client.list('secret/myapp')
if secrets:
    print(f"Available secrets: {secrets['data']['keys']}")

# Delete secret
client.delete('secret/myapp/config')

Authentication Workflows

# Check authentication status
if not client.is_authenticated():
    print("Authentication required")

# Token lookup and validation
token_info = client.lookup_token()
print(f"Token TTL: {token_info['data']['ttl']}")

# Token renewal
renewal = client.renew_token(client.token, increment=3600)
print(f"New TTL: {renewal['auth']['lease_duration']}")

# Clean logout
client.logout(revoke_token=True)

Install with Tessl CLI

npx tessl i tessl/pypi-hvac

docs

auth-methods.md

client.md

index.md

secrets-engines.md

system-backend.md

tile.json