Environment variables 

A very useful feature of the AWS Lambda service is that you can specify your own environment variables to be set at the OS-level during each invocation. You can access these through your code.

This is a great way to parameterize certain variables that are likely to change throughout your code's life cycle, for example, the endpoint of a database.

This is also the perfect place for securing credentials so that they stay out of the code. Environment variables are encrypted automatically using the AWS Key Management Service (KMS). Using environment variables for credentials is one way to make sure they are secure, but maintaining these can get out of control quickly when you start deploying tens or hundreds of Lambda functions.

For larger deployments, it might make sense to manage credentials centrally. For this, a better strategy would be to use the Parameter Store in AWS Systems Manager or AWS Secrets Manager.

Let's dig into an example of setting up and accessing an environment variable. In the configuration screen for an existing function, there is a section called Environment variables:

Lambda function configuration options for adding environment variables

I've added some examples and clicked Save. Let's learn how to access and print these in code:

  • Using Node.js, we can use methods from the console object:
console.log(process.env.DATABASE_ENDPOINT);
console.log(process.env.DATABASE_PORT);
  • In Python, we need to import the os module and use the print statement:
import os
def lambda_handler(event, context):
DB_ENDPOINT = os.environ['DATABASE_ENDPOINT']
DB_PORT = os.environ['DATABASE_PORT']
print('Database endpoint: ', DB_ENDPOINT)
print('Database port: ', DB_PORT)

The preceding example has introduced a handler function – lambda_handler(). This important requirement ensures that a Lambda function works since it's the entry point for events. Let's dive in and learn how to write our own handlers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.157.34