We are encrypting our environment variable "dbPassword" in AWS lambda function and we are trying to decrypt that encrypted value in our typescript file.
import * as AWS from 'aws-sdk';
const kmsClient = new AWS.KMS({region: 'us-east-1'});
class EncryptionUtility
{
static async decryptEnvironmentVariable(encryptedValue: string): string {
try
{
console.log("function decryptEnvironmentVariable() input value => ",encryptedValue);
const req = {
CiphertextBlob: Buffer.from(encryptedValue, 'base64'),
EncryptionContext: { LambdaFunctionName: 'ioh_reference_data_service' },
};
const decryptResult = await kmsClient.decrypt(req).promise();
if (Buffer.isBuffer(decryptResult.Plaintext)) {
return Buffer.from(decryptResult.Plaintext).toString();
}
else
{
throw new Error('We have a problem');
}
}
catch(e)
{
console.log("Exception Generated while executing decryptEnvironmentVariable() => ",e);
}
}
}
export abstract class Config {
static dbPassword: string = await EncryptionUtility.decryptEnvironmentVariable(process.env.dbPassword);
}
In above code, I want my dbPassword static variable of Config class should have decrypted value.
When I am printing Config.dbPassword in console I am getting undefined.
Also, I am getting error that await cannot be used in abstract class.
Config class is being used at many other places, and I want to have decrypted value in me Config class itself so that other places will be intact.
Can you please provide me the solution like how can I achieve this decrypted value in my Config static variables?
Anyone leads would be appreciated!
The issue you're facing is that you can't use await in the class field initialization, especially in a static context. Instead, you can set dbPassword in a separate static method or during the Lambda initialization.
You need to do something similar to this:
However, instead of using encrypted environment variables, why not use ParameterStore. It would simplify things greatly.