Package: datadog-cdk-constructs-v2
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 your.NET,Java,Node.js, andPythonLambda 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 v2WARNING:AWS CDK v1has reached end-of-support anddatadog-cdk-constructswill no longer be receiving updates. It's strongly recommended to upgrade toAWS CDK v2(official migration guide) and switch to usingdatadog-cdk-constructs-v2.Two 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:import{Datadog}from"datadog-cdk-constructs-v2";constdatadog=newDatadog(this,"Datadog",{nodeLayerVersion:<LAYER_VERSION>,pythonLayerVersion:<LAYER_VERSION>,javaLayerVersion:<LAYER_VERSION>,dotnetLayerVersion:<LAYER_VERSION>addLayers:<BOOLEAN>,extensionLayerVersion:"<EXTENSION_VERSION>",forwarderArn:"<FORWARDER_ARN>",createForwarderPermissions:<BOOLEAN>,flushMetricsToLogs:<BOOLEAN>,site:"<SITE>",apiKey:"{Datadog_API_Key}",apiKeySecretArn:"{Secret_ARN_Datadog_API_Key}",apiKeySecret:<AWS_CDK_ISECRET>,//Onlyavailableindatadog-cdk-constructs-v2apiKmsKey:"{Encrypted_Datadog_API_Key}",enableDatadogTracing:<BOOLEAN>,enableMergeXrayTraces:<BOOLEAN>,enableDatadogLogs:<BOOLEAN>,injectLogContext:<BOOLEAN>,logLevel:<STRING>,env:<STRING>,//Optionalservice:<STRING>,//Optionalversion:<STRING>,//Optionaltags:<STRING>,//Optional});datadog.addLambdaFunctions([<LAMBDA_FUNCTIONS>])datadog.addForwarderToNonLambdaLogGroups([<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.constapp=newcdk.App();//Makesuretoadd@datadog/datadog-civiayourpackagemanagerconstdatadogCi=require("@datadog/datadog-ci");//ManuallyuploadingGitmetadatatoDatadog.datadogCi.gitMetadata.uploadGitCommitHash('{Datadog_API_Key}','<SITE>')constapp=newcdk.App();newExampleStack(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):asyncfunctionmain(){//Makesuretoadd@datadog/datadog-civiayourpackagemanagerconstdatadogCi=require("@datadog/datadog-ci");const[,gitHash]=awaitdatadogCi.gitMetadata.uploadGitCommitHash('{Datadog_API_Key}','<SITE>')constapp=newcdk.App();//PassinthehashtotheExampleStackconstructornewExampleStack(app,"ExampleStack",{},gitHash);}Ensure you call this function to initialize your stack.In your stack constructor, change to add an optionalgitHashparameter, and calladdGitCommitMetadata():exportclassExampleStackextendscdk.Stack{constructor(scope:cdk.App,id:string,props?:cdk.StackProps,gitHash?:string){......datadog.addGitCommitMetadata([<YOUR_FUNCTIONS>],gitHash)}}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 totrue. Whentrue, the Lambda Library version variables are also required. Whenfalse, you must include the Datadog Lambda library in your functions' deployment packages.pythonLayerVersionpython_layer_versionVersion of the Python Lambda layer to install, such as83. Required if you are deploying at least one Lambda function written in Python andaddLayersistrue. Find the latest version numberhere.nodeLayerVersionnode_layer_versionVersion of the Node.js Lambda layer to install, such as100. Required if you are deploying at least one Lambda function written in Node.js andaddLayersistrue. Find the latest version number fromhere.javaLayerVersionjava_layer_versionVersion of the Java layer to install, such as8. Required if you are deploying at least one Lambda function written in Java andaddLayersistrue. 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.dotnetLayerVersiondotnet_layer_versionVersion of the .NET layer to install, such as13. Required if you are deploying at least one Lambda function written in .NET andaddLayersistrue. Find the latest version number fromhere.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 Node.js 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 Node.js and Python. Defaults tofalse.encodeAuthorizerContextencode_authorizer_contextWhen set totruefor Lambda authorizers, the tracing context will be encoded into the response for propagation. Supported for Node.js 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 Node.js and Python. Defaults totrue.apmFlushDeadlineapm_flush_deadlineUsed 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 Node.js 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.import*aslambdafrom"aws-cdk-lib/aws-lambda";constlambda_function=newlambda.Function(this,"HelloHandler",{runtime:lambda.Runtime.NODEJS_14_X,code:lambda.Code.fromAsset("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.import{Datadog}from"datadog-cdk-constructs-v2";import*ascdkfrom"aws-cdk-lib";import{Construct}from"constructs";classRootStackextendscdk.Stack{constructor(scope:cdk.App,id:string,props?:cdk.StackProps){super(scope,id,props);newNestedStack(this,"NestedStack");constdatadog=newDatadog(this,"Datadog",{nodeLayerVersion:<LAYER_VERSION>,pythonLayerVersion:<LAYER_VERSION>,javaLayerVersion:<LAYER_VERSION>,dotnetLayerVersion:<LAYER-VERSION>,addLayers:<BOOLEAN>,forwarderArn:"<FORWARDER_ARN>",flushMetricsToLogs:<BOOLEAN>,site:"<SITE>",apiKey:"{Datadog_API_Key}",apiKeySecretArn:"{Secret_ARN_Datadog_API_Key}",apiKmsKey:"{Encrypted_Datadog_API_Key}",enableDatadogTracing:<BOOLEAN>,enableMergeXrayTraces:<BOOLEAN>,enableDatadogLogs:<BOOLEAN>,injectLogContext:<BOOLEAN>});datadog.addLambdaFunctions([<LAMBDA_FUNCTIONS>]);}}classNestedStackextendscdk.NestedStack{constructor(scope:Construct,id:string,props?:cdk.NestedStackProps){super(scope,id,props);constdatadog=newDatadog(this,"Datadog",{nodeLayerVersion:<LAYER_VERSION>,pythonLayerVersion:<LAYER_VERSION>,javaLayerVersion:<LAYER_VERSION>,dotnetLayerVersion:<LAYER-VERSION>,addLayers:<BOOLEAN>,forwarderArn:"<FORWARDER_ARN>",flushMetricsToLogs:<BOOLEAN>,site:"<SITE>",apiKey:"{Datadog_API_Key}",apiKeySecretArn:"{Secret_ARN_Datadog_API_Key}",apiKmsKey:"{Encrypted_Datadog_API_Key}",enableDatadogTracing:<BOOLEAN>,enableMergeXrayTraces:<BOOLEAN>,enableDatadogLogs:<BOOLEAN>,injectLogContext:<BOOLEAN>});datadog.addLambdaFunctions([<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');constsecret=Secret.fromSecretPartialArn(this,'DatadogApiKeySecret','arn:aws:secretsmanager:us-west-1:123:secret:DATADOG_API_KEY');constdatadog=newDatadog(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 for.NET,Java,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.