An example on how to build an AWS Lamda in Python using Terraform
- AWS account
- AWS CLI
- Python 3
- Terraform
- Create a free account at https://aws.amazon.com
- Login in https://console.aws.amazon.com and select your desired region (eu-west-1 - EU Ireland)
- Get your Access Key in Account Menu -> "My Security Credentials" -> "Identity and Access Management (IAM)" -> "Access keys" and save it somewhere secure :)
- Install python in your machine (https://www.python.org/downloads)
- Install terraform in your machine (https://www.terraform.io/downloads.html)
- In AWS console, go to "Services" -> "Lambda" and "Create function"
- Give the function name
- Runtime choose "Python 3.6"
- In Permissions chose the basic lambda permissions role
- And then Create function
Basic function
import json
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps({"message": "It works!"})
}
- Install AWS CLI (https://docs.aws.amazon.com/cli/latest/userguide/install-macos.html)
- Configure AWS CLI
aws configure
AWS Access Key ID [None]: <YOUR KEY ID>
AWS Secret Access Key [None]: <YOUR ACCESS KEY>
Default region name [None]: eu-west-1
Default output format [None]: json
- In your working directory, init terraform
terraform init
- Create the configuration file
config.tf
provider "aws" {
version = "~> 2.24"
region = "eu-west-1"
}
- Create a zip file with your lambda (ie:
functions/it_works.zip
) - Write your lambda definition (ie:
terraform/lambda.tf
) - Plan it!
terraform plan
If everything is ok, you'll all the resources that are going to be create/updated/deleted.
- Apply it!
terraform apply
Go to teh AWS Console and you'll see your lamda that is created.
More about terraform lambda function More about terraform api gateway
terraform destroy