Socket
Socket
Sign inDemoInstall

@aws-cdk/aws-s3-assets

Package Overview
Dependencies
21
Maintainers
5
Versions
249
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @aws-cdk/aws-s3-assets

Deploy local files and directories to S3


Version published
Weekly downloads
128K
increased by1.06%
Maintainers
5
Created
Weekly downloads
 

Package description

What is @aws-cdk/aws-s3-assets?

@aws-cdk/aws-s3-assets is an AWS CDK library that allows you to manage and deploy assets to Amazon S3. It simplifies the process of uploading files and directories to S3 and integrates seamlessly with other AWS CDK constructs.

What are @aws-cdk/aws-s3-assets's main functionalities?

Upload a File to S3

This feature allows you to upload a single file to an S3 bucket. The code sample demonstrates how to create a new asset from a file located at 'path/to/file.txt' and upload it to S3.

const s3assets = require('@aws-cdk/aws-s3-assets');
const cdk = require('@aws-cdk/core');

class MyStack extends cdk.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    new s3assets.Asset(this, 'MyAsset', {
      path: 'path/to/file.txt'
    });
  }
}

const app = new cdk.App();
new MyStack(app, 'MyStack');

Upload a Directory to S3

This feature allows you to upload an entire directory to an S3 bucket. The code sample demonstrates how to create a new asset from a directory located at 'path/to/directory' and upload it to S3.

const s3assets = require('@aws-cdk/aws-s3-assets');
const cdk = require('@aws-cdk/core');

class MyStack extends cdk.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    new s3assets.Asset(this, 'MyAsset', {
      path: 'path/to/directory'
    });
  }
}

const app = new cdk.App();
new MyStack(app, 'MyStack');

Grant Read Permissions

This feature allows you to grant read permissions to an IAM role for the uploaded asset. The code sample demonstrates how to create a new asset, an IAM role, and grant read permissions to the role for the asset.

const s3assets = require('@aws-cdk/aws-s3-assets');
const cdk = require('@aws-cdk/core');
const iam = require('@aws-cdk/aws-iam');

class MyStack extends cdk.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    const asset = new s3assets.Asset(this, 'MyAsset', {
      path: 'path/to/file.txt'
    });

    const role = new iam.Role(this, 'MyRole', {
      assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')
    });

    asset.grantRead(role);
  }
}

const app = new cdk.App();
new MyStack(app, 'MyStack');

Other packages similar to @aws-cdk/aws-s3-assets

Changelog

Source

1.72.0 (2020-11-06)

⚠ BREAKING CHANGES TO EXPERIMENTAL FEATURES

  • rds: Serverless cluster enableHttpEndpoint renamed to enableDataApi
  • stepfunctions-tasks: type of outputLocation in the experimental Athena StartQueryExecution has been changed to s3.Location from string

Features

