Home > front end >  Create S3 bucket and lambda policies with terraform
Create S3 bucket and lambda policies with terraform

Time:11-03

I have some trouble accessing my AWS bucket from a lambda. I create and configure my bucket/lambdas using terraform (terraform newbie here).

Here is the module that creates the S3 bucket :

module "create-my-bucket" {
  source = "terraform-aws-modules/s3-bucket/aws"

  bucket = "my-bucket"
  acl    = "private"

  versioning = {
    enabled = true
  }

  block_public_acls       = true
  block_public_policy     = true
  restrict_public_buckets = true
  ignore_public_acls      = true
  attach_deny_insecure_transport_policy = true

  server_side_encryption_configuration = {
    rule = {
      apply_server_side_encryption_by_default = {
        sse_algorithm = "AES256"
      }
    }
  }
} 

Here is the module that configure policies for the lambda :

module "my_lambda_policy" {
  source = "terraform-aws-modules/iam/aws//modules/iam-policy"

  name        = "validate_lambda_policy"
  path        = "/"
  description = "Validate Policy"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [{
            "Effect": "Allow",
            "Action": [
                "s3:Put*",
                "s3:Get*",
                "s3:List*",
                "ses:SendEmail"
            ],
            "Resource": [
                    "arn:aws:s3:::my-bucket/",
                    "arn:aws:s3:::my-bucket/*",
                    "arn:aws:ses:..."
      ]
    }]
}
EOF
}

Terraform properly creates my bucket and configure my lambda, however, when my lambda tries to perform a "ListObjectsV2" or a "GetObject" operation, it get an "Access Denied".

I have set up with my policies some SES policy. These policies are properly applied (my lambda sends mails) so I expect that my S3 policies are also properly applied. Am I missing something with the bucket configuration ? What should I do to correct this (without setting my bucket full public of course)

CodePudding user response:

This ARN is wrong for the S3 bucket:

                    "arn:aws:s3:::my-bucket/",

the / makes it not match the bucket ARN. This set of documentation is the best place I know of to determine exactly what an ARN looks like for a given resource.

So you should change it to

                    "arn:aws:s3:::my-bucket",

Without the slash. Leave "arn:aws:s3:::my-bucket/*" also, because that will match the objects' arns for Get/Put Object.

  • Related