DEVELOPER BLOG

HOME > DEVELOPER BLOG > Comprehensive Guide to AWS Lambda Functions and Resource Access

Comprehensive Guide to AWS Lambda Functions and Resource Access

1. Introduction

The introduction provides an overview of the article's focus, which is to present a comprehensive guide on AWS Lambda functions and how they can access other AWS resources such as RDS, S3 bucket, and DynamoDB. It may briefly explain the significance of Lambda functions in serverless computing and how they enable event-driven, scalable applications.

2. Purpose

This section states the purpose of the article, which is to educate readers about AWS Lambda functions and demonstrate how to create them using the AWS Management Console and Prismscaler. It also aims to provide insights into how to set up IAM roles and permissions for Lambda functions to access other AWS resources securely.  

3. What is AWS Lambda function?

AWS Lambda is a serverless compute service provided by Amazon Web Services (AWS). It allows you to run code in response to events without the need to provision or manage servers. With AWS Lambda, you can execute your code in a highly scalable and cost-effective manner. Here are some key features and concepts related to AWS Lambda:
  1. Serverless Computing: Lambda is often referred to as a "serverless" service because you don't have to worry about the underlying infrastructure. AWS takes care of server provisioning, maintenance, and scaling for you.
  2. Event-Driven: Lambda functions are triggered by various AWS services or custom events. For example, you can set up a Lambda function to run when an object is uploaded to an S3 bucket, when an HTTP request hits an API Gateway, or in response to changes in a database.
  3. Supported Languages: Lambda supports multiple programming languages, including Node.js, Python, Java, C#, Ruby, and more. You can write your function code in one of these languages.
  4. Stateless: Lambda functions are designed to be stateless, meaning they should not rely on server-specific state or resources. Each function invocation is isolated, which helps with scalability and reliability.
  5. Pay-As-You-Go Pricing: With Lambda, you pay only for the compute time your code actually uses. There are no upfront costs or ongoing infrastructure maintenance fees. This makes it cost-effective, especially for workloads with varying usage patterns.
  6. Automatic Scaling: Lambda automatically scales your functions based on the incoming traffic. If you have a sudden surge in requests, Lambda will allocate more resources to handle the load. Conversely, it will scale down when there's less traffic.
  7. Integrated Logging and Monitoring: AWS provides built-in monitoring and logging for Lambda functions through services like Amazon CloudWatch. This helps you troubleshoot issues and monitor the performance of your functions.
  8. Security: Lambda functions can be configured with IAM (Identity and Access Management) roles, allowing you to control which AWS resources your functions can access. You can also configure VPC (Virtual Private Cloud) settings for more advanced networking requirements.
  9. Versioning and Aliases: Lambda allows you to create multiple versions of your functions, enabling you to deploy updates without affecting existing clients. You can also create aliases to point to specific versions, which is useful for implementing blue-green deployments.
  10. Event Sources: Lambda supports a wide range of event sources, including AWS services like S3, DynamoDB, SQS, and custom events using AWS Step Functions or API Gateway. You can also create custom event sources using AWS CloudWatch Events.

4. How to a Lambda function access to other resources such as RDS, S3 bucket, DynamoDb,...

AWS Lambda functions can access other AWS resources like RDS (Relational Database Service), S3 (Simple Storage Service), DynamoDB, and more by configuring appropriate permissions and network settings. Here's a high-level overview of how you can grant Lambda access to these resources: IAM Roles: Create an IAM Role: Start by creating an IAM role for your Lambda function. This role defines what AWS resources your Lambda function is allowed to access. Attach Policies: Attach AWS managed policies or custom policies to the IAM role. These policies define the permissions for specific AWS services. For example, you can attach the "AmazonRDSFullAccess" policy to allow access to RDS, or "AmazonS3FullAccess" for access to S3. Trust Relationships: Ensure that the trust relationship of the IAM role allows Lambda to assume it. The trust relationship typically looks like this:    
jsonCopy code{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}                
VPC Configuration (if needed):

  • If your Lambda function and the resources you want to access are in a Virtual Private Cloud (VPC), configure the Lambda function to run inside the VPC. You can do this when creating or updating the Lambda function.

  • Ensure that the Lambda function is associated with the appropriate security group and subnet(s) to access resources in the VPC, such as RDS databases or resources behind a VPC endpoint for S3.


Environment Variables (if needed):

  • If your Lambda function needs to connect to specific resources, like a database, you can use environment variables to store connection strings or other configuration settings. Lambda functions can access these environment variables at runtime.


AWS SDKs:

  • In your Lambda function code, use the AWS SDKs or AWS SDK for Lambda's runtime environment (for Node.js and Python) to interact with AWS resources. The SDKs provide libraries and methods to access and manipulate AWS services like RDS, S3, and DynamoDB.

5. Creating AWS Lambda function with AWS console

Step 1. Create Lambda function Go to Lambda service → click to Create function → enter the necessary information like function name, runtime and architecture:     By default, Lambda will create an execution role with permissions to upload logs to Amazon CloudWatch Logs. You can customize this default role later when adding triggers. Or you can choose an existing role.     Then, click to Create function. After function creation successful, edit your code into Code source section:     Step 2. Test Lambda function Go to Test section → create a new test if you don’t have any test case before. You can choose the template or configure Event JSON by yourself.     Then click to Save and click to Test. Here is the test function result:     Step 3. Monitor Lambda function Go to Monitor section, you can see the Cloudwatch metrics about your Lambda function or if you click to View CloudWatch logs, you will see the logs from Lambda function.       The log group of Lambda function has been named following this pattern:
/aws/lambda/<function_name>
                
With DevOps knowledge: 4-6 hours
Without DevOps knowledge: 2-3 days

6. Creating AWS Lambda function with PrismScaler

Prism Scaler provides you with an intuitive model and a concise form, you just need to fill in the necessary information and press create, now PrismScaler will automatically build a simple web application/system that moves on a container on AWS.         With just one click, PrismScaler will help you to initialize your Lambda function along with its execution role in which you will connect to other AWS resources like RDS, DynamoDB, S3,... 5-15 minutes (without DevOps knowledge)

7. How to setup IAM role and permissions for Lambda function

Find out the Lambda function execution role in Configuration section:     If you want your Lambda function can access to other AWS resources, you must grant permission for execution role.  
Add AWS policy
 
Edit your custom policy
Example policies for S3 bucket:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::<YOUR_BUCKET_NAME>",
        "arn:aws:s3:::<YOUR_BUCKET_NAME>/*"
      ]
    }
  ]
}                
Example policies for DynamoDB:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "dynamodb:*",
      "Resource": "arn:aws:dynamodb:<YOUR_REGION>:<YOUR_ACCOUNT_ID>:table/<YOUR_TABLE_NAME>"
    }
  ]
}                  

8. Reference

The reference section lists the sources or external materials used in the article, allowing readers to explore further or verify the information provided. Example policies for RDS: 
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "rds:*",
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}