Bug Fixes

  • apigateway: changes to gateway response does not trigger auto deployment (#11068) (0c8264a), closes #10963
  • cfnspec: incorrect Route 53 health check configuration properties in CloudFormation specification (#11280) (f3c8b50), closes #issuecomment-717435271 #11096
  • cli: --no-previous-parameters incorrectly skips updates (#11288) (1bfc649)
  • core: many nested stacks make NodeJS run out of memory (#11250) (c124886)
  • core: multiple library copies lead to 'Assets must be defined within Stage or App' error (#11113) (fcfed39), closes #10314
  • core: support docker engine v20.10.0-beta1 (#11124) (87887a3)
  • dynamodb: Misconfigured metrics causing empty graphs (#11283) (9968669)
  • ecs: redirect config should honor openListener flag (#11115) (ed6e7ed)
  • event-targets: circular dependency when the lambda target is in a different stack (#11217) (e21f249), closes #10942
  • pipelines: asset stage can't support more than 50 assets (#11284) (5db8e80), closes #9353
  • secretsmanager: can't export secret name from Secret (#11202) (5dcdecb), closes #10914
  • secretsmanager: Secret.fromSecretName doesn't work with ECS (#11042) (fe1ce73), closes #10309 #10519
  • stepfunctions: stack overflow when referenced json path finding encounters a circular object graph (#11225) (f14d823), closes #9319
  • stepfunctions-tasks: Athena* APIs have incorrect supported integration patterns (#11188) (0f66833), closes #11045 #11246
  • stepfunctions-tasks: incorrect S3 permissions for AthenaStartQueryExecution (#11203) (b35c423)
  • explicitly set the 'ImagePullPrincipalType' of image (#11264) (29aa223), closes #10569

Readme

Source

AWS CDK Assets


cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


Assets are local files or directories which are needed by a CDK app. A common example is a directory which contains the handler code for a Lambda function, but assets can represent any artifact that is needed for the app's operation.

When deploying a CDK app that includes constructs with assets, the CDK toolkit will first upload all the assets to S3, and only then deploy the stacks. The S3 locations of the uploaded assets will be passed in as CloudFormation Parameters to the relevant stacks.

The following JavaScript example defines an directory asset which is archived as a .zip file and uploaded to S3 during deployment.

Example of a ZipDirectoryAsset

The following JavaScript example defines a file asset, which is uploaded as-is to an S3 bucket during deployment.

Example of a FileAsset

Attributes

Asset constructs expose the following deploy-time attributes:

  • s3BucketName - the name of the assets S3 bucket.
  • s3ObjectKey - the S3 object key of the asset file (whether it's a file or a zip archive)
  • s3ObjectUrl - the S3 object URL of the asset (i.e. s3://mybucket/mykey.zip)
  • httpUrl - the S3 HTTP URL of the asset (i.e. https://s3.us-east-1.amazonaws.com/mybucket/mykey.zip)

In the following example, the various asset attributes are exported as stack outputs:

Example of referencing an asset

Permissions

IAM roles, users or groups which need to be able to read assets in runtime will should be granted IAM permissions. To do that use the asset.grantRead(principal) method:

The following examples grants an IAM group read permissions on an asset:

Example of granting read access to an asset

How does it work?

When an asset is defined in a construct, a construct metadata entry aws:cdk:asset is emitted with instructions on where to find the asset and what type of packaging to perform (zip or file). Furthermore, the synthesized CloudFormation template will also include two CloudFormation parameters: one for the asset's bucket and one for the asset S3 key. Those parameters are used to reference the deploy-time values of the asset (using { Ref: "Param" }).

Then, when the stack is deployed, the toolkit will package the asset (i.e. zip the directory), calculate an MD5 hash of the contents and will render an S3 key for this asset within the toolkit's asset store. If the file doesn't exist in the asset store, it is uploaded during deployment.

The toolkit's asset store is an S3 bucket created by the toolkit for each environment the toolkit operates in (environment = account + region).

Now, when the toolkit deploys the stack, it will set the relevant CloudFormation Parameters to point to the actual bucket and key for each asset.

Asset Bundling

When defining an asset, you can use the bundling option to specify a command to run inside a docker container. The command can read the contents of the asset source from /asset-input and is expected to write files under /asset-output (directories mapped inside the container). The files under /asset-output will be zipped and uploaded to S3 as the asset.

The following example uses custom asset bundling to convert a markdown file to html:

Example of using asset bundling.

The bundling docker image (image) can either come from a registry (BundlingDockerImage.fromRegistry) or it can be built from a Dockerfile located inside your project (BundlingDockerImage.fromAsset).

You can set the CDK_DOCKER environment variable in order to provide a custom docker program to execute. This may sometime be needed when building in environments where the standard docker cannot be executed (see https://github.com/aws/aws-cdk/issues/8460 for details).

Use local to specify a local bundling provider. The provider implements a method tryBundle() which should return true if local bundling was performed. If false is returned, docker bundling will be done:

new assets.Asset(this, 'BundledAsset', {
  path: '/path/to/asset',
  bundling: {
    local: {
      tryBundle(outputDir: string, options: BundlingOptions) {
        if (canRunLocally) {
          // perform local bundling here
          return true;
        }
        return false;
      },
    },
    // Docker bundling fallback
    image: BundlingDockerImage.fromRegistry('alpine'),
    command: ['bundle'],
  },
});

Although optional, it's recommended to provide a local bundling method which can greatly improve performance.

CloudFormation Resource Metadata

NOTE: This section is relevant for authors of AWS Resource Constructs.

In certain situations, it is desirable for tools to be able to know that a certain CloudFormation resource is using a local asset. For example, SAM CLI can be used to invoke AWS Lambda functions locally for debugging purposes.

To enable such use cases, external tools will consult a set of metadata entries on AWS CloudFormation resources:

  • aws:asset:path points to the local path of the asset.
  • aws:asset:property is the name of the resource property where the asset is used

Using these two metadata entries, tools will be able to identify that assets are used by a certain resource, and enable advanced local experiences.

To add these metadata entries to a resource, use the asset.addResourceMetadata(resource, property) method.

See https://github.com/aws/aws-cdk/issues/1432 for more details

Keywords

FAQs

Last updated on 06 Nov 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc