'Running CDK API Locally - Lambda function doesn't work locally

I'm working on a TypeScript CDK project that is in the early stages of development. We have laid out the basic infrastructure that includes an API Gateway, Lambda, RDS and Elasticache. We're storing environment variables using Secrets Manager.

We have a basic nodejs Lambda function that makes an external API call to one of our providers and it works fine live on AWS; it correctly pulls in two secrets, one for a URL and another for an API key. However, when running this locally, the secrets don't resolve and axois returns Error: connect ECONNREFUSED 127.0.0.1:80. Logging out process.env shows that AWS_ACCOUNT_ID seems to be using a placeholder value of 123456789012 as you can see below:

    "AWS_ACCOUNT_ID": "123456789012",
    "apiKey": "{{resolve:secretsmanager:arn:aws:secretsmanager:us-west-1:123456789012:secret:REDACTED:SecretString:::}}",

What I have tried:

  • I start the API locally using sam local start-api -t ./cdk.out/REDACTED/redactedAPI36455199.template.json --profile default --debug --warm-containers EAGER
    • We don't have a generic template.json file like others seem to have after running npx cdk synth and I believe this is due to the way we have structured ours stacks.
  • My aws credentials in aws configure are correct and have the correct permissions
    • I can return the secret using aws secretsmanager get-secret-value

This is becoming a huge issue as we can not truly develop and test locally. I'm afraid we won't be able to access RDS or Elasticache either once we get to that point.



Solution 1:[1]

Locally, your Lambda has no access to cloud-side env vars. You must explicitly provide local environment variable values to SAM with the --env-vars env.json flag.

// env.json
{
  "Parameters": {
    "API_KEY" : "<hardcode-key-here>"
  }
}

If a Lambda has RDS or Elasticache env vars, those values will also need to be hardcoded in env.json for local Lambda testing. Your Lambda can then make outbound calls to those deployed resources.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fedonev