Skip to content

Latest commit

 

History

History
431 lines (307 loc) · 15.6 KB

File metadata and controls

431 lines (307 loc) · 15.6 KB

|cdk| Tools

Command-line Toolkit (cdk)

cdk (the |toolkit|) is the main tool you use to interact with your |*CDK App*|. It executes the CDK app you have written and compiled, interrogates the application model you have defined, and produces and deploys the |CFN| templates generated by the |cdk|.

There are two ways that you can tell cdk what command to use to run your CDK app. The first way is to include an explicit --app option whenever you use a cdk command:

cdk --app 'node bin/main.js' synth

The second way is to add the following entry to the file cdk.json:

{
   "app": "node bin/main.js"
}

Here are the actions you can take on your CDK app (this is the output of the cdk --help command):

Usage: cdk -a <cdk-app> COMMAND

Commands:
  list                        Lists all stacks in the app          [aliases: ls]
  synthesize [STACKS..]       Synthesizes and prints the CloudFormation template
                              for this stack                    [aliases: synth]
  bootstrap [ENVIRONMENTS..]  Deploys the CDK toolkit stack into an AWS
                              environment
  deploy [STACKS..]           Deploys the stack(s) named STACKS into your AWS
                              account
  destroy [STACKS..]          Destroy the stack(s) named STACKS
  diff [STACK]                Compares the specified stack with the deployed
                              stack or a local template file
  metadata [STACK]            Returns all metadata associated with this stack
  init [TEMPLATE]             Create a new, empty CDK project from a template.
                              Invoked without TEMPLATE, the app template will be
                              used.
  docs                        Opens the documentation in a browser[aliases: doc]
  doctor                      Check your set-up for potential problems

Options:
  --app, -a            REQUIRED: Command-line for executing your CDK app (e.g.
                       "node bin/my-app.js")                            [string]
  --context, -c        Add contextual string parameter.                  [array]
  --plugin, -p         Name or path of a node package that extend the CDK
                       features. Can be specified multiple times         [array]
  --rename             Rename stack name if different from the one defined in
                       the cloud executable                             [string]
  --trace              Print trace for stack warnings                  [boolean]
  --strict             Do not construct stacks with warnings           [boolean]
  --ignore-errors      Ignores synthesis errors, which will likely produce an
                       invalid output                 [boolean] [default: false]
  --json, -j           Use JSON output instead of YAML                 [boolean]
  --verbose, -v        Show debug logs                                 [boolean]
  --profile            Use the indicated AWS profile as the default environment
                                                                        [string]
  --proxy              Use the indicated proxy. Will read from HTTPS_PROXY
                       environment variable if not specified.           [string]
  --ec2creds, -i       Force trying to fetch EC2 instance credentials. Default:
                       guess EC2 instance status.                      [boolean]
  --version-reporting  Disable insersion of the CDKMetadata resource in
                       synthesized templates                           [boolean]
  --role-arn, -r       ARN of Role to use when invoking CloudFormation  [string]
  --version            Show version number                             [boolean]
  --help               Show help                                       [boolean]

If your app has a single stack, there is no need to specify the stack name

If one of cdk.json or ~/.cdk.json exists, options specified there will be used
as defaults. Settings in cdk.json take precedence.

Configuration

The CDK toolkit resolves its configuration by reading files in the following order:

  1. ~/.cdk.json: user-level configuration file
  2. cdk.json: project configuration file
  3. Command line arguments

The following options are supported in cdk.json:

  • app (string): the command-line to use in order to invoke your CDK app.
  • browser (string): the command to use to open the browser, using %u as a placeholder for the path of the file to open
  • context (hash): key-value pairs of context values which can later be read by Construct.getContext(key)
  • language (string): programming langauge to use for cdk-init
  • pathMetadata (boolean): Include "aws:cdk:path" CloudFormation metadata for each resource (enabled by default)
  • plugin (array): Name or path of a node package that extend the CDK features
  • requireApproval (string): what security-sensitive changes need manual approval (choices: "never", "any-change", "broadening")
  • toolkitStackName (string): the name of the CDK toolkit stack
  • versionReporting (boolean): Include the "AWS::CDK::Metadata" resource in synthesized templates

