PutTargets 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

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

PutTargets 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 PutTargets

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

新增 Amazon SNS 主題作為規則的目標。

/// <summary> /// Add an Amazon SNS target topic to a rule. /// </summary> /// <param name="ruleName">The name of the rule to update.</param> /// <param name="targetArn">The ARN of the Amazon SNS target.</param> /// <param name="eventBusArn">The optional event bus name, uses default if empty.</param> /// <returns>The ID of the target.</returns> public async Task<string> AddSnsTargetToRule(string ruleName, string targetArn, string? eventBusArn = null) { var targetID = Guid.NewGuid().ToString(); // Create the list of targets and add a new target. var targets = new List<Target> { new Target() { Arn = targetArn, Id = targetID } }; // Add the targets to the rule. var response = await _amazonEventBridge.PutTargetsAsync( new PutTargetsRequest() { EventBusName = eventBusArn, Rule = ruleName, Targets = targets, }); if (response.FailedEntryCount > 0) { response.FailedEntries.ForEach(e => { _logger.LogError( $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}"); }); } return targetID; }

將輸入轉換器新增至某個規則的目標。

/// <summary> /// Update an Amazon S3 object created rule with a transform on the target. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <param name="targetArn">The ARN of the target.</param> /// <param name="eventBusArn">Optional event bus ARN. If empty, uses the default event bus.</param> /// <returns>The ID of the target.</returns> public async Task<string> UpdateS3UploadRuleTargetWithTransform(string ruleName, string targetArn, string? eventBusArn = null) { var targetID = Guid.NewGuid().ToString(); var targets = new List<Target> { new Target() { Id = targetID, Arn = targetArn, InputTransformer = new InputTransformer() { InputPathsMap = new Dictionary<string, string>() { {"bucket", "$.detail.bucket.name"}, {"time", "$.time"} }, InputTemplate = "\"Notification: an object was uploaded to bucket <bucket> at <time>.\"" } } }; var response = await _amazonEventBridge.PutTargetsAsync( new PutTargetsRequest() { EventBusName = eventBusArn, Rule = ruleName, Targets = targets, }); if (response.FailedEntryCount > 0) { response.FailedEntries.ForEach(e => { _logger.LogError( $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}"); }); } return targetID; }
  • 如需 API 詳細資訊,請參閱 PutTargets AWS SDK for .NET 參考中的 API

C++
C++ 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

包括必需的檔案。

#include <aws/core/Aws.h> #include <aws/events/EventBridgeClient.h> #include <aws/events/model/PutTargetsRequest.h> #include <aws/events/model/PutTargetsResult.h> #include <aws/core/utils/Outcome.h> #include <iostream>

新增目標。

Aws::CloudWatchEvents::EventBridgeClient cwe; Aws::CloudWatchEvents::Model::Target target; target.SetArn(lambda_arn); target.SetId(target_id); Aws::CloudWatchEvents::Model::PutTargetsRequest request; request.SetRule(rule_name); request.AddTargets(target); auto putTargetsOutcome = cwe.PutTargets(request); if (!putTargetsOutcome.IsSuccess()) { std::cout << "Failed to create CloudWatch events target for rule " << rule_name << ": " << putTargetsOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created CloudWatch events target for rule " << rule_name << std::endl; }
  • 如需 API 詳細資訊,請參閱 PutTargets AWS SDK for C++ 參考中的 API

CLI
AWS CLI

若要新增 CloudWatch Events 規則的目標

此範例會新增 Lambda 函數作為規則的目標:

aws events put-targets --rule DailyLambdaFunction --targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:123456789012:function:MyFunctionName"

此範例會將 Amazon Kinesis 串流設定為目標,以便將此規則捕捉到的事件轉送至串流:

aws events put-targets --rule EC2InstanceStateChanges --targets "Id"="1","Arn"="arn:aws:kinesis:us-east-1:123456789012:stream/MyStream","RoleArn"="arn:aws:iam::123456789012:role/MyRoleForThisRule"

此範例會將兩個 Amazon Kinesis 串流設定為單一規則的目標:

aws events put-targets --rule DailyLambdaFunction --targets "Id"="Target1","Arn"="arn:aws:kinesis:us-east-1:379642911888:stream/MyStream1","RoleArn"="arn:aws:iam::379642911888:role/ MyRoleToAccessLambda" "Id"="Target2"," Arn"="arn:aws:kinesis:us-east-1:379642911888:stream/MyStream2","RoleArn"="arn:aws:iam::379642911888:role/MyRoleToAccessLambda"
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 PutTargets

Java
Java 2.x 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

新增 Amazon SNS 主題作為規則的目標。

// Add a rule which triggers an SNS target when a file is uploaded to an S3 // bucket. public static void addSnsEventRule(EventBridgeClient eventBrClient, String ruleName, String topicArn, String topicName, String eventRuleName, String bucketName) { String targetID = java.util.UUID.randomUUID().toString(); Target myTarget = Target.builder() .id(targetID) .arn(topicArn) .build(); List<Target> targets = new ArrayList<>(); targets.add(myTarget); PutTargetsRequest request = PutTargetsRequest.builder() .eventBusName(null) .targets(targets) .rule(ruleName) .build(); eventBrClient.putTargets(request); System.out.println("Added event rule " + eventRuleName + " with Amazon SNS target " + topicName + " for bucket " + bucketName + "."); }

將輸入轉換器新增至某個規則的目標。

public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn, String ruleName) { String targetId = java.util.UUID.randomUUID().toString(); InputTransformer inputTransformer = InputTransformer.builder() .inputTemplate("\"Notification: sample event was received.\"") .build(); Target target = Target.builder() .id(targetId) .arn(topicArn) .inputTransformer(inputTransformer) .build(); try { PutTargetsRequest targetsRequest = PutTargetsRequest.builder() .rule(ruleName) .targets(target) .eventBusName(null) .build(); eventBrClient.putTargets(targetsRequest); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • 如需 API 詳細資訊,請參閱 PutTargets AWS SDK for Java 2.x 參考中的 API

JavaScript
SDK for JavaScript (v3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

匯入 SDK 和用戶端模組並呼叫 API。

import { EventBridgeClient, PutTargetsCommand, } from "@aws-sdk/client-eventbridge"; export const putTarget = async ( existingRuleName = "some-rule", targetArn = "arn:aws:lambda:us-east-1:000000000000:function:test-func", uniqueId = Date.now().toString(), ) => { const client = new EventBridgeClient({}); const response = await client.send( new PutTargetsCommand({ Rule: existingRuleName, Targets: [ { Arn: targetArn, Id: uniqueId, }, ], }), ); console.log("PutTargets response:"); console.log(response); // PutTargets response: // { // '$metadata': { // httpStatusCode: 200, // requestId: 'f5b23b9a-2c17-45c1-ad5c-f926c3692e3d', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // FailedEntries: [], // FailedEntryCount: 0 // } return response; };
  • 如需 API 詳細資訊,請參閱 PutTargets AWS SDK for JavaScript 參考中的 API

SDK for JavaScript (v2)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// 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 ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" }); var params = { Rule: "DEMO_EVENT", Targets: [ { Arn: "LAMBDA_FUNCTION_ARN", Id: "myEventBridgeTarget", }, ], }; ebevents.putTargets(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
  • 如需 API 詳細資訊,請參閱 PutTargets AWS SDK for JavaScript 參考中的 API

Kotlin
Kotlin 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// Add a rule that triggers an SNS target when a file is uploaded to an S3 bucket. suspend fun addSnsEventRule( ruleName: String?, topicArn: String?, topicName: String, eventRuleName: String, bucketName: String, ) { val targetID = UUID.randomUUID().toString() val myTarget = Target { id = targetID arn = topicArn } val targetsOb = mutableListOf<Target>() targetsOb.add(myTarget) val request = PutTargetsRequest { eventBusName = null targets = targetsOb rule = ruleName } EventBridgeClient { region = "us-east-1" }.use { eventBrClient -> eventBrClient.putTargets(request) println("Added event rule $eventRuleName with Amazon SNS target $topicName for bucket $bucketName.") } }

將輸入轉換器新增至某個規則的目標。

suspend fun updateCustomRuleTargetWithTransform( topicArn: String?, ruleName: String?, ) { val targetId = UUID.randomUUID().toString() val inputTransformerOb = InputTransformer { inputTemplate = "\"Notification: sample event was received.\"" } val target = Target { id = targetId arn = topicArn inputTransformer = inputTransformerOb } val targetsRequest = PutTargetsRequest { rule = ruleName targets = listOf(target) eventBusName = null } EventBridgeClient { region = "us-east-1" }.use { eventBrClient -> eventBrClient.putTargets(targetsRequest) } }
  • 如需 API 詳細資訊,請參閱 PutTargets AWS for Kotlin SDK 參考中的 API