hashicorp-vault

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

HashiCorp Vault

HashiCorp Vault

Centrally manage secrets, encryption, and access with HashiCorp Vault.
通过HashiCorp Vault集中管理密钥、加密与访问权限。

When to Use This Skill

使用场景

Use this skill when:
  • Centralizing secrets management
  • Implementing dynamic credentials
  • Managing PKI and certificates
  • Encrypting sensitive data
  • Meeting compliance requirements
在以下场景中使用本技能:
  • 集中化密钥管理
  • 实现动态凭证
  • 管理PKI与证书
  • 加密敏感数据
  • 满足合规要求

Prerequisites

前置条件

  • Vault server (dev or production)
  • Vault CLI installed
  • Network access to Vault
  • Vault服务器(开发或生产环境)
  • 已安装Vault CLI
  • 可网络访问Vault

Quick Start

快速开始

Development Server

开发服务器

bash
undefined
bash
undefined

Start dev server

Start dev server

vault server -dev
vault server -dev

Set environment

Set environment

export VAULT_ADDR='http://127.0.0.1:8200' export VAULT_TOKEN='root'
export VAULT_ADDR='http://127.0.0.1:8200' export VAULT_TOKEN='root'

Verify connection

Verify connection

vault status
undefined
vault status
undefined

Production Deployment

生产部署

hcl
undefined
hcl
undefined

config.hcl

config.hcl

storage "raft" { path = "/opt/vault/data" node_id = "vault-1" }
listener "tcp" { address = "0.0.0.0:8200" tls_cert_file = "/opt/vault/tls/vault.crt" tls_key_file = "/opt/vault/tls/vault.key" }
ui = true

```bash
storage "raft" { path = "/opt/vault/data" node_id = "vault-1" }
listener "tcp" { address = "0.0.0.0:8200" tls_cert_file = "/opt/vault/tls/vault.crt" tls_key_file = "/opt/vault/tls/vault.key" }
ui = true

```bash

Initialize Vault

Initialize Vault

vault operator init -key-shares=5 -key-threshold=3
vault operator init -key-shares=5 -key-threshold=3

Unseal (run 3 times with different keys)

Unseal (run 3 times with different keys)

vault operator unseal <key-1> vault operator unseal <key-2> vault operator unseal <key-3>
vault operator unseal <key-1> vault operator unseal <key-2> vault operator unseal <key-3>

Login

Login

vault login <root-token>
undefined
vault login <root-token>
undefined

Secret Engines

密钥引擎

KV Secrets

KV密钥

bash
undefined
bash
undefined

Enable KV v2

Enable KV v2

vault secrets enable -path=secret kv-v2
vault secrets enable -path=secret kv-v2

Write secret

Write secret

vault kv put secret/myapp/config
username="admin"
password="s3cr3t"
vault kv put secret/myapp/config
username="admin"
password="s3cr3t"

Read secret

Read secret

vault kv get secret/myapp/config vault kv get -field=password secret/myapp/config
vault kv get secret/myapp/config vault kv get -field=password secret/myapp/config

Update secret

Update secret

vault kv put secret/myapp/config
username="admin"
password="new-password"
vault kv put secret/myapp/config
username="admin"
password="new-password"

List secrets

List secrets

vault kv list secret/
vault kv list secret/

Delete secret

Delete secret

vault kv delete secret/myapp/config
vault kv delete secret/myapp/config

Version history

Version history

vault kv metadata get secret/myapp/config
undefined
vault kv metadata get secret/myapp/config
undefined

Database Secrets

数据库密钥

bash
undefined
bash
undefined

Enable database engine

Enable database engine

vault secrets enable database
vault secrets enable database

Configure PostgreSQL connection

Configure PostgreSQL connection

vault write database/config/postgresql
plugin_name=postgresql-database-plugin
connection_url="postgresql://{{username}}:{{password}}@localhost:5432/mydb"
allowed_roles="readonly,readwrite"
username="vault"
password="vault-password"
vault write database/config/postgresql
plugin_name=postgresql-database-plugin
connection_url="postgresql://{{username}}:{{password}}@localhost:5432/mydb"
allowed_roles="readonly,readwrite"
username="vault"
password="vault-password"

Create role

Create role