Security-related changes

In order to protect you against unintended changes that affect your security posture, the CDK toolkit will prompt you to approve security-related changes before deploying them.

You change the level of changes that requires approval by specifying:

cdk deploy --require-approval LEVEL

Where LEVEL can be one of:

  • never - approval is never required.
  • any-change - require approval on any IAM or security-group related change.
  • broadening (default) - require approval when IAM statements or traffic rules are added. Removals do not require approval.

The setting also be configured in cdk.json:

{
    "app": "...",
    "requireApproval": "never"
}

Version Reporting

In order to gain insights in how the |cdk| is used, the versions of libraries used by |cdk| applications are collected and reported using a resource identified as AWS::CDK::Metadata that is added to CloudFormation templates, and can easily be reviewed. This information may also be used to identify stacks using a package with known serious security or reliability issues and contact their users with important information.

The |cdk| reports the name and version of npm modules that are loaded into the application at synthesis time, unless their package.json file contains the "private": true attribute.

The AWS::CDK::Metadata resource looks like the following:

CDKMetadata:
  Type: "AWS::CDK::Metadata"
  Properties:
    Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10"

Opting-out from Version Reporting

To out-out, use one of the following methods:

  • Use the --no-version-reporting in cdk invocations:

    cdk --no-version-reporting synth
  • Set versionReporting to false in ./cdk.json or ~/cdk.json:

    {
      "app": "...",
      "versionReporting": false
    }

Plugins

The |cdk| toolkit provides extension points that enable users to augment the features provided by the toolkit. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as the needs arise.

Loading Plugins

Plugins can be loaded by providing the Node module name (or path) to the CDK toolkit:

  1. Using the --plugin command line option (which can be specified multiple times):

    $ cdk list --plugin=module
    $ cdk deploy --plugin=module_1 --plugin=module_2
  2. Adding entries to the ~/.cdk.json or cdk.json file:

    {
      // ...
      "plugin": [
          "module_1",
          "module_2"
      ],
      // ...
    }

Authoring Plugins

Plugins must be authored in TypeScript or Javascript, and are defined by implementing a Node module that implements the following protocol, and using :js:class:`~aws-cdk.PluginHost` methods:

.. tabs::
    .. code-tab:: typescript

        import cdk = require('aws-cdk');

        export = {
            version: '1', // Version of the plugin infrastructure (currently always '1')
            init(host: cdk.PluginHost): void {
                // Your plugin initialization hook.
                // Use methods of ``host`` to register custom code with the CDK toolkit
            }
        };

    .. code-tab:: javascript

        export = {
            version: '1', // Version of the plugin infrastructure (currently always '1')
            init(host) {
                // Your plugin initialization hook.
                // Use methods of ``host`` to register custom code with the CDK toolkit
            }
        };

Credential Provider Plugins

Custom credential providers are classes implementing the :js:class:`~aws-cdk.CredentialProviderSource` interface, and registered to the toolkit using the :js:func:`~aws-cdk.PluginHost.registerCredentialProviderSource` method.

.. tabs::
   .. code-tab:: typescript

      import cdk = require('aws-cdk');
      import aws = require('aws-sdk');

      class CustomCredentialProviderSource implements cdk.CredentialProviderSource {
        public async isAvailable(): Promise<boolean> {
          // Return ``false`` if the plugin could determine it cannot be used (for example,
          // if it depends on files that are not present on this host).
          return true;
        }

        public async canProvideCredentials(accountId: string): Promise<boolean> {
          // Return ``false`` if the plugin is unable to provide credentials for the
          // requested account (for example if it's not managed by the credentials
          // system that this plugin adds support for).
          return true;
        }

        public async getProvider(accountId: string, mode: cdk.Mode): Promise<aws.Credentials> {
          let credentials: aws.Credentials;
          // Somehow obtain credentials in ``credentials``, and return those.
          return credentials;
        }
      }

      export = {
        version = '1',
        init(host: cdk.PluginHost): void {
          // Register the credential provider to the PluginHost.
          host.registerCredentialProviderSource(new CustomCredentialProviderSource());
        }
      };

   .. code-tab:: javascript

      class CustomCredentialProviderSource {
        async isAvailable() {
          // Return ``false`` if the plugin could determine it cannot be used (for example,
          // if it depends on files that are not present on this host).
          return true;
        }

        async canProvideCredentials(accountId) {
          // Return ``false`` if the plugin is unable to provide credentials for the
          // requested account (for example if it's not managed by the credentials
          // system that this plugin adds support for).
          return true;
        }

        async getProvider(accountId, mode) {
          let credentials;
          // Somehow obtain credentials in ``credentials``, and return those.
          return credentials;
        }
      }

      export = {
        version = '1',
        init(host) {
          // Register the credential provider to the PluginHost.
          host.registerCredentialProviderSource(new CustomCredentialProviderSource());
        }
      };

Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence it is strongly advised that the credentials objects returned are self-refreshing, as descibed in the AWS SDK for Javascript documentation.

Reference

.. js:module:: aws-cdk

CredentialProviderSource (interface)

.. js:class:: CredentialProviderSource

   .. js:attribute:: name

      A friendly name for the provider, which will be used in error messages, for example.

      :type: ``string``

   .. js:method:: isAvailable()

      Whether the credential provider is even online. Guaranteed to be called before any of the other functions are called.

      :returns: ``Promise<boolean>``

   .. js:method:: canProvideCredentials(accountId)

      Whether the credential provider can provide credentials for the given account.

      :param string accountId: the account ID for which credentials are needed.
      :returns: ``Promise<boolean>``

   .. js:method:: getProvider(accountId, mode)

      Construct a credential provider for the given account and the given access mode.
      Guaranteed to be called only if canProvideCredentails() returned true at some point.

      :param string accountId: the account ID for which credentials are needed.
      :param aws-cdk.Mode mode: the kind of operations the credentials are intended to perform.
      :returns: ``Promise<aws.Credentials>``

Mode (enum)

.. js:class:: Mode

   .. js:data:: ForReading

      Credentials are inteded to be used for read-only scenarios.

   .. js:data:: ForWriting

      Credentials are intended to be used for read-write scenarios.

Plugin (interface)

.. js:class:: Plugin()

   .. js:attribute:: version

      The version of the plug-in interface used by the plug-in. This will be used by
      the plug-in host to handle version changes. Currently, the only valid value for
      this attribute is ``'1'``.

      :type: ``string``

   .. js:method:: init(host)

      When defined, this function is invoked right after the plug-in has been loaded,
      so that the plug-in is able to initialize itself. It may call methods of the
      :js:class:`~aws-cdk.PluginHost` instance it receives to register new
      :js:class:`~aws-cdk.CredentialProviderSource` instances.

      :param aws-cdk.PluginHost host: The |cdk| plugin host
      :returns: ``void``

PluginHost

.. js:class:: PluginHost()

   .. js:data:: instance

      :type: :js:class:`~aws-cdk.PluginHost`

   .. js:method:: load(moduleSpec)

      Loads a plug-in into this PluginHost.

      :param string moduleSpec: the specification (path or name) of the plug-in module to be loaded.
      :throws Error: if the provided ``moduleSpec`` cannot be loaded or is not a valid :js:class:`~aws-cdk.Plugin`.
      :returns: ``void``

   .. js:method:: registerCredentialProviderSource(source)

      Allows plug-ins to register new :js:class:`~aws-cdk.CredentialProviderSources`.

      :param aws-cdk.CredentialProviderSources source: a new CredentialProviderSource to register.
      :returns: ``void``