Skip to content

Instantly share code, notes, and snippets.

@projectweekend
Last active February 8, 2022 13:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save projectweekend/b360ef9ce775e87aa9c1 to your computer and use it in GitHub Desktop.
Save projectweekend/b360ef9ce775e87aa9c1 to your computer and use it in GitHub Desktop.
Update AWS Lambda code with Boto3
import io
import os
from zipfile import ZipFile
from boto3.session import Session
session = Session(
aws_access_key_id='your-aws-access-key',
aws_secret_access_key='your-iam-secret-key',
region_name='your-aws-region')
aws_lambda = session.client('lambda')
def files_to_zip(path):
for root, dirs, files in os.walk(path):
for f in files:
full_path = os.path.join(root, f)
archive_name = full_path[len(path) + len(os.sep):]
yield full_path, archive_name
def make_zip_file_bytes(path):
buf = io.BytesIO()
with ZipFile(buf, 'w') as z:
for full_path, archive_name in files_to_zip(path=path):
z.write(full_path, archive_name)
return buf.getvalue()
def update_lambda(lambda_name, lambda_code_path):
if not os.path.isdir(lambda_code_path):
raise ValueError('Lambda directory does not exist: {0}'.format(lambda_code_path))
aws_lambda.update_function_code(
FunctionName=lambda_name,
ZipFile=make_zip_file_bytes(path=lambda_code_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment