Create an EventBridge rule using an AWS SDK - Amazon EventBridge

Create an EventBridge rule using an AWS SDK

The following code examples show how to create an Amazon EventBridge rule.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples:

.NET
AWS SDK for .NET
Note

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

Create a rule that triggers when an object is added to an Amazon Simple Storage Service bucket.

/// <summary> /// Create a new event rule that triggers when an Amazon S3 object is created in a bucket. /// </summary> /// <param name="roleArn">The ARN of the role.</param> /// <param name="ruleName">The name to give the rule.</param> /// <param name="bucketName">The name of the bucket to trigger the event.</param> /// <returns>The ARN of the new rule.</returns> public async Task<string> PutS3UploadRule(string roleArn, string ruleName, string bucketName) { string eventPattern = "{" + "\"source\": [\"aws.s3\"]," + "\"detail-type\": [\"Object Created\"]," + "\"detail\": {" + "\"bucket\": {" + "\"name\": [\"" + bucketName + "\"]" + "}" + "}" + "}"; var response = await _amazonEventBridge.PutRuleAsync( new PutRuleRequest() { Name = ruleName, Description = "Example S3 upload rule for EventBridge", RoleArn = roleArn, EventPattern = eventPattern }); return response.RuleArn; }

Create a rule that uses a custom pattern.

/// <summary> /// Update a rule to use a custom defined event pattern. /// </summary> /// <param name="ruleName">The name of the rule to update.</param> /// <returns>The ARN of the updated rule.</returns> public async Task<string> UpdateCustomEventPattern(string ruleName) { string customEventsPattern = "{" + "\"source\": [\"ExampleSource\"]," + "\"detail-type\": [\"ExampleType\"]" + "}"; var response = await _amazonEventBridge.PutRuleAsync( new PutRuleRequest() { Name = ruleName, Description = "Custom test rule", EventPattern = customEventsPattern }); return response.RuleArn; }
  • For API details, see PutRule in AWS 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 AWS Code Examples Repository.

Include the required files.

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

Create the rule.

Aws::CloudWatchEvents::EventBridgeClient cwe; Aws::CloudWatchEvents::Model::PutRuleRequest request; request.SetName(rule_name); request.SetRoleArn(role_arn); request.SetScheduleExpression("rate(5 minutes)"); request.SetState(Aws::CloudWatchEvents::Model::RuleState::ENABLED); auto outcome = cwe.PutRule(request); if (!outcome.IsSuccess()) { std::cout << "Failed to create CloudWatch events rule " << rule_name << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created CloudWatch events rule " << rule_name << " with resulting Arn " << outcome.GetResult().GetRuleArn() << std::endl; }
  • For API details, see PutRule in AWS SDK for C++ API Reference.

Java
SDK for Java 2.x
Note

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

Create a scheduled rule.

public static void createEBRule(EventBridgeClient eventBrClient, String ruleName, String cronExpression) { try { PutRuleRequest ruleRequest = PutRuleRequest.builder() .name(ruleName) .eventBusName("default") .scheduleExpression(cronExpression) .state("ENABLED") .description("A test rule that runs on a schedule created by the Java API") .build(); PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); System.out.println("The ARN of the new rule is "+ ruleResponse.ruleArn()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

Create a rule that triggers when an object is added to an Amazon Simple Storage Service bucket.

// Create a new event rule that triggers when an Amazon S3 object is created in a bucket. public static void addEventRule( EventBridgeClient eventBrClient, String roleArn, String bucketName, String eventRuleName) { String pattern = "{\n" + " \"source\": [\"aws.s3\"],\n" + " \"detail-type\": [\"Object Created\"],\n" + " \"detail\": {\n" + " \"bucket\": {\n" + " \"name\": [\""+bucketName+"\"]\n" + " }\n" + " }\n" + "}"; try { PutRuleRequest ruleRequest = PutRuleRequest.builder() .description("Created by using the AWS SDK for Java v2") .name(eventRuleName) .eventPattern(pattern) .roleArn(roleArn) .build(); PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); System.out.println("The ARN of the new rule is "+ ruleResponse.ruleArn()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • For API details, see PutRule in AWS SDK for Java 2.x 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 AWS 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 { PutRuleCommand } from "@aws-sdk/client-eventbridge"; import { ebClient } from "./libs/eventBridgeClient.js"; // Set the parameters. export const params = { Name: "DEMO_EVENT", RoleArn: "IAM_ROLE_ARN", //IAM_ROLE_ARN ScheduleExpression: "rate(5 minutes)", State: "ENABLED", }; export const run = async () => { try { const data = await ebClient.send(new PutRuleCommand(params)); console.log("Success, scheduled rule created; Rule ARN:", 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 PutRule in AWS 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 AWS 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 = { Name: 'DEMO_EVENT', RoleArn: 'IAM_ROLE_ARN', ScheduleExpression: 'rate(5 minutes)', State: 'ENABLED' }; ebevents.putRule(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.RuleArn); } });
  • For API details, see PutRule in AWS SDK for JavaScript API Reference.

Kotlin
SDK for Kotlin
Note

This is prerelease documentation for a feature in preview release. It is subject to change.

Note

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

Create a scheduled rule.

suspend fun createScRule(ruleName: String?, cronExpression: String?) { val ruleRequest = PutRuleRequest { name = ruleName eventBusName = "default" scheduleExpression = cronExpression state = RuleState.Enabled description = "A test rule that runs on a schedule created by the Kotlin API" } EventBridgeClient { region = "us-west-2" }.use { eventBrClient -> val ruleResponse = eventBrClient.putRule(ruleRequest) println("The ARN of the new rule is ${ruleResponse.ruleArn}") } }

Create a rule that triggers when an object is added to an Amazon Simple Storage Service bucket.

// Create a new event rule that triggers when an Amazon S3 object is created in a bucket. suspend fun addEventRule(roleArnVal: String?, bucketName: String, eventRuleName: String?) { val pattern = """{ "source": ["aws.s3"], "detail-type": ["Object Created"], "detail": { "bucket": { "name": ["$bucketName"] } } }""" val ruleRequest = PutRuleRequest { description = "Created by using the AWS SDK for Kotlin" name = eventRuleName eventPattern = pattern roleArn = roleArnVal } EventBridgeClient { region = "us-east-1" }.use { eventBrClient -> val ruleResponse = eventBrClient.putRule(ruleRequest) println("The ARN of the new rule is ${ruleResponse.ruleArn}") } }
  • For API details, see PutRule in AWS SDK for Kotlin API reference.

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