IAM Roles for Lambda Function

Understanding IAM Roles for AWS Lambda Function

The AWS Lambda service is the serverless compute service on the cloud. Now if the AWS Lambda function needs to access other resources then the IAM Role that is attached to the Lambda function needs to have the required access. This article discusses IAM Roles for AWS Lambda Function that is an important topic under the domain Identity and Access Management (IAM). This topic will help those who are preparing for the AWS Certified Solutions Architect Professional Exam or AWS Certified Security Specialty Exam.

A common type of question that comes up in the AWS certification exam is the permissions that can be assigned to an AWS Lambda function.

AWS Lambda and API Gateway training course

IAM Roles for AWS Lambda Function

Let’s understand IAM roles for AWS Lambda function through an example:

In this example, we will make AWS Lambda run an AWS Athena query against a CSV file in S3. And we will see what is required from an IAM Role perspective.

Step 1) So first, we have an S3 bucket defined as shown below

IAM Roles for AWS Lambda Function

The S3 bucket has a data file called data.csv which is a simple data file which contains the name of AWS certification exams.

Step 2) Now we go onto AWS Athena. Here we have a database called demodb. We execute the following query to create a table.

Here we execute the following query:

CREATE EXTERNAL TABLE IF NOT EXISTS exams (

  ID INT,

  name STRING

    ) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' 

WITH SERDEPROPERTIES ("separatorChar" = ",") 

LOCATION 's3://athena2020/'

IAM Roles for AWS Lambda Function

Once you run the query, you will get the table created in AWS Athena

IAM Roles for AWS Lambda Function

Step 3) Now let’s run a select query in AWS Athena just to check if we are able to fetch the data.

IAM Roles for AWS Lambda Function

So, you will see the result data. This is the result data that is stored in the .csv file in S3.

Step 4) Now create an AWS Lambda function. This will have python as the underlying runtime.

IAM Roles for AWS Lambda Function

Following is the code snippet

import json

import time

import boto3




def lambda_handler(event, context):

    # TODO implement

    client = boto3.client('athena')

    query='select * from exams;'

    S3_OUTPUT='s3://athena2020/output'

    # Execution

    response = client.start_query_execution(

        QueryString=query,

        QueryExecutionContext={

            'Database': 'demodb'

        },

        ResultConfiguration={

            'OutputLocation': S3_OUTPUT,

        }

    )

    time.sleep(5)

    query_execution_id = response['QueryExecutionId']

    print(query_execution_id)

    result = client.get_query_results(QueryExecutionId=query_execution_id)

    print(result)

    return {

        'statusCode': 200,

        'body': json.dumps('Results from Lambda!')

    }

The code snippet is quite self-explanatory. We are using the python boto3 SDK to work with Athena queries. We then transfer the output results to the S3 folder location ‘s3://athena2020/output’. This is important to note.

Now if you drill further down, you will see the IAM Role attached to the Lambda function

IAM Roles for AWS Lambda Function

So, it’s a service role called athenarole.

If we go to the Role definition in Security credentials, you can see that the role has a basic execution policy

IAM Roles for AWS Lambda Function

Step 5) Let’s run our AWS Lambda function

IAM Roles for AWS Lambda Function

So, when we Test our AWS Lambda function, we are getting an Access Denied error. This is because we need to give permission to our AWS Lambda function to access the Athena service. Since the lambda function is making a call to AWS Athena, we need to add this permission to the role.

Step 6) So let’s go back to the IAM Role definition and click on Attach policies

IAM Roles for AWS Lambda Function

For the purpose of this demo, let’s just add a policy for full access to AWS Athena

So in the next screen, find and choose AmazonAthenaFullAccess and choose Attach policy

IAM Roles for AWS Lambda Function

Step 7) Now let’s run our Lambda function again

IAM Roles for AWS Lambda Function

We are still getting the same error. Why is that?

Remember that the function also sends the output data to S3, hence we need to also ensure that the IAM role also has access to S3

Step 8) So let’s go back to the IAM Role definition and click on Attach policies

IAM Roles for AWS Lambda Function

For the purpose of this demo, let’s just add a policy for full access to AWS S3

So in the next screen, find and choose AmazonS3FullAccess and choose Attach policy

Now let’s run our AWS Lambda function

IAM Roles for AWS Lambda Function

You will now get a successful execution of the Lambda function

IAM Roles for AWS Lambda Function

Summary

  • There is a service linked role which is present for AWS Lambda functions
  • These roles have permissions which are required to access other AWS services
  • You can attach multiple policies to IAM Roles for AWS Lambda function

So, here we’ve covered IAM Roles with AWS Lambda Function. Hope this helps in your preparation of AWS certification exams specifically, AWS Certified Solutions Architect Professional & AWS Certified Security Specialty Exams. If you are done with your preparation, it’s the time to check your preparation level. Try Whizlabs practice tests for the AWS Certified Solutions Architect Professional Exam and AWS Certified Security Specialty Exam

Whizlabs practice tests have been prepared by the industry experts and make you confident enough to pass the actual certification exams. 

If you have any other query regarding the AWS Certified Solutions Architect Professional Exam or AWS Certified Security Specialty Exam, just put a comment below or write in Whizlabs Forum.

About Pavan Gumaste

Pavan Rao is a programmer / Developer by Profession and Cloud Computing Professional by choice with in-depth knowledge in AWS, Azure, Google Cloud Platform. He helps the organisation figure out what to build, ensure successful delivery, and incorporate user learning to improve the strategy and product further.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top