Vault from entry to proficiency series four: use python code to connect to the Vault server, store passwords, and read passwords

Vault from entry to proficiency series four: use python code to connect to the Vault server, store passwords, and read passwords

1. Create a Vault client

Initialize a new Vault client that will use token-based authentication for all its requests:

import hvac
import sys



client = hvac.Client(
    url='http://127.0.0.1:8200',
    token='hvs.BvXow4DjJ8VntB57DjQnd2hY',
)

2. Store password

Secrets are sensitive data such as API keys and passwords that we should not store in our code or configuration files. Instead, we want to store such values ​​in Vault.

We'll use the Vault client we just initialized to write the password to Vault as follows:


create_response = client.secrets.kv.v2.create_or_update_secret(
    path='my-secret-password',
    secret=dict(password='Hashi123'),
)

print('Secret written successfully.')

3. Write the complete code of the password

import hvac
import sys

client = hvac.Client(
    url='http://127.0.0.1:8200',
    token='hvs.BvXow4DjJ8VntB57DjQnd2hY',
)

create_response = client.secrets.kv.v2.create_or_update_secret(
    path='my-secret-password',
    secret=dict(password='Hashi123'),
)

print('Secret written successfully.')

Fourth, the command line to view the password

After executing the code, view the password on the command line

Start a new terminal, use the root token

export VAULT_ADDR='http://127.0.0.1:8200'
export VAULT_TOKEN="hvs.BvXow4DjJ8VntB57DjQnd2hY"

View my-secret-password password

vault kv get -mount=secret my-secret-password
========= Secret Path =========
secret/data/my-secret-password

======= Metadata =======
Key                Value
---                -----
created_time       2023-06-19T06:38:47.440087Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            1

====== Data ======
Key         Value
---         -----
password    Hashi123

5. Use the code to view the password

read_response = client.secrets.kv.read_secret_version(path='my-secret-password')

password = read_response['data']['data']['password']
print(password)

if password != 'Hashi123':
    sys.exit('unexpected password')

print('Access granted!')

Execute the code, the output is as follows:

Hashi123
Access granted!

Guess you like

Origin blog.csdn.net/zhengzaifeidelushang/article/details/131287833