Search code examples
amazon-web-servicesamazon-s3aws-cdk

Write S3 objects with CDK


I am trying to code a CDK doing the job of writing some empty objects inside some folders that I need to be visible in my bucket.

I have found this answer https://serverfault.com/questions/957686/how-to-upload-a-file-into-s3-bucket-using-cloudformation-script showing the way in CloudFormation.

I wonder if somebody has done something similar with CDK.

Thank you


Solution

  • You can achieve this with @aws-cdk/aws-s3-deployment.

    Using TypeScript:

    import s3 = require('@aws-cdk/aws-s3');
    import s3deploy = require('@aws-cdk/aws-s3-deployment');
    
    const myBucket = new s3.Bucket(this, 'Bucket');
    
    new s3deploy.BucketDeployment(this, 'DeployFiles', {
      sources: [s3deploy.Source.asset('./folder')], // 'folder' contains your empty files at the right locations
      destinationBucket: bucket,
    });
    

    Asset feature will require the execution of the command:

    cdk bootstrap aws://<account>/<region>

    that will run a cloudFormation and create a bucket with name cdktoolkit-stagingbucket-<random_chars>.