Run AWS CLI in a Lambda Function

AWS SDK is the standard way to go when a Lambda function needs to perform operations on AWS infrastructure by making calls to AWS services. But it’s also quite a verbose way of doing things. A lot of code is required along with minute attention to detail. It’s a fact that most such tasks would be easier to do using the AWS CLI.

This post describes how you can run the same AWS CLI commands inside a Lambda function that you run on your local terminal. Start by creating a Lambda layer as shown below:

After deploying this Lambda layer, create a Bash Lambda as described here & add this layer to it. After that, you can run any AWS CLI command in the function’s handler as shown below:

function handler () {
    EVENT_DATA=$1
    DATA=`/opt/awscli/aws lambda get-function --function-name my-bash-lambda --query 'Configuration.FunctionArn' --output text`
    RESPONSE="{\"statusCode\": 200, \"body\": \"$DATA\"}"
    echo $RESPONSE
}
Response:
{
  "statusCode": 200,
  "body": "arn:aws:lambda:us-east-1:123456789012:function:my-bash-lambda"
}

Make sure that the Lambda function’s execution role includes permissions to perform whatever operations you’re doing from the CLI.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.