AWS/CDK

[AWS CDK] DEFINE RESOURCES

brightlightkim 2022. 3. 29. 05:34

Add resources to the hit counter construct

Now, let’s define the AWS Lambda function and the DynamoDB table in our HitCounter construct.

 

Windows users: on Windows, you will have to stop the npm run watch command that is running in the background, then run npm install, then start npm run watch again. Otherwise you will get an error about files being in use.

 

Now, go back to lib/hitcounter.ts and add the following highlighted code:

import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { Construct } from 'constructs';

export interface HitCounterProps {
  /** the function for which we want to count url hits **/
  downstream: lambda.IFunction;
}

export class HitCounter extends Construct {

  /** allows accessing the counter function */
  public readonly handler: lambda.Function;

  constructor(scope: Construct, id: string, props: HitCounterProps) {
    super(scope, id);

    const table = new dynamodb.Table(this, 'Hits', {
        partitionKey: { name: 'path', type: dynamodb.AttributeType.STRING }
    });

    this.handler = new lambda.Function(this, 'HitCounterHandler', {
        runtime: lambda.Runtime.NODEJS_14_X,
        handler: 'hitcounter.handler',
        code: lambda.Code.fromAsset('lambda'),
        environment: {
            DOWNSTREAM_FUNCTION_NAME: props.downstream.functionName,
            HITS_TABLE_NAME: table.tableName
        }
    });
  }
}

What did we do here?

This code is hopefully quite easy to understand:

  • We defined a DynamoDB table with path as the partition key.
  • We defined a Lambda function which is bound to the lambda/hitcounter.handler code.
  • We wired the Lambda’s environment variables to the functionName and tableName of our resources.

Late-bound values

The functionName and tableName properties are values that only resolve when we deploy our stack (notice that we haven’t configured these physical names when we defined the table/function, only logical IDs). This means that if you print their values during synthesis, you will get a “TOKEN”, which is how the CDK represents these late-bound values. You should treat tokens as opaque strings. This means you can concatenate them together for example, but don’t be tempted to parse them in your code.

'AWS > CDK' 카테고리의 다른 글

[AWS CDK] Granting Permissions  (0) 2022.03.29
[AWS CDK] CLOUDWATCH LOGS  (0) 2022.03.29
[AWS CDK] HIT COUNTER HANDLER  (0) 2022.03.29
[AWS CDK] DEFINE THE HITCOUNTER API  (0) 2022.03.29
[AWS CDK] Writing Constructs  (0) 2022.03.29