HVAC: HashiCorp Vault API Client

2.4.0 · active · verified Sun Mar 29

HVAC is a Python client library for interacting with HashiCorp Vault. It provides a programmatic interface to manage secrets, policies, and authentication methods within a Vault instance. Currently at version 2.4.0, the library maintains an active development status with regular minor releases addressing new Vault features, bug fixes, and dependency updates, alongside occasional major releases for significant breaking changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `hvac.Client`, authenticate using a token (read from an environment variable), and perform basic CRUD operations (create, read, delete) on a KV v2 secret engine. Ensure a Vault server is running and accessible at `VAULT_ADDR` with a valid `VAULT_TOKEN` for authentication. The KV v2 secret engine should be enabled at the `secret` mount point.

import os
import hvac

# Configure these environment variables or replace with direct values
VAULT_ADDR = os.environ.get('VAULT_ADDR', 'http://127.0.0.1:8200')
VAULT_TOKEN = os.environ.get('VAULT_TOKEN', 'root-token-for-dev')

try:
    client = hvac.Client(url=VAULT_ADDR, token=VAULT_TOKEN)

    if not client.is_authenticated():
        raise Exception("HVAC client not authenticated. Check VAULT_ADDR and VAULT_TOKEN.")

    print("Client authenticated successfully.")

    # Example: Write a secret to KV v2 engine
    mount_point = 'secret'
    path = 'my-app/config'
    secret_data = {'api_key': 'super-secret-key-123', 'environment': 'dev'}

    print(f"\nWriting secret to {mount_point}/{path}...")
    client.secrets.kv.v2.create_or_update_secret(
        mount_point=mount_point,
        path=path,
        secret=secret_data,
    )
    print("Secret written.")

    # Example: Read the secret from KV v2 engine
    print(f"\nReading secret from {mount_point}/{path}...")
    read_response = client.secrets.kv.v2.read_secret_version(
        mount_point=mount_point,
        path=path
    )

    retrieved_data = read_response['data']['data']
    print(f"Retrieved secret: {retrieved_data}")

    # Example: Delete the secret
    print(f"\nDeleting secret {mount_point}/{path}...")
    client.secrets.kv.v2.delete_metadata_and_all_versions(
        mount_point=mount_point,
        path=path
    )
    print("Secret deleted.")

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →