Package: datadog-cdk-constructs
Datadog CDK ConstructsUse this Datadog CDK Construct Library to deploy serverless applications using AWS CDK .This CDK library automatically configures ingestion of metrics, traces, and logs from your serverless applications by:Installing and configuring the Datadog Lambda layers for yourPython,Node.js, andJavaLambda functions.Enabling the collection of traces and custom metrics from your Lambda functions.Managing subscriptions from the Datadog Forwarder to your Lambda and non-Lambda log groups.AWS CDK v1 vs AWS CDK v2Two separate versions of Datadog CDK Constructs exist;datadog-cdk-constructsanddatadog-cdk-constructs-v2. These are designed to work withAWS CDK v1andAWS CDK v2respectively.datadog-cdk-constructs-v2requires Node >= 14, whiledatadog-cdk-constructssupports Node >= 12.datadog-cdk-constructs-v2contains more features.Otherwise, the use of the two packages is identical.npm Package Installation:For use with AWS CDK v2:yarn add --dev datadog-cdk-constructs-v2
# or
npm install datadog-cdk-constructs-v2 --save-devFor use with AWS CDK v1:yarn add --dev datadog-cdk-constructs
# or
npm install datadog-cdk-constructs --save-devPyPI Package Installation:For use with AWS CDK v2:pip install datadog-cdk-constructs-v2For use with AWS CDK v1:pip install datadog-cdk-constructsNote:Pay attention to the output from your package manager as theDatadog CDK Construct Libraryhas peer dependencies.UsageAWS CDKIf you are new to AWS CDK then check out thisworkshop.The following examples assume the use of AWS CDK v2. If you're using CDK v1, importdatadog-cdk-constructsrather thandatadog-cdk-constructs-v2.Add this to your CDK stack:# Example automatically generated from non-compiling source. May contain errors.fromdatadog_cdk_constructs_v2importDatadogdatadog=Datadog(self,"Datadog",node_layer_version=<LAYER_VERSION>,python_layer_version=<LAYER_VERSION>,java_layer_version=<LAYER_VERSION>,add_layers=<BOOLEAN>,extension_layer_version="<EXTENSION_VERSION>",forwarder_arn="<FORWARDER_ARN>",create_forwarder_permissions=<BOOLEAN>,flush_metrics_to_logs=<BOOLEAN>,site="<SITE>",api_key="{Datadog_API_Key}",api_key_secret_arn="{Secret_ARN_Datadog_API_Key}",api_key_secret=<AWS_CDK_ISECRET>,# Only available in datadog-cdk-constructs-v2api_kms_key="{Encrypted_Datadog_API_Key}",enable_datadog_tracing=<BOOLEAN>,enable_merge_xray_traces=<BOOLEAN>,enable_datadog_logs=<BOOLEAN>,inject_log_context=<BOOLEAN>,log_level=<STRING>,env=<STRING>,# Optionalservice=<STRING>,# Optionalversion=<STRING>,# Optionaltags=<STRING>)datadog.add_lambda_functions([<LAMBDA_FUNCTIONS>])datadog.add_forwarder_to_non_lambda_log_groups([<LOG_GROUPS>])Source Code IntegrationSource code integrationis enabled by default through automatic lambda tagging, and will work if:The Datadog Github Integration is installed.Your datadog-cdk dependency satisfies either of the below versions:datadog-cdk-constructs-v2>= 1.4.0datadog-cdk-constructs>= 0.8.5Alternative Methods to Enable Source Code IntegrationIf the automatic implementation doesn't work for your case, please follow one of the two guides below.Note: these alternate guides only work for Typescript.datadog-cdk version satisfied, but Datadog Github Integration NOT installedIf the Datadog Github Integration is not installed, you need to import thedatadog-cipackage and manually upload your Git metadata to Datadog.
We recommend you do this where your CDK Stack is initialized.# Example automatically generated from non-compiling source. May contain errors.app=cdk.App()# Make sure to add @datadog/datadog-ci via your package managerdatadog_ci=require("@datadog/datadog-ci")# Manually uploading Git metadata to Datadog.datadog_ci.git_metadata.upload_git_commit_hash("{Datadog_API_Key}","<SITE>")app=cdk.App()ExampleStack(app,"ExampleStack")app.synth()datadog-cdk version NOT satisfiedChange your initialization function as follows (note: we're changing this to pass just thegitHashvalue to the CDK):# Example automatically generated from non-compiling source. May contain errors.defmain():# Make sure to add @datadog/datadog-ci via your package managerdatadog_ci=require("@datadog/datadog-ci")[,gitHash]=awaitdatadogCi.gitMetadata.uploadGitCommitHash('{Datadog_API_Key}','<SITE>')app=cdk.App()# Pass in the hash to the ExampleStack constructorExampleStack(app,"ExampleStack",{},git_hash)Ensure you call this function to initialize your stack.In your stack constructor, change to add an optionalgitHashparameter, and calladdGitCommitMetadata():# Example automatically generated from non-compiling source. May contain errors.classExampleStack(cdk.Stack):def__init__(self,scope,id,props=None,git_hash=None):datadog.add_git_commit_metadata([<YOUR_FUNCTIONS>],git_hash)ConfigurationTo further configure your Datadog construct, use the following custom parameters:Note: The descriptions use the npm package parameters, but they also apply to the PyPI package parameters.npm package parameterPyPI package parameterDescriptionaddLayersadd_layersWhether to add the Lambda Layers or expect the user to bring their own. Defaults to true. When true, the Lambda Library version variables are also required. When false, you must include the Datadog Lambda library in your functions' deployment packages.pythonLayerVersionpython_layer_versionVersion of the Python Lambda layer to install, such as 21. Required if you are deploying at least one Lambda function written in Python andaddLayersis true. Find the latest version numberhere.nodeLayerVersionnode_layer_versionVersion of the Node.js Lambda layer to install, such as 29. Required if you are deploying at least one Lambda function written in Node.js andaddLayersis true. Find the latest version number fromhere.javaLayerVersionjava_layer_versionVersion of the Java layer to install, such as 8. Required if you are deploying at least one Lambda function written in Java andaddLayersis true. Find the latest version number in theServerless Java installation documentation.Note:extensionLayerVersion >= 25andjavaLayerVersion >= 5are required for the Datadog construct to instrument your Java functions properly.extensionLayerVersionextension_layer_versionVersion of the Datadog Lambda Extension layer to install, such as 5. WhenextensionLayerVersionis set,apiKey(or if encrypted,apiKMSKeyorapiKeySecretArn) needs to be set as well. When enabled, lambda function log groups will not be subscribed by the forwarder. Learn more about the Lambda extensionhere.forwarderArnforwarder_arnWhen set, the plugin will automatically subscribe the Datadog Forwarder to the functions' log groups. Do not setforwarderArnwhenextensionLayerVersionis set.createForwarderPermissionscreateForwarderPermissionsWhen set totrue, creates a Lambda permission on the the Datadog Forwarder per log group. Since the Datadog Forwarder has permissions configured by default, this is unnecessary in most use cases.flushMetricsToLogsflush_metrics_to_logsSend custom metrics using CloudWatch logs with the Datadog Forwarder Lambda function (recommended). Defaults totrue. If you disable this parameter, it's required to setapiKey(or if encrypted,apiKMSKeyorapiKeySecretArn).sitesiteSet which Datadog site to send data. This is only used whenflushMetricsToLogsisfalseorextensionLayerVersionis set. Possible values aredatadoghq.com,datadoghq.eu,us3.datadoghq.com,us5.datadoghq.com,ap1.datadoghq.com, andddog-gov.com. The default isdatadoghq.com.apiKeyapi_keyDatadog API Key, only needed whenflushMetricsToLogsisfalseorextensionLayerVersionis set. For more information about getting a Datadog API key, see theAPI key documentation.apiKeySecretArnapi_key_secret_arnThe ARN of the secret storing the Datadog API key in AWS Secrets Manager. Use this parameter in place ofapiKeywhenflushMetricsToLogsisfalseorextensionLayeris set. Remember to add thesecretsmanager:GetSecretValuepermission to the Lambda execution role.apiKeySecretapi_key_secretAnAWS CDK ISecretrepresenting a secret storing the Datadog API key in AWS Secrets Manager. Use this parameter in place ofapiKeySecretArnto automatically grant your Lambda execution roles read access to the given secret.See herefor an example.Only available in datadog-cdk-constructs-v2.apiKmsKeyapi_kms_keyDatadog API Key encrypted using KMS. Use this parameter in place ofapiKeywhenflushMetricsToLogsisfalseorextensionLayerVersionis set, and you are using KMS encryption.enableDatadogTracingenable_datadog_tracingEnable Datadog tracing on your Lambda functions. Defaults totrue.enableMergeXrayTracesenable_merge_xray_tracesEnable merging X-Ray traces on your Lambda functions. Defaults tofalse.enableDatadogLogsenable_datadog_logsSend Lambda function logs to Datadog via the Datadog Lambda Extension.  Defaults totrue. Note: This setting has no effect on logs sent via the Datadog Forwarder.enableSourceCodeIntegrationenable_source_code_integrationEnable Datadog Source Code Integration, connecting your telemetry with application code in your Git repositories. This requires the Datadog Github Integration to work, otherwise please follow thealternative method. Learn morehere. Defaults totrue.injectLogContextinject_log_contextWhen set, the Lambda layer will automatically patch console.log with Datadog's tracing ids. Defaults totrue.logLevellog_levelWhen set todebug, the Datadog Lambda Library and Extension will log additional information to help troubleshoot issues.envenvWhen set along withextensionLayerVersion, aDD_ENVenvironment variable is added to all Lambda functions with the provided value. When set along withforwarderArn, anenvtag is added to all Lambda functions with the provided value.serviceserviceWhen set along withextensionLayerVersion, aDD_SERVICEenvironment variable is added to all Lambda functions with the provided value. When set along withforwarderArn, aservicetag is added to all Lambda functions with the provided value.versionversionWhen set along withextensionLayerVersion, aDD_VERSIONenvironment variable is added to all Lambda functions with the provided value. When set along withforwarderArn, aversiontag is added to all Lambda functions with the provided value.tagstagsA comma separated list of key:value pairs as a single string. When set along withextensionLayerVersion, aDD_TAGSenvironment variable is added to all Lambda functions with the provided value. When set along withforwarderArn, the cdk parses the string and sets each key:value pair as a tag to all Lambda functions.enableColdStartTracingenable_cold_start_tracingSet tofalseto disable Cold Start Tracing. Used in NodeJS and Python. Defaults totrue.coldStartTraceMinDurationmin_cold_start_trace_durationSets the minimum duration (in milliseconds) for a module load event to be traced via Cold Start Tracing. Number. Defaults to3.coldStartTraceSkipLibscold_start_trace_skip_libsOptionally skip creating Cold Start Spans for a comma-separated list of libraries. Useful to limit depth or skip known libraries. Default depends on runtime.enableProfilingenable_profilingEnable the Datadog Continuous Profiler withtrue. Supported in Beta for NodeJS and Python. Defaults tofalse.encodeAuthorizerContextencode_authorizer_contextWhen set totruefor Lambda authorizers, the tracing context will be encoded into the response for propagation. Supported for NodeJS and Python. Defaults totrue.decodeAuthorizerContextdecode_authorizer_contextWhen set totruefor Lambdas that are authorized via Lambda authorizers, it will parse and use the encoded tracing context (if found). Supported for NodeJS and Python. Defaults totrue.apmFlushDeadlineUsed to determine when to submit spans before a timeout occurs, in milliseconds. When the remaining time in an AWS Lambda invocation is less than the value set, the tracer attempts to submit the current active spans and all finished spans. Supported for NodeJS and Python. Defaults to100milliseconds.redirectHandlerredirect_handlerWhen set tofalse, skip redirecting handler to the Datadog Lambda Library's handler. Useful when only instrumenting with Datadog Lambda Extension. Defaults totrue.Note: Using the parameters above may override corresponding function levelDD_XXXenvironment variables.TracingEnable X-Ray Tracing on your Lambda functions. For more information, seeCDK documentation.# Example automatically generated from non-compiling source. May contain errors.importaws_cdk_lib.aws_lambdaaslambda_lambda_function=lambda_.Function(self,"HelloHandler",runtime=lambda_.Runtime.NODEJS_14_X,code=lambda_.Code.from_asset("lambda"),handler="hello.handler",tracing=lambda_.Tracing.ACTIVE)Nested StacksAdd the Datadog CDK Construct to each stack you wish to instrument with Datadog. In the example below, we initialize the Datadog CDK Construct and calladdLambdaFunctions()in both theRootStackandNestedStack.# Example automatically generated from non-compiling source. May contain errors.fromdatadog_cdk_constructs_v2importDatadogimportaws_cdk_libascdkfromconstructsimportConstructclassRootStack(cdk.Stack):def__init__(self,scope,id,props=None):super().__init__(scope,id,props)NestedStack(self,"NestedStack")datadog=Datadog(self,"Datadog",node_layer_version=<LAYER_VERSION>,python_layer_version=<LAYER_VERSION>,java_layer_version=<LAYER_VERSION>,add_layers=<BOOLEAN>,forwarder_arn="<FORWARDER_ARN>",flush_metrics_to_logs=<BOOLEAN>,site="<SITE>",api_key="{Datadog_API_Key}",api_key_secret_arn="{Secret_ARN_Datadog_API_Key}",api_kms_key="{Encrypted_Datadog_API_Key}",enable_datadog_tracing=<BOOLEAN>,enable_merge_xray_traces=<BOOLEAN>,enable_datadog_logs=<BOOLEAN>,inject_log_context=<BOOLEAN>)datadog.add_lambda_functions([<LAMBDA_FUNCTIONS>])classNestedStack(cdk.NestedStack):def__init__(self,scope,id,props=None):super().__init__(scope,id,props)datadog=Datadog(self,"Datadog",node_layer_version=<LAYER_VERSION>,python_layer_version=<LAYER_VERSION>,java_layer_version=<LAYER_VERSION>,add_layers=<BOOLEAN>,forwarder_arn="<FORWARDER_ARN>",flush_metrics_to_logs=<BOOLEAN>,site="<SITE>",api_key="{Datadog_API_Key}",api_key_secret_arn="{Secret_ARN_Datadog_API_Key}",api_kms_key="{Encrypted_Datadog_API_Key}",enable_datadog_tracing=<BOOLEAN>,enable_merge_xray_traces=<BOOLEAN>,enable_datadog_logs=<BOOLEAN>,inject_log_context=<BOOLEAN>)datadog.add_lambda_functions([<LAMBDA_FUNCTIONS>])TagsAdd tags to your constructs. We recommend setting anenvandservicetag to tie Datadog telemetry together. For more information seeofficial AWS documentationandCDK documentation.Automatically grant AWS secret read access to Lambda execution roleOnly available in datadog-cdk-constructs-v2To automatically grant your Lambda execution roles read access to a given secret, pass inapiKeySecretin place ofapiKeySecretArnwhen initializing the Datadog construct.const { Secret } = require('aws-cdk-lib/aws-secretsmanager');

const secret = Secret.fromSecretPartialArn(this, 'DatadogApiKeySecret', 'arn:aws:secretsmanager:us-west-1:123:secret:DATADOG_API_KEY');

const datadog = new Datadog(this, 'Datadog', {
  ...
  apiKeySecret: secret
  ...
});WhenaddLambdaFunctionsis called, the Datadog CDK construct grants your Lambda execution roles read access to the given AWS secret. This is done through theAWS ISecret's grantRead function.How it worksThe Datadog CDK construct takes in a list of lambda functions and installs the Datadog Lambda Library by attaching the Lambda Layers forJava,Node.js, andPythonto your functions. It redirects to a replacement handler that initializes the Lambda Library without any required code changes. Additional configurations added to the Datadog CDK construct will also translate into their respective environment variables under each lambda function (if applicable / required).While Lambda function based log groups are handled by theaddLambdaFunctionsmethod automatically, the construct has an additional functionaddForwarderToNonLambdaLogGroupswhich subscribes the forwarder to any additional log groups of your choosing.Resources to learn about CDKCDK TypeScript WorkshopVideo Introducing CDK by AWS with DemoCDK ConceptsRepository StructureIn this repository, the foldersv1andv2correspond to the packagesdatadog-cdk-constructsanddatadog-cdk-contructs-v2. Each can be treated as a separate project (they are separate projen projects with separate dependencies, config files, tests, and scripts).Additionally, there is acommonfolder that contains shared logic common to bothv1andv2packages. This is done by soft-linking acommonfolder withinv1/srcandv2/srcto thecommonfolder in the root of the repository.Using ProjenThev1andv2Datadog CDK Construct Libraries both use Projen to maintain project configuration files such as thepackage.json,.gitignore,.npmignore, etc. Most of the configuration files will be protected by Projen via read-only permissions. In order to change these files, edit the.projenrc.jsfile withinv1orv2folders, then runnpx projen(while inv1orv2) to synthesize the new changes. Check outProjenfor more details.Opening IssuesIf you encounter a bug with this package, we want to hear about it. Before opening a new issue, search the existing issues to avoid duplicates.When opening an issue, include the Datadog CDK Construct version, Node version, and stack trace if available. In addition, include the steps to reproduce when appropriate.You can also open an issue for a feature request.ContributingIf you find an issue with this package and have a fix, please feel free to open a pull request following theprocedures.TestingIf you contribute to this package you can run the tests usingyarn testwithin thev1orv2folders. This package also includes a sample application for manual testing:Open a seperate terminal andcdintov1orv2.Runyarn watch, this will ensure the Typescript files in thesrcdirectory are compiled to Javascript in thelibdirectory.Navigate tosrc/sample, here you can editindex.tsto test your contributions manually.At the root of thev1orv2directory (whichever you are working on), runnpx cdk --app lib/sample/index.js <CDK Command>, replacing<CDK Command>with common CDK commands likesynth,diff, ordeploy.Note, if you receive "... is not authorized to perform: ..." you may also need to authorize the commands with your AWS credentials.Debug LogsTo display the debug logs for this library, set theDD_CONSTRUCT_DEBUG_LOGSenv var totruewhen runningcdk synth(use--quietto suppress generated template output).Example:Ensure you are at the root of thev1orv2directoryDD_CONSTRUCT_DEBUG_LOGS=true npx cdk --app lib/sample/index.js synth --quietCommunityFor product feedback and questions, join the#serverlesschannel in theDatadog community on Slack.LicenseUnless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.