简体   繁体   中英

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!

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 ket-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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM