2

I need to access environment variables I created in AWS Lambda from my Chalice Python code but I am unable to find examples that make sense.

Thoughts?

I am using Python 3.6.

Not a machine
  • 508
  • 1
  • 5
  • 21

1 Answers1

8

You just use the os environment variable access.

import os
print(os.environ["MY_VARIABLE"])

If your question is how to set the environment variables in Chalice. You set them in the Chalice config:

.chalice/config.json

{
  "version": "2.0",
  "app_name": "gtf",
  "stages": {
    "dev": {
      "environment_variables": {
          "MY_VARIABLE": "MY_VALUE"
      }
    }
  }
}

https://chalice.readthedocs.io/en/latest/topics/configfile.html

Michael Robellard
  • 2,268
  • 15
  • 25
  • It is the os environment variable of which I was unsure. IBM and Microsoft provide examples for their env handoff but I didn't see anything for AWS. I guess I should have presumed the use of standard OS environment variables. Thank you for clarifying! – Not a machine Dec 11 '19 at 19:15
  • I put a working example on GitHub of a Chalice REST service that uses this technique to set the name of the underlying DynamoDB table in an env variable and use it in the Lambda function. Here's a link: [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/blob/be0b2d488884a6dfa6be49c347d1988bb5d09e60/python/example_code/lambda/chalice_examples/lambda_rest/chalicelib/covid_data.py#L39). – Laren Crawford Aug 03 '20 at 21:57
  • In my case I need to save "aws_access_key_id" and "aws_secret_access_key" as environment variables. Obviously I cannot commit config.json Do you know the right way to load such sensitive values to config.json? (from .env file for example) – Honesta Feb 13 '23 at 14:14
  • You should not be using those in your config.json boto will automatically pull the credentials from the lambda environment when you need them, You lambda runs off the IAM settings for the Lambda not of your access id and key – Michael Robellard Feb 13 '23 at 17:51