

 [AWS SDK for JavaScript V3 API 참조 안내서](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)는 AWS SDK for JavaScript 버전 3(V3)의 모든 API 작업을 자세히 설명합니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS Lambda 함수를 실행하기 위한 예약된 이벤트 생성
<a name="scheduled-events-invoking-lambda-example"></a>

Amazon CloudWatch 이벤트를 사용하여 AWS Lambda 함수를 호출하는 예약된 이벤트를 생성할 수 있습니다. cron 표현식을 사용하여 Lambda 함수가 간접적으로 호출되는 시기를 예약하도록 CloudWatch 이벤트를 구성할 수 있습니다. 예를 들어 평일마다 Lambda 함수를 간접적으로 호출하도록 CloudWatch 이벤트를 예약할 수 있습니다.

AWS Lambda 는 서버를 프로비저닝하거나 관리하지 않고도 코드를 실행할 수 있는 컴퓨팅 서비스입니다. 다양한 프로그래밍 언어로 Lambda 함수를 생성할 수 있습니다. 에 대한 자세한 내용은 [란 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 무엇입니까?를 AWS Lambda참조하십시오.

이 자습서에서는 Lambda JavaScript 런타임 API를 사용하여 Lambda 함수를 생성합니다. 이 예제에서는 다양한 AWS 서비스를 호출하여 특정 사용 사례를 수행합니다. 예를 들어 다음 그림과 같이 조직에서 1주년을 맞이하는 직원들에게 축하하는 모바일 문자 메시지를 보낸다고 가정해 보겠습니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picPhone.png)


이 자습서를 완료하는 데 약 20분 정도 걸립니다.

이 자습서에서는 JavaScript 로직을 사용하여 이 사용 사례를 수행하는 솔루션을 생성하는 방법을 보여줍니다. 예를 들어 Lambda 함수를 사용하여 데이터베이스를 읽어 1주년 기념일을 맞이한 직원을 확인하는 방법, 데이터를 처리하고 문자 메시지를 보내는 방법을 모두 알아봅니다. 그런 다음, cron 표현식을 사용하여 평일마다 Lambda 함수를 간접적으로 호출하는 방법을 알아봅니다.

이 AWS 자습서에서는 이러한 필드가 포함된 Employee이라는 Amazon DynamoDB 테이블을 사용합니다.
+ **id** - 테이블의 프라이머리 키입니다.
+ **firstName** –직원의 이름입니다.
+ **phone** –직원의 전화번호입니다.
+ **startDate** – 직원의 시작 날짜입니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/pic00.png)


**중요**  
완료 비용:이 문서에 포함된 AWS 서비스는 AWS 프리 티어에 포함됩니다. 하지만 요금이 부과되지 않도록 하려면 이 자습서를 완료한 후에 모든 리소스를 종료해야 합니다.

**앱을 빌드하려면 다음을 수행합니다.**

