本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
PutTargets
搭配 AWS SDK或 使用 CLI
下列程式碼範例示範如何使用 PutTargets
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 。 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++
-
- SDK 適用於 C++
-
注意
還有更多 。 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 事件規則的目標
此範例會新增 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詳細資訊,請參閱 命令參考 PutTargets
中的 。 AWS CLI
-
- Java
-
- SDK 適用於 Java 2.x
-
注意
還有更多 。 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 適用於 JavaScript (v3)
-
注意
還有更多 。 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 適用於 JavaScript (v2)
-
注意
還有更多 。 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
-
- SDK 適用於 Kotlin
-
注意
還有更多 。 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 SDK for Kotlin API參考 。
-
如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 EventBridge 搭配 使用 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。