Skip to content

Commit 952e470

Browse files
author
Ben Fortuna
committed
Added templates for common lambda functions
1 parent 3fd46eb commit 952e470

File tree

18 files changed

+572
-2
lines changed

18 files changed

+572
-2
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
terraform-aws-lambda-function.iml
3+
.terraform/

Makefile

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
SHELL:=/bin/bash
2+
TERRAFORM_VERSION=0.12.24
3+
TERRAFORM=docker run --rm -v "${PWD}:/work" -v "${HOME}:/root" -e AWS_DEFAULT_REGION=$(AWS_DEFAULT_REGION) -e http_proxy=$(http_proxy) --net=host -w /work hashicorp/terraform:$(TERRAFORM_VERSION)
4+
5+
.PHONY: all clean test docs format
6+
7+
all: test docs format
8+
9+
clean:
10+
rm -rf .terraform/
11+
12+
test:
13+
$(TERRAFORM) init && $(TERRAFORM) validate
14+
15+
docs:
16+
docker run --rm -v "${PWD}:/work" tmknom/terraform-docs markdown ./ >./README.md
17+
18+
format:
19+
$(TERRAFORM) fmt -list=true ./

README.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,30 @@
1-
# terraform-aws-lambda-function
2-
Templates for common Lambda functions
1+
# ![AWS](aws-logo.png) Lambda Function
2+
3+
Purpose: Provision a Lambda Function in AWS.
4+
5+
Rationale: Apply standards provide templates for Lambda functions.
6+
7+
## Requirements
8+
9+
No requirements.
10+
11+
## Providers
12+
13+
| Name | Version |
14+
|------|---------|
15+
| archive | n/a |
16+
| aws | n/a |
17+
18+
## Inputs
19+
20+
| Name | Description | Type | Default | Required |
21+
|------|-------------|------|---------|:--------:|
22+
| function\_name | Name of the Lambda function | `any` | n/a | yes |
23+
| role | IAM role assumed by the Lambda function | `any` | n/a | yes |
24+
| runtime | A runtime to use for the function (leave blank to use default runtime) | `any` | `null` | no |
25+
| template | A predefined function template | `any` | n/a | yes |
26+
27+
## Outputs
28+
29+
No output.
30+

aws-logo.png

3.84 KB
Loading

functions.tf

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
locals {
2+
templates = {
3+
ec2-instance-cycle = {
4+
lambda_handler = "lambda_handler"
5+
default_runtime = "python3.6"
6+
}
7+
}
8+
}

main.tf

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* # ![AWS](aws-logo.png) Lambda Function
3+
*
4+
* Purpose: Provision a Lambda Function in AWS.
5+
*
6+
* Rationale: Apply standards provide templates for Lambda functions.
7+
*/
8+
data "archive_file" "function" {
9+
source_dir = "${path.module}/templates/${var.template}"
10+
output_path = "${var.template}.zip"
11+
type = "zip"
12+
}
13+
14+
data "aws_iam_role" "role" {
15+
name = var.role
16+
}
17+
18+
resource "aws_lambda_function" "function" {
19+
function_name = var.function_name
20+
role = data.aws_iam_role.role.arn
21+
filename = data.archive_file.function.output_path
22+
handler = "${var.function_name}.${local.templates[var.template]["lambda_handler"]}"
23+
runtime = var.runtime != null ? var.runtime : local.templates[var.template]["default_runtime"]
24+
source_code_hash = data.archive_file.function.output_base64sha256
25+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
exports.handler = (event, context, callback) => {
2+
const request = event.Records[0].cf.request;
3+
request.uri = request.uri.replace(/\+/g, '%2B');
4+
callback(null, request);
5+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import re
2+
3+
4+
def lambda_handler(event):
5+
request = event['Records'][0]['cf']['request']
6+
request.uri = re.sub(r"\+", "%2B", request.uri)
7+
return request
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
DynamoDB Import Comma-separated values (CSV) document.
3+
4+
An AWS Lambda function used to import batch records to a DynamoDB table.
5+
"""
6+
import csv
7+
import json
8+
import os
9+
import uuid
10+
11+
import boto3
12+
from botocore.exceptions import ClientError
13+
14+
data_types = os.environ['DataTypes']
15+
table_name = os.environ['TableName']
16+
item_template = json.loads(os.environ['ItemTemplate'])
17+
auto_generate_key = os.environ['AutoGenerateKey']
18+
19+
20+
def lambda_handler(event):
21+
bucket = event['Records'][0]['s3']['bucket']['name']
22+
filename = event['Records'][0]['s3']['object']['key']
23+
24+
import_file(bucket, filename)
25+
26+
27+
def import_file(bucket, filename):
28+
s3 = boto3.client('s3')
29+
dynamodb = boto3.client('dynamodb')
30+
try:
31+
data = s3.get_object(Bucket=bucket, Key=filename)['Body'].read().decode('utf-8')
32+
csv_reader = csv.reader(data.splitlines(), delimiter=',')
33+
columns = None
34+
linenum = 0
35+
for row in csv_reader:
36+
if linenum == 0:
37+
# use header row to identify the columns..
38+
columns = row
39+
else:
40+
import_row(row2map(columns, row), dynamodb)
41+
linenum += 1
42+
except ClientError as e:
43+
print(e)
44+
45+
46+
def row2map(columns, row):
47+
retval = {}
48+
if (auto_generate_key):
49+
retval['UUID'] = uuid.uuid4().hex
50+
for key, value in item_template.items():
51+
data_type = data_types[key] if key in data_types else 'S'
52+
retval[key] = {data_type: value}
53+
54+
for column in columns:
55+
if len(row[columns.index(column)]) > 0:
56+
data_type = data_types[column] if column in data_types else 'S'
57+
retval[column] = {data_type: row[columns.index(column)]}
58+
return retval
59+
60+
61+
def import_row(row, client):
62+
try:
63+
client.put_item(TableName=table_name, Item=row)
64+
except ClientError as e:
65+
print(e)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
DynamoDB Put Item.
3+
4+
An AWS Lambda function used to add items to a DynamoDB table.
5+
"""
6+
import json
7+
import os
8+
9+
import boto3
10+
from botocore.exceptions import ClientError
11+
12+
data_types = os.environ['DataTypes']
13+
table_name = os.environ['TableName']
14+
15+
16+
def lambda_handler(event):
17+
item = json.loads(event['Item'])
18+
19+
put_item(dict2payload(item))
20+
21+
22+
def dict2payload(item):
23+
retval = {}
24+
for key, value in item.items():
25+
data_type = data_types[key] if key in data_types else 'S'
26+
retval[key] = {data_type: value}
27+
return retval
28+
29+
30+
def put_item(payload):
31+
dynamodb = boto3.client('dynamodb')
32+
try:
33+
dynamodb.put_item(TableName=table_name, Item=payload)
34+
except ClientError as e:
35+
print(e)

0 commit comments

Comments
 (0)