My friend got a branded watch as a gift few days back, he went straight to his bank and kept it in the locker! we asked him don’t you trust us, friend? He said i believe in Zero Trust Policy. Likewise you should also keep your api keys, database and application credentials safe and secure in AWS Secret manager and not hardcode it into your code. This is a really good practice for your compliance and audit requirements.
Secret Manager
It allows you to store and retrieve your api keys, database or applications credentials easily and safely, instead of hardcoding the credentials in your source code or a .env file. Imagine this as a bank locker to store your precious things, like my friend did… 🙂
You can use the aws managed kms key aws/secretsmanager to encrypt these secrets or bring your own key using customer managed kms key, if you don’t want to store it in plain text. Go to AWS secrets manager → store new secret → key (Name - Identifier) and value (Credential) and in your code.
Here’s a sample python code to do the same, before running it please ensure the instance from where you are running this has secret manger get_secret_value permission.
def getApiToken():
secret_name = "app_name"
region_name = "ap-south-1"
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
secret = get_secret_value_response['SecretString']
secret_dict = json.loads(secret)
api_token = secret_dict.get('api_token')
return api_token
except Exception as e:
raise e
Here we get the api token stored in the secret manager. For Python import boto3, to make the secret manager get_secret_value api call. You just need to call this function once when application restarts and store in-memory to use it further.
Additional Features
You can also rotate secrets automatically, using aws lambda.
Replicate the secret to another aws region (like hyderabad) for disaster recovery.
Monitor if any change is made by integrating aws eventbridge and cloudtrail.
Monitor how many api calls are made to your secret manager using aws cloudwatch.