nnnm
nnnm

Reputation: 313

Restricting S3 bucket access to an AWS Lambda function

I have a file in an S3 bucket for which I would like to restrict access, so that it can only be accessed from within a specific Lambda function. I tried writing a Bucket policy (subbing in my info for region, account, etc.) to accomplish this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1457474835965",
      "Action": "s3:*",
      "Principal": "*",
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::my-bucket/file.txt",
      "Condition": {
        "ArnNotEquals": {
          "aws:SourceArn": "arn:aws:lambda:region:account:function:FunctionName"
        }
      }
    }
  ]
}

However access to the file was still denied to the Lambda function when it was invoked. How can I accomplish what I am trying to do?

Upvotes: 3

Views: 4213

Answers (3)

varad_s
varad_s

Reputation: 1192

You can also try.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1457474835965",
      "Action": "s3:*",
      "Effect": "Allow",
      "Principal": {
         "AWS": "arn:aws:iam::${Id}:role/${lambdaName}-${region}-lambdaRole"
       },
      "Resource": "arn:aws:s3:::my-bucket/file.txt"
    }
  ]
}

The Principal element specifies the user, account, service, or other entity that is allowed or denied access to a resource. Hence Provide the iam role for lambda function in "Principal" object. You can get it from

lambda's console -> Permissions -> Execution Role.

For more info checkout following page: https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-bucket-user-policy-specifying-principal-intro.html

Upvotes: 0

gurnisht
gurnisht

Reputation: 111

{
    "Version": "2012-10-17",
    "Id": "Policy1592828725895",
    "Statement": [
        {
            "Sid": "ListRelevantDirectories20150907",
            "Effect": "Deny",
            "NotPrincipal": {
                "AWS": [
                    "arn:aws:iam::123456789999:role/LamdaRole",
                    "arn:aws:iam::123456789999:root",
                    "arn:aws:iam::123456789999:user/John"
                ]
            },
            "Action": "s3:*",
             "Resource": [
                "arn:aws:s3:::bucket_name",
                "arn:aws:s3:::bucket_name/*"
            ]
        }
    ]
}

Upvotes: 0

ataylor
ataylor

Reputation: 66109

Your lambda function will be running with a specific role. Create a policy that grants access to the s3 resource and add it to the role.

Example:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::my-bucket/file.txt"
    }
  ]
}

Upvotes: 4

Related Questions