zacurry
zacurry

Reputation: 906

Serverless - How to access Aws secret manager as environment variable

Currently, I am accessing AWS parameter store value as environment variable. It is defined in serverless yml like so:

environment:
    XYZ_CREDS: ${ssm:xyzCreds}

In code, I access this like so process.env.XYZ_CREDS
I need to move this value to AWS secret manager and access the xyzCreds in the same way.
Based on the serverless document I tried like so -

  custom:
    xyzsecret: ${ssm:/aws/reference/secretsmanager/XYZ_CREDS_SECRET_MANAGERa~true} 
  environment:
    XYZ_CREDS: ${self:custom.xyzsecret}}

But it's not working. Please help!

Upvotes: 4

Views: 5025

Answers (4)

Robin Thomas
Robin Thomas

Reputation: 4116

I have created a serverless plugin since I faced the same issue. You check out the plugin here: https://github.com/robin-thomas/serverless-aws-secrets

You can have your environment variables that look like this:

MYSQL_USERNAME=secret:MYSQL_USERNAME
MYSQL_PASSWORD=secret:MYSQL_PASSWORD

The plugin will then load the secret from AWS Secrets Manager, and then replace values of MYSQL_USERNAME and MYSQL_PASSWORD.

So when you access process.env.MYSQL_USERNAME within your lambda, the secret is already available.

Upvotes: 1

Northern Captain
Northern Captain

Reputation: 1237

After struggling with this issue by myself, I found the solution that worked for me.

Assume that we have a secret XYZ_CREDS where we store user and password key-value pairs. AWS Secrets manager stores them in JSON format: {"user": "test", "password": "xxxx"}

Here is how to put user and password into Lambda function environment variables:

custom:
  xyzsecret: ${ssm:/aws/reference/secretsmanager/XYZ_CREDS~true}
myService:
  handler: index.handler
  environment:
    username: ${self:custom.xyzsecret.user}
    password: ${self:custom.xyzsecret.password}

I'm using Serverless 1.73.1 for deploying to CloudFormation.

Hope this helps others.

Upvotes: 7

Ezhil Arasan
Ezhil Arasan

Reputation: 478

Secret manager stores in key value/json format.So specify the variables individually

Eg.

   environment:
     user_name: ${self:custom.xyzsecret}.username
     password: ${self:custom.xyzsecret}.password 

otherwise pass secret manager name and decrypt using aws-sdk in the code

 environment:
     secretkey_name:XYZ_CREDS_SECRET_MANAGERa

Upvotes: 0

atreyHazelHispanic
atreyHazelHispanic

Reputation: 109

Given that the name of your secret in secrets manager is correct. I think you might have an "a" after manager before the decryption.

Upvotes: 1

Related Questions