AWS ‐ Secret Manager In Program - FullstackCodingGuy/Developer-Fundamentals GitHub Wiki

✅ Using AWS Secrets Manager for Redis Password in AWS Lambda

To securely store and retrieve your Redis password using AWS Secrets Manager, follow these steps:


1️⃣ Store Redis Password in AWS Secrets Manager

  1. Go to AWS Console → Secrets Manager
  2. Click "Store a new secret"
  3. Select "Other type of secret"
  4. Add the Redis credentials in Key-Value format:
    redis_password = my_secure_password
    
  5. Click Next, name the secret:
    redis/credentials
    
  6. Click Store.

2️⃣ Grant Lambda Access to AWS Secrets Manager

Your Lambda function needs permission to retrieve the secret.
Update your IAM Role with this policy:

{
  "Effect": "Allow",
  "Action": "secretsmanager:GetSecretValue",
  "Resource": "arn:aws:secretsmanager:YOUR_REGION:YOUR_ACCOUNT_ID:secret:redis/credentials-*"
}

3️⃣ Update Lambda to Retrieve the Redis Password

Modify your Redis connection code to fetch the password from Secrets Manager.

Install AWS SDK in Lambda

npm install @aws-sdk/client-secrets-manager

Update Code to Fetch Redis Password

const { SecretsManagerClient, GetSecretValueCommand } = require("@aws-sdk/client-secrets-manager");
const redis = require("redis");

// AWS Secrets Manager client
const secretsClient = new SecretsManagerClient({ region: "us-east-1" });

const getRedisPassword = async () => {
  try {
    const secret = await secretsClient.send(new GetSecretValueCommand({ SecretId: "redis/credentials" }));
    const secretValue = JSON.parse(secret.SecretString);
    return secretValue.redis_password; // Retrieve the password
  } catch (err) {
    console.error("Error fetching Redis secret:", err);
    throw err;
  }
};

const connectRedis = async () => {
  const redisPassword = await getRedisPassword(); // Fetch password from Secrets Manager

  const client = redis.createClient({
    socket: {
      host: process.env.REDIS_HOST || "my-cluster.abc123.ng.0001.use1.cache.amazonaws.com",
      port: process.env.REDIS_PORT || 6379
    },
    password: redisPassword // Use the fetched password
  });

  client.on("error", (err) => console.error("Redis Error:", err));

  await client.connect();
  console.log("✅ Connected to Redis with AWS Secrets Manager");
};

module.exports = connectRedis;

4️⃣ Deploy Lambda with AWS SAM

In template.yaml, add environment variables:

Environment:
  Variables:
    REDIS_HOST: "my-cluster.abc123.ng.0001.use1.cache.amazonaws.com"
    REDIS_PORT: "6379"
    AWS_REGION: "us-east-1"

Then deploy:

sam build && sam deploy --guided

🚀 Final Steps

✅ Store Redis password securely in AWS Secrets Manager
IAM Role allows Lambda to fetch secrets
✅ Lambda dynamically fetches the password at runtime
✅ Redis connection is now secure and encrypted

Now, restart your Lambda function, and it should connect securely! 🔥