

 適用於 JavaScript 的 AWS SDK v2 已end-of-support。我們建議您遷移至 [適用於 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)。如需如何遷移的其他詳細資訊和資訊，請參閱此[公告](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 傳送事件到 Amazon CloudWatch Events
<a name="cloudwatch-examples-sending-events"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**這個 Node.js 程式碼範例會說明：**
+ 如何建立及更新觸發事件所用的規則。
+ 如何定義一個或多個目標以回應事件。
+ 如何傳送與目標相符的事件以進行處理。

## 使用案例
<a name="cloudwatch-examples-sending-events-scenario"></a>

CloudWatch Events 提供近乎即時的系統事件串流，將 Amazon Web Services 資源的變更描述到任何各種目標。使用簡單的規則，您可以比對事件，並將這些事件轉傳到一或多個目標函數或串流。

在此範例中，一系列 Node.js 模組用於將事件傳送至 CloudWatch Events。Node.js 模組使用適用於 JavaScript 的 SDK，以下列 `CloudWatchEvents`用戶端類別的方法管理執行個體：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putRule-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putRule-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putTargets-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putTargets-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putEvents-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putEvents-property)

如需 CloudWatch Events 的詳細資訊，請參閱《Amazon CloudWatch Events 使用者指南》中的[使用 PutEvents 新增](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html)事件。 *Amazon CloudWatch *

## 先決條件任務
<a name="cloudwatch-examples-sending-events-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 安裝 Node.js。如需安裝 Node.js 的詳細資訊，請參閱 [Node.js 網站](https://nodejs.org)。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 [從共用登入資料檔案中在 Node.js 中載入登入資料](loading-node-credentials-shared.md)。
+ 使用 **hello-world** 藍圖建立 Lambda 函數，做為事件的目標。若要了解如何執行，請參閱《*Amazon CloudWatch Events 使用者指南*》中的[步驟 1：建立 AWS Lambda 函數](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/LogEC2InstanceState.html)。
+ 建立 IAM 角色，其政策會授予 CloudWatch Events 的許可，並包含 `events.amazonaws.com` 做為信任的實體。如需建立 IAM 角色的詳細資訊，請參閱《*IAM 使用者指南*》中的[建立角色以委派許可給 AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)。

您可以使用下列角色政策來建立 IAM 角色。

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Sid": "CloudWatchEventsFullAccess",
         "Effect": "Allow",
         "Action": "events:*",
         "Resource": "*"
      },
      {
         "Sid": "IAMPassRoleForCloudWatchEvents",
         "Effect": "Allow",
         "Action": "iam:PassRole",
         "Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
      }      
   ]
}
```

------

您可以使用下列信任關係來建立 IAM 角色。

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Principal": {
            "Service": "events.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
      }      
   ]
}
```

------

## 建立排程的規則
<a name="cloudwatch-examples-sending-events-rules"></a>

以檔名 `cwe_putrule.js` 建立一個 Node.js 模組。請務必依前述的內容來設定軟體開發套件。若要存取 CloudWatch Events，請建立 `AWS.CloudWatchEvents` 服務物件。建立 JSON 物件，其中包含指定新排程規則所需的參數，其中包含下列項目：
+ 規則的名稱
+ 您先前建立之 IAM 角色的 ARN
+ 排定每 5 分鐘為觸發的規則表達式

呼叫 `putRule` 方法來建立規則。回呼會傳回新的或更新規則的 ARN。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Name: "DEMO_EVENT",
  RoleArn: "IAM_ROLE_ARN",
  ScheduleExpression: "rate(5 minutes)",
  State: "ENABLED",
};

cwevents.putRule(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.RuleArn);
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node cwe_putrule.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-events/cwe_putrule.js)找到這個範本程式碼。

## 新增 AWS Lambda 函數目標
<a name="cloudwatch-examples-sending-events-targets"></a>

以檔名 `cwe_puttargets.js` 建立一個 Node.js 模組。請務必依前述的內容來設定軟體開發套件。若要存取 CloudWatch Events，請建立 `AWS.CloudWatchEvents` 服務物件。建立 JSON 物件，其中包含指定要連接目標之規則所需的參數，包括您建立之 Lambda 函數的 ARN。呼叫 `AWS.CloudWatchEvents` 服務物件的 `putTargets` 方法。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Rule: "DEMO_EVENT",
  Targets: [
    {
      Arn: "LAMBDA_FUNCTION_ARN",
      Id: "myCloudWatchEventsTarget",
    },
  ],
};

cwevents.putTargets(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node cwe_puttargets.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-events/cwe_puttargets.js)找到這個範本程式碼。

## 傳送事件
<a name="cloudwatch-examples-sending-events-putevents"></a>

以檔名 `cwe_putevents.js` 建立一個 Node.js 模組。請務必依前述的內容來設定軟體開發套件。若要存取 CloudWatch Events，請建立 `AWS.CloudWatchEvents` 服務物件。建立 JSON 物件，其包含傳送事件所需的參數。對於每個事件，包括事件來源、受事件影響的任何資源的 ARN，以及事件的詳細資訊。呼叫 `AWS.CloudWatchEvents` 服務物件的 `putEvents` 方法。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Entries: [
    {
      Detail: '{ "key1": "value1", "key2": "value2" }',
      DetailType: "appRequestSubmitted",
      Resources: ["RESOURCE_ARN"],
      Source: "com.company.app",
    },
  ],
};

cwevents.putEvents(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Entries);
  }
});
```

若要執行範例，請在命令列中輸入以下內容。

```
node cwe_putevents.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-events/cwe_putevents.js)找到這個範本程式碼。