Grant AWS Lambda Access of Secrets  Manager

Grant AWS Lambda Access of Secrets Manager

Introduction

In this article, we ran a Python application in AWS Lambda using Docker. Now we want to add some licencing mechanism by keeping the access key or any secret key to another service or application to restrict the use of this application. Here we can make use of the AWS Secrets Manager service to keep the access key or secret key safe.

So in this article, we will learn how to access AWS Secrets Manager in AWS Lambda.

AWS Lambda IAM Role

When we create any AWS Lambda function one default IAM role also gets created with AWSLambdaBasicExecutionRole policy. You can see that IAM role in the Configuration tab in the Permissions section of the AWS Lambda function page you already created. The role name would be starting with the Lambda function name.

So basically we are going to add one more policy to this role to access the Secret Manager. Go to the role page by clicking on Edit button.

To add a new policy click on Add permissions then Create inline policy

On the next page search for the service Secrets Manager whose access wants to grant to Lambda function.

In the next step, we have to select actions of Secrets Manager that are allowed for Lambda. Here we require only one which is GetSecretValue . Search for GetSecretValue in the search box and select it from the search results.

In the next section Resources you can select specific to allow only for this Lambda function and then click on Next button.

In the next page give the name to this policy and click on Create Policy button to create the final policy.

That's it after creating the policy it should start showing on the Lambda permissions page as shown below.

Now Lambda has access of GetSecretValue method of Secrets Manager.

Modify Lambda Function

The final step is to modify our Lambda function to use the secrets stored in Secrets Manager. We can do this by calling the Secrets Manager API from within our function. Here is an example Python code snippet that retrieves a secret value from Secrets Manager:

import boto3
import json

def lambda_handler(event, context):
    secret_name = "my_secret_name"
    region_name = "ap-south-1"

    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )

    get_secret_value_response = client.get_secret_value(
        SecretId=secret_name
    )

    if 'SecretKey' in get_secret_value_response:
        secret = get_secret_value_response['SecretKey']
    else:
        secret = json.loads(get_secret_value_response['SecretKey'])

Conclusion

By creating an IAM policy, and attaching it to the Lambda execution role we can use AWS Secrets Manager in AWS Lambda.