Query using AWS Secrets Manager

Query your Amazon DocumentDB cluster using a Python app calling the AWS Secrets Manager API

Perform the following steps to query your Amazon DocumentDB cluster using a sample Python app which will access AWS Secrets Manager and retrieve a temporary access token.

(1) Open the AWS Cloud9 console created by Cloud Formation per the Prerequisites section of this Security Lab. Select Open IDE to open the AWS Cloud9 IDE. A terminal window is available at the bottom of the screen. Slide the window up to enlarge the terminal.
AWS SM 5

(To increase the terminal’s font size if necessary, select the gear icon in the upper right then select User Settings–>Terminal–>Font size).

(2) You will next unset any OS variables containing insecure credentials that may have been set in an earlier lab to ensure they are not used (the commands should return silently):

unset password
unset username
unset clusterendpoint
env | egrep -i 'password|username|clusterendpoint' 

(3) Enter the following command to copy the sample Python code containing the AWS Secrets Manager API call which will get your cluster’s userid, password, cluster endpoint, and port:

wget https://raw.githubusercontent.com/aws-samples/amazon-documentdb-samples/master/samples/connect-and-query/DocumentDB_Secrets_Mgr_sample.py

Review the sample code just downloaded:

cat DocumentDB_Secrets_Mgr_sample.py

Pay special attention to ensure secret name matches your secret name and region name matches your region. (Modify using an editor if your environment is different): AWS SM 10

Other code sections specific to AWS Secrets Manager integration to review are the return json.loads(secret) and the populating of the credentials variables: AWS SM 20

The Amazon DocumentDB code section creates a connection to your Amazon DocumentDB cluster, performs an insert operation to write few documents to Amazon DocumentDB, finds a document using one of the attributes in JSON and then updates the value of this document.

Run the sample Python code which will connect to your Amazon DocumentDB cluster using your cluster’s credentials that are securely stored in AWS Secrets Manager.

python3 DocumentDB_Secrets_Mgr_sample.py 

AWS SM 30

Congratulations! You used AWS Secrets Manager to securely connect to your Amazon DocumentDB cluster from a Python client.