1. [사전 조건 완료 ](#scheduled-events-invoking-lambda-provision-resources)

1. [AWS 리소스 생성 ](#scheduled-events-invoking-lambda-provision-resources)

1. [브라우저 스크립트 준비 ](#scheduled-events-invoking-lambda-browser-script)

1. [Lambda 함수 생성 및 업로드 ](#scheduled-events-invoking-lambda-browser-script)

1. [Lambda 함수 배포 ](#scheduled-events-invoking-lambda-deploy-function)

1. [앱 실행](#scheduled-events-invoking-lambda-run)

1. [리소스 삭제](#scheduled-events-invoking-lambda-destroy)

## 사전 필수 작업
<a name="scheduled-events-invoking-lambda-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 Node.js TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.

## AWS 리소스 생성
<a name="scheduled-events-invoking-lambda-provision-resources"></a>

이 자습서를 시작하려면 다음 리소스가 필요합니다.
+ 이전 그림에 나와 있는 필드와 **Id**라는 키가 있는 **Employee**라는 Amazon DynamoDB 테이블. 이 사용 사례를 테스트하려는 유효한 휴대폰을 포함해 올바른 데이터를 입력했는지 확인하세요. 자세한 내용은 [테이블 생성](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)을 참조하세요.
+ Lambda 함수를 실행하기 위한 권한이 연결된 IAM 역할.
+ Lambda 함수를 호스팅하는 Amazon S3 버킷.

이러한 리소스를 수동으로 생성할 수 있지만이 자습서에 설명된 CloudFormation 대로를 사용하여 이러한 리소스를 프로비저닝하는 것이 좋습니다.

### 를 사용하여 AWS 리소스 생성 CloudFormation
<a name="scheduled-events-invoking-lambda-resources-cli"></a>

CloudFormation 를 사용하면 AWS 인프라 배포를 예측 가능하고 반복적으로 생성하고 프로비저닝할 수 있습니다. 에 대한 자세한 내용은 [AWS CloudFormation 사용 설명서를](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) CloudFormation참조하세요.

를 사용하여 CloudFormation 스택을 생성하려면 AWS CLI:

1. [AWS CLI 사용 설명서](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)의 AWS CLI 지침에 따라를 설치하고 구성합니다.

1. 프로젝트 폴더의 루트 디렉터리에 이름이 `setup.yaml`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/setup.yaml) 내용을 해당 파일에 복사합니다.
**참고**  
 CloudFormation 템플릿은 [ GitHub에서 사용할](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/resources/cdk/lambda_using_scheduled_events) 수 있는를 AWS CDK 사용하여 생성되었습니다. 에 대한 자세한 내용은 [AWS Cloud Development Kit (AWS CDK) 개발자 안내서](https://docs.aws.amazon.com/cdk/latest/guide/)를 AWS CDK참조하세요.

1. 명령줄에서 다음 명령을 실행하여 *STACK\$1NAME*을 스택의 고유한 이름으로 바꿉니다.
**중요**  
스택 이름은 AWS 리전 및 AWS 계정 내에서 고유해야 합니다. 최대 128자까지 지정할 수 있으며 숫자와 하이픈을 사용할 수 있습니다.

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   `create-stack` 명령 파라미터에 대한 자세한 내용은 [AWS CLI 명령 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 및 [CloudFormation 사용 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)를 참조하세요.

    CloudFormation 대시보드에서 스택을 열고 리소스 탭을 선택하여 콘솔의 **리소스** 목록을 봅니다. 자습서에는 이러한 정보가 필요합니다.

1. 스택이 생성되면에 설명된 대로 AWS SDK for JavaScript 를 사용하여 DynamoDB 테이블을 채웁니다[DynamoDB 테이블 채우기](#scheduled-events-invoking-lambda-resources-create-table).

### DynamoDB 테이블 채우기
<a name="scheduled-events-invoking-lambda-resources-create-table"></a>

테이블을 채우려면 먼저, 이름이 `libs`인 디렉터리를 생성하고 이 디렉터리 안에 이름이 `dynamoClient.js`인 파일을 생성한 다음, 아래 내용을 해당 파일에 붙여 넣습니다.

```
const { DynamoDBClient } = require( "@aws-sdk/client-dynamodb" );
// Set the AWS Region.
const REGION = "REGION"; // e.g. "us-east-1"
// Create an Amazon DynamoDB service client object.
const dynamoClient = new DynamoDBClient({region:REGION});
module.exports = { dynamoClient };
```

 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js) 제공합니다.

다음으로, 프로젝트 폴더의 루트 디렉터리에 이름이 `populate-table.js`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js) 내용을 해당 파일에 복사합니다. 항목 중 하나에 대해 `phone` 속성의 값을 E.164 형식의 유효한 휴대폰 번호로 바꾸고 `startDate`의 값을 오늘 날짜로 바꿉니다.

명령줄에서 다음 명령을 실행합니다.

```
node populate-table.js
```

```
const {
BatchWriteItemCommand } = require( "aws-sdk/client-dynamodb" );
const {dynamoClient} = require(  "./libs/dynamoClient" );
// Set the parameters.
const params = {
  RequestItems: {
    Employees: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            firstName: { S: "Bob" },
            phone: { N: "155555555555654" },
            startDate: { S: "2019-12-20" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            firstName: { S: "Xing" },
            phone: { N: "155555555555653" },
            startDate: { S: "2019-12-17" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "55" },
            firstName: { S: "Harriette" },
            phone: { N: "155555555555652" },
            startDate: { S: "2019-12-19" },
          },
        },
      },
    ],
  },
};

export const run = async () => {
  try {
    const data = await dbclient.send(new BatchWriteItemCommand(params));
    console.log("Success", data);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js) 제공합니다.

## AWS Lambda 함수 생성
<a name="scheduled-events-invoking-lambda-browser-script"></a>

### SDK 구성
<a name="scheduled-events-invoking-lambda-configure-sdk"></a>

먼저 필수 AWS SDK for JavaScript (v3) 모듈 및 명령과 `DynamoDBClient` DynamoDB `ScanCommand` `SNSClient` 및 Amazon SNS `PublishCommand` 명령을 가져옵니다. *REGION*을 AWS 리전으로 바꿉니다. 그런 다음, 오늘 날짜를 계산하여 파라미터에 할당합니다. 다음으로, `ScanCommand`.Replace *TABLE\$1NAME*의 파라미터를 이 예의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 섹션에서 생성한 테이블 이름을 사용해 생성합니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [Lambda 함수 번들링](#scheduled-events-invoking-lambda-full) 섹션을 참조하세요.)

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};
```

### DynamoDB 테이블 스캔
<a name="scheduled-events-invoking-lambda-scan-table"></a>

먼저, Amazon SNS `PublishCommand`를 사용하여 텍스트 메시지를 게시하는 `sendText`라는 async/await 함수를 생성합니다. 그런 다음, DynamoDB 테이블을 스캔하여 오늘이 근무 기념일인 직원을 찾은 후 `sendText` 함수를 직접적으로 호출하여 해당 직원에게 문자 메시지를 보내는 `try` 블록 패턴을 추가합니다. 오류가 발생하면 `catch` 블록이 직접적으로 호출됩니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [Lambda 함수 번들링](#scheduled-events-invoking-lambda-full) 섹션을 참조하세요.)

```
exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

### Lambda 함수 번들링
<a name="scheduled-events-invoking-lambda-full"></a>

이 주제에서는 `mylambdafunction.js` 및이 예제에 필요한 AWS SDK for JavaScript 모듈을 라는 번들 파일로 번들링하는 방법을 설명합니다`index.js`.

1. webpack을 아직 설치하지 않았다면 이 예의 [사전 필수 작업](#scheduled-events-invoking-lambda-prerequisites)에 따라 설치합니다.
**참고**  
*Webpack*에 관한 자세한 내용은 [Webpack으로 애플리케이션 번들링](webpack.md) 단원을 참조하세요.

1. 명령줄에서 다음을 실행하여 이 예의 JavaScript를 `<index.js>`라는 파일로 번들링합니다.

   ```
   webpack mylamdbafunction.js --mode development --target node --devtool false --output-library-target umd -o index.js
   ```
**중요**  
출력 이름이 `index.js`인 것에 주목하세요. 이는 Lambda 함수가 작동하려면 `index.js` 핸들러가 있어야 하기 때문입니다.

1. 번들 출력 파일, `index.js`를 `my-lambda-function.zip`이라는 ZIP 파일로 압축합니다.

1. 이 자습서의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 항목에서 생성한 Amazon S3 버킷에 `mylambdafunction.zip`을 업로드합니다.

`mylambdafunction.js`에 대한 전체 브라우저 스크립트 코드는 다음과 같습니다.

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};

// Create the client service objects.
const dbclient = new DynamoDBClient({ region: REGION });
const snsclient = new SNSClient({ region: REGION });

exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

## Lambda 함수 배포
<a name="scheduled-events-invoking-lambda-deploy-function"></a>

프로젝트의 루트에서 `lambda-function-setup.js` 파일을 생성하고 아래 내용을 해당 파일에 붙여 넣습니다.

*BUCKET\$1NAME*을 Lambda 함수의 ZIP 버전을 업로드한 Amazon S3 버킷 이름으로 바꿉니다. *ZIP\$1FILE\$1NAME*을 Lambda 함수의 ZIP 버전 이름으로 바꿉니다. *IAM\$1ROLE\$1ARN*을 이 자습서의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 항목에서 생성한 IAM 역할의 Amazon 리소스 번호(ARN)로 바꿉니다. *LAMBDA\$1FUNCTION\$1NAME*을 Lambda 함수 이름으로 바꿉니다.

```
// Load the required Lambda client and commands.
const {
   CreateFunctionCommand,
} = require("@aws-sdk/client-lambda");
const {
   lambdaClient
} = require("..libs/lambdaClient.js");

// Instantiate an Lambda client service object.
const lambda = new LambdaClient({ region: REGION });

// Set the parameters.
const params = {
  Code: {
    S3Bucket: "BUCKET_NAME", // BUCKET_NAME
    S3Key: "ZIP_FILE_NAME", // ZIP_FILE_NAME
  },
  FunctionName: "LAMBDA_FUNCTION_NAME",
  Handler: "index.handler",
  Role: "IAM_ROLE_ARN", // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
  Runtime: "nodejs12.x",
  Description:
    "Scans a DynamoDB table of employee details and using Amazon Simple Notification Services (Amazon SNS) to " +
    "send employees an email the each anniversary of their start-date.",
};

const run = async () => {
  try {
    const data = await lambda.send(new CreateFunctionCommand(params));
    console.log("Success", data); // successful response
  } catch (err) {
    console.log("Error", err); // an error occurred
  }
};
run();
```

명령줄에 다음을 입력하여 Lambda 함수를 배포합니다.

```
node lambda-function-setup.js
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js) 제공합니다.

## Lambda 함수를 간접적으로 호출하도록 CloudWatch 구성
<a name="scheduled-events-invoking-lambda-run"></a>

Lambda 함수를 간접적으로 호출하도록 CloudWatch를 구성하려면 다음을 수행합니다.

1. Lambda 콘솔에서 **함수 페이지**를 엽니다.

1. Lambda 함수를 선택합니다.

1. **Designer**에서 **트리거 추가**를 선택합니다.

1. 트리거 유형을 **CloudWatch Events/EventBridge**로 설정합니다.

1. 규칙에서 **새 규칙 생성**을 선택합니다.

1.  규칙 이름과 규칙 설명을 입력합니다.

1. 규칙 유형에서 **예약 표현식**을 선택합니다.

1. **예약 표현식** 필드에 cron 표현식을 입력합니다. 예를 들어 **cron(0 12 ? \$1 MON-FRI \$1)**를 입력합니다.

1. **추가**를 선택합니다.
**참고**  
자세한 내용은 [Amazon EventBridge에 AWS Lambda 사용(CloudWatch Events)](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents.html) 단원을 참조하세요.

## 리소스 삭제
<a name="scheduled-events-invoking-lambda-destroy"></a>

축하합니다\$1 AWS SDK for JavaScript를 사용하여 Amazon CloudWatch 예약 이벤트를 통해 Lambda 함수를 간접적으로 호출했습니다. 이 자습서의 시작 부분에서 설명한 것처럼 요금이 부과되지 않도록 하려면 이 자습서를 진행하는 동안 생성한 모든 리소스를 종료해야 합니다. 다음과 같이이 자습서의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 주제에서 생성한 CloudFormation 스택을 삭제하여이 작업을 수행할 수 있습니다.

1. [CloudFormation 콘솔]( https://console.aws.amazon.com/cloudformation/home)을 엽니다.

1. **스택** 페이지에서 스택을 선택합니다.

1. **삭제**를 선택합니다.