AWS Lambda deployment with Terraform & Terragrunt - Tutorial
This tutorial shows how to deploy a Python
function on
AWS Lambda
with
Terraform
and
Terragrunt
.
The Terraform
configuration can also:
- install the required
Python
dependencies - keep track of changes to the code and dependencies to avoid re-deploying an unchanged function
Terragrunt
is a wrapper for Terraform
which helps
to manage multiple environments.
Prerequisites
Optional:
Setup
- Create an AWS account and get a
Access Key ID
andSecret Access Key
pair (read the docs) - Install and configure the
AWS CLI
(read the docs) - Install
Terraform
(read the docs) - Install
Python
or, withMiniconda
orConda
, run:(Python docs)$ conda env create -n tflambda -f environment.yml $ source activate tflambda
Terragrunt
is optional, install it for a more advanced setup (read the docs)
Usage
Running locally
$ cd lambda
$ pip install -r requirements.txt
$ python lambda.py
to view the log output on screen, run:
$ LOG_LEVEL=INFO python lambda.py
Deploying to AWS Lambda with Terraform
Run:
$ cd terraform
$ terraform init
$ terraform apply
If you have multiple AWS profiles and you want to set the profile to use:
$ AWS_PROFILE=myprofilename terraform apply
The Terraform AWS provider
offers a number of options to set credentials,
check the docs
for further details.
To deploy to a specific AWS region
(see variables.tf
for defaults):
$ terraform apply -var aws_region="eu-west-1"
Deploying to AWS Lambda with Terragrunt
2 sample Terragrunt
configurations are provided:
terragrunt/eu
sets the AWSregion
toeu-west-1
terragrunt/us
sets the AWSregion
tous-east-1
Run:
$ cd terragrunt/eu
$ terragrunt apply
change /eu
to /us
and repeat to try another region.
AWS profiles selection also applies to Terragrunt
:
$ AWS_PROFILE=myprofilename terragrunt apply
Cleaning up
Run:
$ cd terraform
$ terraform destroy