1

I have the following main.tf file which creates an S3 bucket my-tf-test-bucket-12567 and an AWS lambda hasher_lambda:

provider "aws" {
  profile = "default"
  region  = "us-east-1"
}

resource "aws_s3_bucket" "b" {
  bucket = "my-tf-test-bucket-12567"
  acl    = "private"

  tags = {
    Name        = "My bucket"
    Environment = "Dev"
  }
}

data "archive_file" "lambda" {
  type        = "zip"
  source_file = "${path.module}/src/hash.py"
  output_path = "${path.module}/src/hash.py.zip"
}
 
resource "aws_iam_role" "iam_for_lambda" {
  # add S3 inline policies for lambda to be able to read/write from/to S3 bucket
  name = "iam_for_lambda"
 
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}
 
resource "aws_lambda_function" "hasher_lambda" {
  filename      = data.archive_file.lambda.output_path
  function_name = "hasher_lambda"
  role          = aws_iam_role.iam_for_lambda.arn
  handler       = "hash.handler"
  runtime       = "python3.8"
}

How can I configure the AWS lambda to be triggered by S3 bucket my-tf-test-bucket-12567 in Terraform?

1 Answer 1

3

You may need to create an aws_s3_bucket_notification and aws_lambda_permission in order for the function to be invoked by S3 events.

Lambda permission:

resource "aws_lambda_permission" "allow_bucket" {
  statement_id  = "AllowExecutionFromS3Bucket"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.hasher_lambda.arn
  principal     = "s3.amazonaws.com"
  source_arn    = aws_s3_bucket.bucket.arn
}

Bucket notification:

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = aws_s3_bucket.b.id

  lambda_function {
    lambda_function_arn = aws_lambda_function.func.arn
    events              = ["s3:ObjectCreated:*"]
  }

  depends_on = [aws_lambda_permission.allow_bucket]
}

There can be several event notification types which may cause an invocation of the Lambda. The whole list can be found in the AWS docs: source.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.