Gunakan PutRule dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan PutRule dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanPutRule.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat aturan yang dipicu saat objek ditambahkan ke bucket Amazon Simple Storage Service.

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

Buat aturan yang menggunakan pola kustom.

/// <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; }
  • Untuk API detailnya, lihat PutRuledi AWS SDK for .NET APIReferensi.

C++
SDKuntuk C ++
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Sertakan file-file yang diperlukan.

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

Buat aturan.

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; }
  • Untuk API detailnya, lihat PutRuledi AWS SDK for C++ APIReferensi.

CLI
AWS CLI

Untuk membuat aturan CloudWatch Acara

Contoh ini membuat aturan yang dipicu setiap hari pada pukul 9:00 pagi ()UTC. Jika Anda menggunakan put-target untuk menambahkan fungsi Lambda sebagai target aturan ini, Anda dapat menjalankan fungsi Lambda setiap hari pada waktu yang ditentukan:

aws events put-rule --name "DailyLambdaFunction" --schedule-expression "cron(0 9 * * ? *)"

Contoh ini membuat aturan yang memicu ketika setiap EC2 instance di wilayah mengubah status:

aws events put-rule --name "EC2InstanceStateChanges" --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}" --role-arn "arn:aws:iam::123456789012:role/MyRoleForThisRule"

Contoh ini membuat aturan yang memicu ketika setiap EC2 instance di wilayah dihentikan atau dihentikan:

aws events put-rule --name "EC2InstanceStateChangeStopOrTerminate" --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"],\"detail\":{\"state\":[\"stopped\",\"terminated\"]}}" --role-arn "arn:aws:iam::123456789012:role/MyRoleForThisRule"
  • Untuk API detailnya, lihat PutRuledi Referensi AWS CLI Perintah.

Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat aturan terjadwal.

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

Buat aturan yang dipicu saat objek ditambahkan ke bucket Amazon Simple Storage Service.

// 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); } }
  • Untuk API detailnya, lihat PutRuledi AWS SDK for Java 2.x APIReferensi.

JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Impor modul SDK dan klien dan panggil fileAPI.

import { EventBridgeClient, PutRuleCommand } from "@aws-sdk/client-eventbridge"; export const putRule = async ( ruleName = "some-rule", source = "some-source", ) => { const client = new EventBridgeClient({}); const response = await client.send( new PutRuleCommand({ Name: ruleName, EventPattern: JSON.stringify({ source: [source] }), State: "ENABLED", EventBusName: "default", }), ); console.log("PutRule response:"); console.log(response); // PutRule response: // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd7292ced-1544-421b-842f-596326bc7072', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // RuleArn: 'arn:aws:events:us-east-1:xxxxxxxxxxxx:rule/EventBridgeTestRule-1696280037720' // } return response; };
  • Untuk API detailnya, lihat PutRuledi AWS SDK for JavaScript APIReferensi.

SDKuntuk JavaScript (v2)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 = { 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); } });
  • Untuk API detailnya, lihat PutRuledi AWS SDK for JavaScript APIReferensi.

Kotlin
SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat aturan terjadwal.

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}") } }

Buat aturan yang dipicu saat objek ditambahkan ke bucket Amazon Simple Storage Service.

// 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}") } }
  • Untuk API detailnya, lihat PutRule AWSSDKAPIreferensi Kotlin.