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 () {
    DATA=`/opt/awscli/aws lambda get-function --function-name my-bash-lambda --query 'Configuration.FunctionArn' --output text`
    RESPONSE="{\"statusCode\": 200, \"body\": \"$DATA\"}"
    echo $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.