get secrets from enterprise vault using python

Viewed 5554

I am trying to get secrets(user id/password) from enterprise vault. When manually I try to read user id and password, I log in to vault by okta and then I select a namespace and inside that, I can get the secrets by going into the proper path.

I want to do that programmatically but I am not understanding from where to start. I found some packages "HVAC" which is useful for vault login.

Can anyone here post the way to login into the vault and then fetching secrets from the vault? Consider the application that will be running on the AWS ec2 machine. The application has access to AWS sts service and AWS Cognito.

I am using the below code and running it from ec2 instance:

import logging
import requests
from requests.exceptions import RequestException
import hvac
logger = logging.getLogger(__name__)
EC2_METADATA_URL_BASE = 'http://169.254.169.254'
def load_aws_ec2_role_iam_credentials(role_name, metadata_url_base=EC2_METADATA_URL_BASE):
    
    metadata_pkcs7_url = '{base}/latest/meta-data/iam/security-credentials/{role}'.format(
        base=metadata_url_base,
        role=role_name,
    )
    logger.debug("load_aws_ec2_role_iam_credentials connecting to %s" % metadata_pkcs7_url)
    response = requests.get(url=metadata_pkcs7_url)
    response.raise_for_status()
    security_credentials = response.json()
    return security_credentials
credentials = load_aws_ec2_role_iam_credentials('my_ec2_role')

a = credentials['AccessKeyId']
b = credentials['SecretAccessKey']
c = credentials['Token']
client = hvac.Client(
        url='http://vault.mycompany.net/ui/vault/secrets?namespace=namespace1',
        token = c
        )
print(client.is_authenticated())

list_response = client.secrets.kv.v2.list_secrets(
        path='path'
)
print(list_response['data'])

I am getting response "true" and then this error getting this error:

Traceback (most recent call last):
  File "3.py", line 44, in <module>
    print(list_response['data'])
TypeError: 'Response' object is not subscriptable

.Can anyone tell me what wrong I am doing?what will be the url if in my enterprise vault there is namespace called "namespace1"

0 Answers
Related