Add a target using an Amazon SDK - Amazon EventBridge
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Add a target using an Amazon SDK

The following code examples show how to add a target to an Amazon EventBridge event.

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Add an Amazon SNS topic as a target for a rule.

/// <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; }

Add an input transformer to a target for a rule.

/// <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; }
  • For API details, see PutTargets in Amazon SDK for .NET API Reference.

C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Include the required files.

#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>

Add the target.

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; }
  • For API details, see PutTargets in Amazon SDK for C++ API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Create the client in a separate module and export it.

import { EventBridgeClient } from "@aws-sdk/client-eventbridge"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon EventBridge service client object. export const ebClient = new EventBridgeClient({ region: REGION });

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js. import { PutTargetsCommand } from "@aws-sdk/client-eventbridge"; import { ebClient } from "./libs/eventBridgeClient.js"; // Set the parameters. export const params = { Rule: "DEMO_EVENT", Targets: [ { Arn: "LAMBDA_FUNCTION_ARN", //LAMBDA_FUNCTION_ARN Id: "myCloudWatchEventsTarget", }, ], }; export const run = async () => { try { const data = await ebClient.send(new PutTargetsCommand(params)); console.log("Success, target added; requestID: ", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
  • For API details, see PutTargets in Amazon SDK for JavaScript API Reference.

SDK for JavaScript (v2)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// 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); } });
  • For API details, see PutTargets in Amazon SDK for JavaScript API Reference.

For a complete list of Amazon SDK developer guides and code examples, see Using EventBridge with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.