vault write database/roles/readonly
db_name=postgresql
creation_statements="CREATE ROLE "{{name}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";"
default_ttl="1h"
max_ttl="24h"
vault write database/roles/readonly
db_name=postgresql
creation_statements="CREATE ROLE "{{name}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";"
default_ttl="1h"
max_ttl="24h"

Get credentials

Get credentials

vault read database/creds/readonly
undefined
vault read database/creds/readonly
undefined

AWS Secrets

AWS密钥

bash
undefined
bash
undefined

Enable AWS engine

Enable AWS engine

vault secrets enable aws
vault secrets enable aws

Configure root credentials

Configure root credentials

vault write aws/config/root
access_key=AKIA...
secret_key=secret...
region=us-east-1
vault write aws/config/root
access_key=AKIA...
secret_key=secret...
region=us-east-1

Create role

Create role

vault write aws/roles/deploy
credential_type=iam_user
policy_document=-<<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:"], "Resource": ["arn:aws:s3:::my-bucket/"] } ] } EOF
vault write aws/roles/deploy
credential_type=iam_user
policy_document=-<<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:"], "Resource": ["arn:aws:s3:::my-bucket/"] } ] } EOF

Get credentials

Get credentials

vault read aws/creds/deploy
undefined
vault read aws/creds/deploy
undefined

PKI Secrets

PKI密钥

bash
undefined
bash
undefined

Enable PKI engine

Enable PKI engine

vault secrets enable pki vault secrets tune -max-lease-ttl=87600h pki
vault secrets enable pki vault secrets tune -max-lease-ttl=87600h pki

Generate root CA

Generate root CA

vault write -field=certificate pki/root/generate/internal
common_name="example.com"
ttl=87600h > ca_cert.crt
vault write -field=certificate pki/root/generate/internal
common_name="example.com"
ttl=87600h > ca_cert.crt

Configure URLs

Configure URLs

vault write pki/config/urls
issuing_certificates="https://vault.example.com:8200/v1/pki/ca"
crl_distribution_points="https://vault.example.com:8200/v1/pki/crl"
vault write pki/config/urls
issuing_certificates="https://vault.example.com:8200/v1/pki/ca"
crl_distribution_points="https://vault.example.com:8200/v1/pki/crl"

Create role

Create role

vault write pki/roles/web-server
allowed_domains="example.com"
allow_subdomains=true
max_ttl="720h"
vault write pki/roles/web-server
allowed_domains="example.com"
allow_subdomains=true
max_ttl="720h"

Issue certificate

Issue certificate

vault write pki/issue/web-server
common_name="web.example.com"
ttl="24h"
undefined
vault write pki/issue/web-server
common_name="web.example.com"
ttl="24h"
undefined

Authentication Methods

认证方式

AppRole

AppRole

bash
undefined
bash
undefined

Enable AppRole

Enable AppRole

vault auth enable approle
vault auth enable approle

Create role

Create role

vault write auth/approle/role/myapp
token_policies="myapp-policy"
token_ttl=1h
token_max_ttl=4h
secret_id_ttl=10m
vault write auth/approle/role/myapp
token_policies="myapp-policy"
token_ttl=1h
token_max_ttl=4h
secret_id_ttl=10m

Get role ID

Get role ID

vault read auth/approle/role/myapp/role-id
vault read auth/approle/role/myapp/role-id

Generate secret ID

Generate secret ID

vault write -f auth/approle/role/myapp/secret-id
vault write -f auth/approle/role/myapp/secret-id

Login

Login

vault write auth/approle/login
role_id=<role-id>
secret_id=<secret-id>
undefined
vault write auth/approle/login
role_id=<role-id>
secret_id=<secret-id>
undefined

Kubernetes

Kubernetes

bash
undefined
bash
undefined

Enable Kubernetes auth

Enable Kubernetes auth

vault auth enable kubernetes
vault auth enable kubernetes

Configure

Configure

vault write auth/kubernetes/config
kubernetes_host="https://kubernetes.default.svc"
kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
vault write auth/kubernetes/config
kubernetes_host="https://kubernetes.default.svc"
kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt

Create role

Create role

vault write auth/kubernetes/role/myapp
bound_service_account_names=myapp
bound_service_account_namespaces=default
policies=myapp-policy
ttl=1h
undefined
vault write auth/kubernetes/role/myapp
bound_service_account_names=myapp
bound_service_account_namespaces=default
policies=myapp-policy
ttl=1h
undefined

OIDC

OIDC

bash
undefined
bash
undefined

Enable OIDC auth

Enable OIDC auth

vault auth enable oidc
vault auth enable oidc

Configure

Configure

vault write auth/oidc/config
oidc_discovery_url="https://accounts.google.com"
oidc_client_id="your-client-id"
oidc_client_secret="your-client-secret"
default_role="default"
vault write auth/oidc/config
oidc_discovery_url="https://accounts.google.com"
oidc_client_id="your-client-id"
oidc_client_secret="your-client-secret"
default_role="default"

Create role

Create role

vault write auth/oidc/role/default
bound_audiences="your-client-id"
allowed_redirect_uris="http://localhost:8250/oidc/callback"
user_claim="sub"
policies="default"
undefined
vault write auth/oidc/role/default
bound_audiences="your-client-id"
allowed_redirect_uris="http://localhost:8250/oidc/callback"
user_claim="sub"
policies="default"
undefined

Policies

策略

Policy Definition

策略定义

hcl
undefined
hcl
undefined

myapp-policy.hcl

myapp-policy.hcl

Read secrets

Read secrets

path "secret/data/myapp/*" { capabilities = ["read", "list"] }
path "secret/data/myapp/*" { capabilities = ["read", "list"] }

Database credentials

Database credentials

path "database/creds/myapp-db" { capabilities = ["read"] }
path "database/creds/myapp-db" { capabilities = ["read"] }

PKI certificates

PKI certificates

path "pki/issue/web-server" { capabilities = ["create", "update"] }
path "pki/issue/web-server" { capabilities = ["create", "update"] }

Deny access to other secrets

Deny access to other secrets

path "secret/data/other/*" { capabilities = ["deny"] }

```bash
path "secret/data/other/*" { capabilities = ["deny"] }

```bash

Create policy

Create policy

vault policy write myapp myapp-policy.hcl
vault policy write myapp myapp-policy.hcl

List policies

List policies

vault policy list
vault policy list

Read policy

Read policy

vault policy read myapp
undefined
vault policy read myapp
undefined

Application Integration

应用集成

Python

Python

python
import hvac
python
import hvac

Initialize client

Initialize client

client = hvac.Client(url='http://localhost:8200')
client = hvac.Client(url='http://localhost:8200')

AppRole authentication

AppRole authentication

client.auth.approle.login( role_id='role-id', secret_id='secret-id' )
client.auth.approle.login( role_id='role-id', secret_id='secret-id' )

Read secret

Read secret

secret = client.secrets.kv.v2.read_secret_version( path='myapp/config', mount_point='secret' ) password = secret['data']['data']['password']
secret = client.secrets.kv.v2.read_secret_version( path='myapp/config', mount_point='secret' ) password = secret['data']['data']['password']

Get database credentials

Get database credentials

db_creds = client.secrets.database.generate_credentials( name='myapp-db' )
undefined
db_creds = client.secrets.database.generate_credentials( name='myapp-db' )
undefined

Kubernetes Sidecar

Kubernetes Sidecar

yaml
apiVersion: v1
kind: Pod
metadata:
  name: myapp
  annotations:
    vault.hashicorp.com/agent-inject: "true"
    vault.hashicorp.com/role: "myapp"
    vault.hashicorp.com/agent-inject-secret-config: "secret/data/myapp/config"
    vault.hashicorp.com/agent-inject-template-config: |
      {{- with secret "secret/data/myapp/config" -}}
      export DB_PASSWORD="{{ .Data.data.password }}"
      {{- end }}
spec:
  serviceAccountName: myapp
  containers:
    - name: myapp
      image: myapp:latest
      command: ["/bin/sh", "-c", "source /vault/secrets/config && ./start.sh"]
yaml
apiVersion: v1
kind: Pod
metadata:
  name: myapp
  annotations:
    vault.hashicorp.com/agent-inject: "true"
    vault.hashicorp.com/role: "myapp"
    vault.hashicorp.com/agent-inject-secret-config: "secret/data/myapp/config"
    vault.hashicorp.com/agent-inject-template-config: |
      {{- with secret "secret/data/myapp/config" -}}
      export DB_PASSWORD="{{ .Data.data.password }}"
      {{- end }}
spec:
  serviceAccountName: myapp
  containers:
    - name: myapp
      image: myapp:latest
      command: ["/bin/sh", "-c", "source /vault/secrets/config && ./start.sh"]

Common Issues

常见问题

Issue: Sealed Vault

问题:Vault处于密封状态

Problem: Vault is sealed after restart Solution: Implement auto-unseal with cloud KMS or HSM
现象:重启后Vault处于密封状态 解决方案:使用云KMS或HSM实现自动解封

Issue: Token Expired

问题:令牌过期

Problem: Application token has expired Solution: Implement token renewal, use shorter-lived tokens
现象:应用令牌已过期 解决方案:实现令牌续期,使用短生命周期令牌

Issue: Permission Denied

问题:权限拒绝

Problem: Cannot access secrets Solution: Review policies, check token capabilities
现象:无法访问密钥 解决方案:检查策略配置,验证令牌权限

Best Practices

最佳实践

  • Use short-lived tokens
  • Implement auto-unseal
  • Enable audit logging
  • Use namespaces for isolation
  • Rotate root tokens regularly
  • Implement least-privilege policies
  • Use dynamic secrets where possible
  • Regular backup and DR testing
  • 使用短生命周期令牌
  • 实现自动解封
  • 启用审计日志
  • 使用命名空间实现隔离
  • 定期轮换根令牌
  • 遵循最小权限原则配置策略
  • 尽可能使用动态密钥
  • 定期备份并进行灾难恢复测试

Related Skills

相关技能

  • aws-secrets-manager - AWS native secrets
  • sops-encryption - File encryption
  • kubernetes-hardening - K8s security
  • aws-secrets-manager - AWS原生密钥管理
  • sops-encryption - 文件加密
  • kubernetes-hardening - Kubernetes安全加固