If you’ve landed here, you’ve realized that AWS Lambda is a great, fun way to have production code up and running. However; when using Python, it quickly becomes obvious that the process of zipping the package, uploading to s3 and navigating the AWS interface is annoying at best.
The following tutorial will take you through an easy deployment, all from the command line:
- Installing relevant packages locally
- Setting up AWS
- Updating your local code
- Deployment and execution
- Tips/Tricks
- (Optional) Setting up Github actions
Press enter or click to view image in full size
Install relevant packages
- Install serverless
npm install -g serverless2. Create your repo/package for aws-lambda
serverless create --template aws-python3 \ --name sample_project --path sample_project3. Create your virtualenv (to keep requirements isolated in python). And activate it.
virtualenv env --python=python3 & source env/bin/activate4. (Optional) Install any requirements you need for your project
pip install numpy & pip freeze > requirements.txt5. Install Docker (necessary to set up native packages on AWS lambda)
Set up AWS
In order to push to AWS Lambda from the command line, you need to have an access id and access key and params
- Create AWS account (if you haven’t already)
- Create a new access key, or find ones you’ve already made before. Keys can be accessed here. https://console.aws.amazon.com/iam/home?#/security_credentials
Press enter or click to view image in full size
3. Store the access key id and access key on your local environment (necessary for serverless)
export AWS_ACCESS_KEY_ID=<YOUR_KEY_ID> AWS_SECRET_ACCESS_KEY <YOUR SECRET_ID>4. (Optional) Store the variables as an alias, that way you can make sure you always push to the right AWS environment
alias aws_creds="export AWS_ACCESS_KEY_ID=<YOUR_KEY_ID> AWS_SECRET_ACCESS_KEY <YOUR SECRET_ID>"Update Python code on your machine
Remember how you ran create serverless , now enter into the directorycd sample_project . There are two files of importance handler.py and serverless.yml
Get Robert Olsthoorn’s stories in your inbox
Join Medium for free to get updates from this writer.
handler.py is where your python code lives. Update it appropriately.
To run on your own machine
python handler.pyserverless.yml is where you configure serverless for uploading.
Deploy and debug
- Run the deployment script, this will take a few minutes.
serverless deployOnce it finishes, check in AWS lambda that it updated appropriately.
Press enter or click to view image in full size
us-east-22. Invoke and call the function from your command line
serverless invoke -f sample-scraper --logYou did it! Tips/tricks
- To change the frequency, update the
cronfield in the serverless.yml file. - If the file size is too large, zip the requirements. Change the
zip:truein serverless.yml - Trying to store a file locally? Lambda lets you write to the
/tmpdirectory. Once you write it there, you can use s3 to then offload it to another place.