Created
September 30, 2024 14:23
-
-
Save thatbeautifuldream/6c75d066313ef13ecc1d339b00dba2ac to your computer and use it in GitHub Desktop.
AWS Secrets Manager Integration with Node.js: Fetch and Store Secrets in .env File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { | |
| SecretsManagerClient, | |
| GetSecretValueCommand, | |
| } from "@aws-sdk/client-secrets-manager"; | |
| import fs from "fs"; | |
| // Initialize AWS Secrets Manager client | |
| const client = new SecretsManagerClient({ | |
| region: "your-region-here", // Replace with your AWS region | |
| }); | |
| // Function to fetch secret value from AWS Secrets Manager | |
| const getSecretValue = async (secretName) => { | |
| try { | |
| const response = await client.send( | |
| new GetSecretValueCommand({ | |
| SecretId: secretName, // Replace with your secret name | |
| VersionStage: "AWSCURRENT", // Uses the current version of the secret by default | |
| }) | |
| ); | |
| if (response.SecretString) { | |
| return JSON.parse(response.SecretString); // Parse and return the secret as JSON | |
| } | |
| throw new Error("Secret is not a string"); | |
| } catch (err) { | |
| console.error("Error fetching secret:", err); | |
| throw err; | |
| } | |
| }; | |
| // Function to write the fetched secrets into a .env file | |
| const writeEnvFile = (secrets) => { | |
| const envContent = Object.entries(secrets) | |
| .map(([key, value]) => `${key}=${value}`) | |
| .join("\n"); | |
| // Write the secrets to a .env file | |
| fs.writeFileSync(".env", envContent, "utf8"); | |
| console.log(".env file created/updated"); | |
| }; | |
| (async () => { | |
| try { | |
| const secrets = await getSecretValue("your-secret-name-here"); // Replace with your secret name | |
| // Set secrets as environment variables in the process | |
| Object.entries(secrets).forEach(([key, value]) => { | |
| process.env[key] = value; | |
| }); | |
| // Write secrets to the .env file | |
| writeEnvFile(secrets); | |
| console.log("Secrets loaded:", Object.keys(secrets)); // Logs the keys of the loaded secrets | |
| } catch (err) { | |
| console.error("Error loading secrets:", err); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment