How to store a key in AWS Secrets Manager instead of ‘.env’

Henry Coder
hellocode
Published in
3 min readNov 15, 2023

Navigate to AWS Secrets Manager

On the Secrets Manager dashboard, click on the “Store a new secret” button.

For a single key or API key, choose “Other type of secrets”, then enter key-value pairs:

Enter a name for your secret, for example: openaiapikey01. The name is used to reference the secret in your code or other AWS services.

We can call the secret by the following code:


import openai
from openai import OpenAI
import boto3 #pip3 install boto3
import json
import os
from dotenv import load_dotenv
load_dotenv()


def get_secret():
secret_name = "openaiapikey01"
region_name = "us-west-2"

try:
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)

get_secret_value_response = client.get_secret_value(SecretId=secret_name)
return json.loads(get_secret_value_response['SecretString'])
except Exception as e:
print(f"Error fetching secret: {e}")
# Fallback to local .env or environment variables
return {
"OPENAI_API_KEY": os.environ.get("OPENAI_API_KEY"),
# Add other secrets as needed
}

secrets = get_secret()

openai.api_key = secrets['OPENAI_API_KEY']

The beauty of the above code is that it can be compatible with both local and AWS: it will get the key from AWS Secrets Manger first, but if it goes wrong, it will get the key from “.env” file.

On your EC2 instance, the application will use the attached IAM role to access the Secrets Manager and fetch the required secrets.

--

--