Hashicorp Vault - Login to the vault using Python hvac and approle

by
Jeremy Canfield |
Updated: October 21 2024
| Hashicorp Vault articles
This assumes you are familiar with the Python hvac client. If not, check out my article Hashicorp Vault - Getting Started with Python hvac.
This assumes the following has already been done.
- Hashicorp Vault has been installed
- Hashicorp Vault has been initialized
- Hashicorp Vault has been unsealed
- approle authentication has been enabled
- an approle role has been created with a role ID and secret ID
For example, let's say a role named my-role was created and the role ID is b4a68549-1464-7aac-b0cd-d22954985aa8.
~]$ vault read auth/approle/role/my-role/role-id
Key Value
--- -----
role_id b4a68549-1464-7aac-b0cd-d22954985aa8
And the secret ID is 6039e2e2-6017-8db9-2e1b-dd6bd449f901.
~]$ vault write -f auth/approle/role/my-role/secret-id
Key Value
--- -----
secret_id 6039e2e2-6017-8db9-2e1b-dd6bd449f901
secret_id_accessor c8ef166e-4b09-0e1f-b70e-cb3a871a6460
secret_id_num_uses 40
secret_id_ttl 10m
Here is how you can login to the vault using Python hvac approle.
Check out my article Hashicorp Vault - Error Handling using Python hvac for details on how to include Error Handling.
#!/usr/bin/python3
import hvac
client = hvac.Client(url='http://vault.example.com:8200')
is_client_authenticated = client.is_authenticated()
print(f"is_client_authenticated before approle login= {is_client_authenticated}")
response = client.auth.approle.login(
role_id="b4a68549-1464-7aac-b0cd-d22954985aa8",
secret_id="6039e2e2-6017-8db9-2e1b-dd6bd449f901"
)
is_client_authenticated = client.is_authenticated()
print(f"is_client_authenticated after approle login = {is_client_authenticated}")
print(f"response = {response}")
If the authentication is successful, something like this should be returned.
s_client_authenticated before approle login= False
is_client_authenticated after approle login = True
{
'request_id': '2c4c96cd-9c89-c890-d268-07960de80fc3',
'lease_id': '',
'renewable': False,
'lease_duration': 0,
'data': None,
'wrap_info': None,
'warnings': None,
'auth': {
'client_token': 'hvs.CAESabdfQMC4tzU_WAKEMD1iTpQ3gqtgDfvMn123itUVGa8hGiMKHGh2cy5KQV23456djBRa3pnMmabRkJIVFJ0dfbdarKnFQ',
'accessor': 'IBj234FgmwEadfbx4ba0qwGY',
'policies': [
'default', 'my_policy'
],
'token_policies': [
'default', 'my_policy'
],
'metadata': {
'role_name': 'my_role'
},
'lease_duration': 7200,
'renewable': True,
'entity_id': '1esdf268-d112-a134-d271-8cc08adsbb03',
'token_type': 'service',
'orphan': True,
'mfa_requirement': None,
'num_uses': 0
},
'mount_type': ''
}
Did you find this article helpful?
If so, consider buying me a coffee over at