Want To Use aws Command In Lambda Function

How To

Build Environment In Local

Step 1 make sure your python, pip and virtualenv are same python version

~ » python3 --version
Python 3.7.9
~ » pip3 --version 
pip 20.1.1 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)
~ » virtualenv --version
virtualenv 20.11.2 from /usr/local/lib/python3.9/site-packages/virtualenv/

Step 2 Create Python Environment And Lambda Layer Folder

mkdir -p awscli-lambda awscli-lambda/layer
cd awscli-lambda && virtualenv env

Folder Tree

├── env
└── layer
  • Comment :

  • env Folder Is Use To Build ENV

  • layer Folder Is Use To Upload Library To Lambda Layer

Step 3 Change To Isolation Python Env And Install Package

cd env && source bin/active

Then You’ll See

(env) ----------------------------------------
~/awscli-lambda/env »

Install Package

pip install awscli

Then Change Path To layer Folder

cd ../layer/

Copy Library To layer Folder

cp -r ../env/lib/python3.9/site-packages/ .

Copy aws Command To layer Folder

cp ../env/bin/aws .

Change Python Execution Environment In aws File

$ vim aws 





Compression File

zip -r ../ *

Step 4 Upload To Lambda Function Layer And Add To Lambda Function

Click Create Layer And Enter Name, Upload Zip, Select Your Architech (Local Compute) And Select Runtimes

After Upload, Your Can Go To Lambda Function Console And Add Layer

Step 5 Now, You Can Go To Code Page, Write Some Code To Use aws Command In Lambda

import subprocess
def lambda_handler(event, context):'/opt/aws --version')

Or Use def

import subprocess, logging

logger = logging.getLogger()

def run_command(command):
    command_list = command.split(' ')

    try:"Running shell command: \"{}\"".format(command))
        result =, stdout=subprocess.PIPE);"Command output:\n---\n{}\n---".format(result.stdout.decode('UTF-8')))
    except Exception as e:
        logger.error("Exception: {}".format(e))
        return False

    return True
def lambda_handler(event, context):
	run_command('/opt/aws --version' )

Congratulations, You Can Run AWS CLI In Lambda