Skip to content

Instantly share code, notes, and snippets.

@sbmagar
Last active August 25, 2022 04:40
Show Gist options
  • Save sbmagar/d4329130a28871d1729e7e92f6818568 to your computer and use it in GitHub Desktop.
Save sbmagar/d4329130a28871d1729e7e92f6818568 to your computer and use it in GitHub Desktop.
AWS Lambda with Terraform
import logging
import os
logger = logging.getLogger()
ACTIONS = {
'plus': lambda x, y: x + y,
'minus': lambda x, y: x - y,
'times': lambda x, y: x * y,
'divided-by': lambda x, y: x / y}
def lambda_handler(event, context):
logger.setLevel(os.environ.get('LOG_LEVEL', logging.INFO))
logger.debug('Event: %s', event)
action = event.get('action')
func = ACTIONS.get(action)
x = event.get('x')
y = event.get('y')
result = None
try:
if func is not None and x is not None and y is not None:
result = func(x, y)
logger.info("%s %s %s is %s", x, action, y, result)
else:
logger.error("I can't calculate %s %s %s.", x, action, y)
except ZeroDivisionError:
logger.warning("I can't divide %s by 0!", x)
response = {'result': result}
return response
data "aws_iam_policy_document" "example_lambda_policy" {
statement {
sid = "examplePolicyId"
effect = "Allow"
principals {
identifiers = ["lambda.amazonaws.com"]
type = "Service"
}
actions = ["sts:AssumeRole"]
}
}
resource "aws_iam_role" "example_lambda_iam" {
name = "example_lambda_iam"
assume_role_policy = data.aws_iam_policy_document.example_lambda_policy.json
}
provider "archive" {}
data "archive_file" "example_zip_file" {
type = "zip"
source_file = "example.py"
output_path = "example.zip"
}
resource "aws_lambda_function" "example_lambda_function" {
function_name = "example_function"
filename = data.archive_file.example_zip_file.output_path
# source_code_hash = data.archive_file.exmaple_zip_file.output_base64sha256
role = aws_iam_role.example_lambda_iam.arn
handler = "example.lambda_handler"
runtime = "python3.9"
}
output "lambda_function" {
value = aws_lambda_function.example_lambda_function.qualified_arn
}
variable "aws_region" {
default = "ap-south-1"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment