Yes, you can fetch database credentials from AWS Secrets Manager to establish the database connection in your application deployed on AWS EC2. Here’s a step-by-step guide to achieve this:
Steps to Fetch Database Credentials from AWS Secrets Manager
- Create a Secret in AWS Secrets Manager:
- Go to the AWS Secrets Manager console.
- Create a new secret and store your database credentials (username, password, host, etc.).
- Save the secret and note the secret ID.
- Grant Necessary Permissions:
- Ensure your EC2 instance has the necessary IAM permissions to access the secret.
- Attach a policy to your EC2 instance's IAM role that allows access to the specific secret.
- Retrieve the Secret in Your Application:
- Use the AWS SDK or CLI to retrieve the secret in your application.
- Here’s an example using Python with the boto3 library:
python
import boto3
import json
# Initialize a Secrets Manager client
session = boto3.session.Session()
client = session.client(service_name='secretsmanager', region_name='your-region')
# Retrieve the secret value
secret_name = "your-secret-id"
get_secret_value_response = client.get_secret_value(SecretId=secret_name)
# Parse the secret value
secret = json.loads(get_secret_value_response['SecretString'])
db_host = secret['db_host']
db_user = secret['db_user']
db_password = secret['db_password']
# Now you can use these credentials to establish the database connection
- Update Your Application Configuration:
- Remove the database credentials from your configuration file.
- Use the retrieved credentials to establish the database connection dynamically.
Example Configuration Update
If you're using a framework like Flask, you can update your configuration as follows:
python
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://{db_user}:{db_password}@{db_host}/your-database'