Created
April 22, 2022 14:16
-
-
Save AHaydar/bfc173db2078b2eeb884da8632248c5d to your computer and use it in GitHub Desktop.
Terraform example for DynamoDB table, Lambda, and IAM to allow the Lambda to scan the table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
provider "aws" { | |
profile = "default" | |
region = "ap-southeast-2" | |
} | |
module "company_table" { | |
source = "terraform-aws-modules/dynamodb-table/aws" | |
name = "company" | |
hash_key = "companyId" | |
attributes = [ | |
{ | |
name = "companyId" | |
type = "S" | |
} | |
] | |
} | |
resource "aws_iam_role" "iam_for_lambda" { | |
name = "iam_for_lambda" | |
# Terraform's "jsonencode" function converts a | |
# Terraform expression result to valid JSON syntax. | |
assume_role_policy = jsonencode({ | |
Version = "2012-10-17" | |
Statement = [ | |
{ | |
Action = "sts:AssumeRole" | |
Effect = "Allow" | |
Sid = "" | |
Principal = { | |
Service = "lambda.amazonaws.com" | |
} | |
}, | |
] | |
}) | |
} | |
data "aws_iam_policy_document" "lambda_policy_document" { | |
statement { | |
actions = [ | |
"dynamodb:Scan", | |
] | |
resources = [ | |
module.company_table.dynamodb_table_arn | |
] | |
} | |
} | |
resource "aws_iam_policy" "dynamodb_lambda_policy" { | |
name = "dynamodb-lambda-policy" | |
description = "This policy will be used by the lambda to write get data from DynamoDB" | |
policy = data.aws_iam_policy_document.lambda_policy_document.json | |
} | |
resource "aws_iam_role_policy_attachment" "lambda_attachements" { | |
role = aws_iam_role.iam_for_lambda.name | |
policy_arn = aws_iam_policy.dynamodb_lambda_policy.arn | |
} | |
resource "aws_lambda_function" "test_lambda" { | |
filename = "get-companies-lambda.zip" | |
function_name = "test_lambda" | |
role = aws_iam_role.iam_for_lambda.arn | |
handler = "index.handler" | |
source_code_hash = filebase64sha256("get-companies-lambda.zip") | |
runtime = "nodejs14.x" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment