Home > Enterprise >  how do you create s3 subdirectories using aws cdk?
how do you create s3 subdirectories using aws cdk?

Time:03-31

if I wanted to create a bucket with a layout like this:

bucket/
├─ subdir-1/
│  ├─ subsubdir-1/
├─ subdir-2/
├─ subdir-3/

how could I do this using the cdk? Or even a yml cf template?

CodePudding user response:

As mentioned in the comment, you do not need to create directories/template. When you use SDK/CLI to upload an object, it will automatically create the folder/structure matching the key used when uploading the object. You may be able to create empty directories through CLI/SDK but I don't think aws-cdk would do that as it is not supposed to managed the content of S3.

If you really want to maintain a certain layout for the bucket, you could use bucket policy to only allow certain directory when the SDK/CLI put your object to S3. This policy could be added on the aws-cdk (Ref: aws-cdk-s3-docs-addPolicy). Policy example as follows.

{
  "Sid": "Layout",
  "Effect": "Deny",
  "Principal": "*",
  "Action": "s3:PutObject*",
  "NotResource": [
    "arn:aws:s3:::{BUCKET_NAME}/subdir-1/*",
    "arn:aws:s3:::{BUCKET_NAME}/subdir-1/subdir-1/*",
    "arn:aws:s3:::{BUCKET_NAME}/subdir-2/*",
    "arn:aws:s3:::{BUCKET_NAME}/subdir-3/*",
  ]
}

More detail on s3 bucket policy: https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html

  • Related