怎么生成secret_id 和role_id 通过这篇文章可以找到:
Jenkins pipeline 怎么连接Vault_jenkinsfile withvault-CSDN博客
当你拥有了secret_id 和role_id,你就可以通过以下代码来进行连接:
bash
VaultLoginByApprole(){
role_id=$1
secret_id=$2
export VAULT_ADDR=your vault addr
export VAULT_NAMESPACE=your namesapce
export VAULT_TOKEN="$(vault write -ns '$ns' -field=token auth/approle/login role_id="$role_id" secret_id="$secret_id")"
}
Python实现
python
import subprocess
import os
def VaultLoginByApprole(role_id, secret_id):
# Set environment variables
os.environ['VAULT_ADDR'] = 'your vault addr'
os.environ['VAULT_NAMESPACE'] = 'your namespace'
# Run the vault write command and get the token
command = f"vault write -ns {os.environ['VAULT_NAMESPACE']} -field=token auth/approle/login role_id={role_id} secret_id={secret_id}"
output = subprocess.run(command.split(), capture_output=True, text=True)
token = output.stdout.strip()
# Set the VAULT_TOKEN environment variable
os.environ['VAULT_TOKEN'] = token
python
import os
import hvac
def VaultLoginByApprole(role_id, secret_id):
# Set environment variables
os.environ['VAULT_ADDR'] = 'your_vault_addr'
os.environ['VAULT_NAMESPACE'] = 'your_namespace'
# Create a Vault client
client = hvac.Client()
# Login using AppRole
response = client.auth_approle(role_id, secret_id)
# Extract the token from the response
token = response['auth']['client_token']
# Set the VAULT_TOKEN environment variable
os.environ['VAULT_TOKEN'] = token