Skip to content

Instantly share code, notes, and snippets.

@jbnunn
Last active December 4, 2022 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbnunn/566834edbf51f8e911a4fc963d356a13 to your computer and use it in GitHub Desktop.
Save jbnunn/566834edbf51f8e911a4fc963d356a13 to your computer and use it in GitHub Desktop.
Update a Lambda function from the command line (Mac OS X)
"""
$ python update.py
Updates an AWS Lambda function with all the latest goodies.
To use, create a directory containing all the files and requirements required to
execute your Lambda function. Supply the directory, ARN of your Lambda function,
and AWS profile (defaults to `default`) as arguments to `update.py`, e.g.,
python update.py <directory> <lambda_arn> <aws_profile>
This will:
1. Create a ZIP file of the specified directory and place it in a `package` directory
2. Upload the ZIP file (`package/function.zip`) as your function's code to AWS Lambda
3. Poll Lambda to let you know when the code is ready to use
"""
import os
import sys
import boto3
import shutil
if len(sys.argv) < 3:
sys.exit('Usage: python update.py <directory> <aws_lambda_arn> <aws_profile>')
DIRECTORY = sys.argv[1]
AWS_LAMBDA_ARN = sys.argv[2]
AWS_PROFILE = sys.argv[3] if len(sys.argv) > 3 else 'default'
boto3.setup_default_session(profile_name=AWS_PROFILE)
lambda_client = boto3.client('lambda')
def create_zip_archive():
"""
Creates a ZIP archive of the given directory
"""
print('✨ Creating ZIP archive...')
filename = 'function'
shutil.make_archive(f'./package/{filename}', 'zip', DIRECTORY)
print('📦 ZIP archive created!')
return f'package/{filename}.zip'
def update_lambda(filename):
"""
Updates the Lambda function with the latest code
"""
print('🚀 Uploading Lambda function...')
with open(filename, 'rb') as f:
lambda_client.update_function_code(
FunctionName=AWS_LAMBDA_ARN,
ZipFile=f.read()
)
print('✅ Lambda function updated')
def poll_lambda_status():
"""
Uses a waiter to poll Lambda for up to 100 seconds (5 * 20) to check
your function's availability
"""
print('⏰ Waiting for function to become available...')
waiter = lambda_client.get_waiter('function_updated')
try:
waiter.wait(
FunctionName=AWS_LAMBDA_ARN,
WaiterConfig={
'Delay': 5,
'MaxAttempts': 20
}
)
except:
print('🤔 Hmm... the Lambda function failed to update')
else:
print('💥 Lambda function is now active!')
def kickoff():
f = create_zip_archive()
update_lambda(f)
poll_lambda_status()
if __name__ == '__main__':
kickoff()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment