Search code examples
amazon-web-servicesamazon-s3bucket

When creating an amazon s3 bucket, is it possible to set a policy to be automatically written into the bucket?


I have a policy that needs to be attached to every new S3 bucket created, and it is a hassle to rewrite it every time with the new bucket name in the code. Is there a way to dynamically write bucket policies automatically according to the name of the bucket?


Solution

  • A good solution for this would be to create a CloudWatch event for the CreateBucket event, an example event syntax for this is below.

    {
      "source": [
        "aws.s3"
      ],
      "detail-type": [
        "AWS API Call via CloudTrail"
      ],
      "detail": {
        "eventSource": [
          "s3.amazonaws.com"
        ],
        "eventName": [
          "CreateBucket"
        ]
      }
    }
    

    Add a trigger to this event of a Lambda function, that Lambda function would be developed to apply the bucket policy to the S3 bucket (with you adding the bucket name passed into the Lambda function event).

    You will need to enable CloudTrail logging for S3 bucket API calls for this operation to be allowed.