Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
EventBridge exemples utilisant AWS SDK for .NET
Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l'aide du AWS SDK for .NET with EventBridge.
Les principes de base sont des exemples de code qui vous montrent comment effectuer les opérations essentielles au sein d'un service.
Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Les actions vous indiquent comment appeler des fonctions de service individuelles, mais vous pouvez les visualiser dans leur contexte dans les scénarios correspondants.
Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.
Mise en route
Les exemples de code suivants montrent comment commencer à utiliser EventBridge.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. using Amazon.EventBridge; using Amazon.EventBridge.Model; namespace EventBridgeActions; public static class HelloEventBridge { static async Task Main(string[] args) { var eventBridgeClient = new AmazonEventBridgeClient(); Console.WriteLine($"Hello Amazon EventBridge! Following are some of your EventBuses:"); Console.WriteLine(); // You can use await and any of the async methods to get a response. // Let's get the first five event buses. var response = await eventBridgeClient.ListEventBusesAsync( new ListEventBusesRequest() { Limit = 5 }); foreach (var eventBus in response.EventBuses) { Console.WriteLine($"\tEventBus: {eventBus.Name}"); Console.WriteLine($"\tArn: {eventBus.Arn}"); Console.WriteLine($"\tPolicy: {eventBus.Policy}"); Console.WriteLine(); } } }
-
Pour API plus de détails, voir ListEventBusesla section AWS SDK for .NET APIRéférence.
-
Rubriques
Principes de base
L’exemple de code suivant illustre comment :
Créez une règle et ajoutez-y une cible.
Activez et désactivez les règles.
Répertoriez et mettez à jour les règles et les cibles.
Envoyez des événements, puis nettoyez les ressources.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Exécutez un scénario interactif à une invite de commande.
public class EventBridgeScenario { /* Before running this .NET code example, set up your development environment, including your credentials. This .NET example performs the following tasks with Amazon EventBridge: - Create a rule. - Add a target to a rule. - Enable and disable rules. - List rules and targets. - Update rules and targets. - Send events. - Delete the rule. */ private static ILogger logger = null!; private static EventBridgeWrapper _eventBridgeWrapper = null!; private static IConfiguration _configuration = null!; private static IAmazonIdentityManagementService? _iamClient = null!; private static IAmazonSimpleNotificationService? _snsClient = null!; private static IAmazonS3 _s3Client = null!; static async Task Main(string[] args) { // Set up dependency injection for Amazon EventBridge. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonEventBridge>() .AddAWSService<IAmazonIdentityManagementService>() .AddAWSService<IAmazonS3>() .AddAWSService<IAmazonSimpleNotificationService>() .AddTransient<EventBridgeWrapper>() ) .Build(); _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally, load local settings. .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<EventBridgeScenario>(); ServicesSetup(host); string topicArn = ""; string roleArn = ""; Console.WriteLine(new string('-', 80)); Console.WriteLine("Welcome to the Amazon EventBridge example scenario."); Console.WriteLine(new string('-', 80)); try { roleArn = await CreateRole(); await CreateBucketWithEventBridgeEvents(); await AddEventRule(roleArn); await ListEventRules(); topicArn = await CreateSnsTopic(); var email = await SubscribeToSnsTopic(topicArn); await AddSnsTarget(topicArn); await ListTargets(); await ListRulesForTarget(topicArn); await UploadS3File(_s3Client); await ChangeRuleState(false); await GetRuleState(); await UpdateSnsEventRule(topicArn); await ChangeRuleState(true); await UploadS3File(_s3Client); await UpdateToCustomRule(topicArn); await TriggerCustomRule(email); await CleanupResources(topicArn); } catch (Exception ex) { logger.LogError(ex, "There was a problem executing the scenario."); await CleanupResources(topicArn); } Console.WriteLine(new string('-', 80)); Console.WriteLine("The Amazon EventBridge example scenario is complete."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Populate the services for use within the console application. /// </summary> /// <param name="host">The services host.</param> private static void ServicesSetup(IHost host) { _eventBridgeWrapper = host.Services.GetRequiredService<EventBridgeWrapper>(); _snsClient = host.Services.GetRequiredService<IAmazonSimpleNotificationService>(); _s3Client = host.Services.GetRequiredService<IAmazonS3>(); _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>(); } /// <summary> /// Create a role to be used by EventBridge. /// </summary> /// <returns>The role Amazon Resource Name (ARN).</returns> public static async Task<string> CreateRole() { Console.WriteLine(new string('-', 80)); Console.WriteLine("Creating a role to use with EventBridge and attaching managed policy AmazonEventBridgeFullAccess."); Console.WriteLine(new string('-', 80)); var roleName = _configuration["roleName"]; var assumeRolePolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": \"events.amazonaws.com\"" + "}," + "\"Action\": \"sts:AssumeRole\"" + "}]" + "}"; var roleResult = await _iamClient!.CreateRoleAsync( new CreateRoleRequest() { AssumeRolePolicyDocument = assumeRolePolicy, Path = "/", RoleName = roleName }); await _iamClient.AttachRolePolicyAsync( new AttachRolePolicyRequest() { PolicyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess", RoleName = roleName }); // Allow time for the role to be ready. Thread.Sleep(10000); return roleResult.Role.Arn; } /// <summary> /// Create an Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events enabled. /// </summary> /// <returns>Async task.</returns> private static async Task CreateBucketWithEventBridgeEvents() { Console.WriteLine(new string('-', 80)); Console.WriteLine("Creating an S3 bucket with EventBridge events enabled."); var testBucketName = _configuration["testBucketName"]; var bucketExists = await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(_s3Client, testBucketName); if (!bucketExists) { await _s3Client.PutBucketAsync(new PutBucketRequest() { BucketName = testBucketName, UseClientRegion = true }); } await _s3Client.PutBucketNotificationAsync(new PutBucketNotificationRequest() { BucketName = testBucketName, EventBridgeConfiguration = new EventBridgeConfiguration() }); Console.WriteLine($"\tAdded bucket {testBucketName} with EventBridge events enabled."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Create and upload a file to an S3 bucket to trigger an event. /// </summary> /// <returns>Async task.</returns> private static async Task UploadS3File(IAmazonS3 s3Client) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Uploading a file to the test bucket. This will trigger a subscription email."); var testBucketName = _configuration["testBucketName"]; var fileName = $"example_upload_{DateTime.UtcNow.Ticks}.txt"; // Create the file if it does not already exist. if (!File.Exists(fileName)) { await using StreamWriter sw = File.CreateText(fileName); await sw.WriteLineAsync( "This is a sample file for testing uploads."); } await s3Client.PutObjectAsync(new PutObjectRequest() { FilePath = fileName, BucketName = testBucketName }); Console.WriteLine($"\tPress Enter to continue."); Console.ReadLine(); Console.WriteLine(new string('-', 80)); } /// <summary> /// Create an Amazon Simple Notification Service (Amazon SNS) topic to use as an EventBridge target. /// </summary> /// <returns>Async task.</returns> private static async Task<string> CreateSnsTopic() { Console.WriteLine(new string('-', 80)); Console.WriteLine( "Creating an Amazon Simple Notification Service (Amazon SNS) topic for email subscriptions."); var topicName = _configuration["topicName"]; string topicPolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Sid\": \"EventBridgePublishTopic\"," + "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": \"events.amazonaws.com\"" + "}," + "\"Resource\": \"*\"," + "\"Action\": \"sns:Publish\"" + "}]" + "}"; var topicAttributes = new Dictionary<string, string>() { { "Policy", topicPolicy } }; var topicResponse = await _snsClient!.CreateTopicAsync(new CreateTopicRequest() { Name = topicName, Attributes = topicAttributes }); Console.WriteLine($"\tAdded topic {topicName} for email subscriptions."); Console.WriteLine(new string('-', 80)); return topicResponse.TopicArn; } /// <summary> /// Subscribe a user email to an SNS topic. /// </summary> /// <param name="topicArn">The ARN of the SNS topic.</param> /// <returns>The user's email.</returns> private static async Task<string> SubscribeToSnsTopic(string topicArn) { Console.WriteLine(new string('-', 80)); string email = ""; while (string.IsNullOrEmpty(email)) { Console.WriteLine("Enter your email to subscribe to the Amazon SNS topic:"); email = Console.ReadLine()!; } var subscriptions = new List<string>(); var paginatedSubscriptions = _snsClient!.Paginators.ListSubscriptionsByTopic( new ListSubscriptionsByTopicRequest() { TopicArn = topicArn }); // Get the entire list using the paginator. await foreach (var subscription in paginatedSubscriptions.Subscriptions) { subscriptions.Add(subscription.Endpoint); } if (subscriptions.Contains(email)) { Console.WriteLine($"\tYour email is already subscribed."); Console.WriteLine(new string('-', 80)); return email; } await _snsClient.SubscribeAsync(new SubscribeRequest() { TopicArn = topicArn, Protocol = "email", Endpoint = email }); Console.WriteLine($"Use the link in the email you received to confirm your subscription, then press Enter to continue."); Console.ReadLine(); Console.WriteLine(new string('-', 80)); return email; } /// <summary> /// Add a rule which triggers when a file is uploaded to an S3 bucket. /// </summary> /// <param name="roleArn">The ARN of the role used by EventBridge.</param> /// <returns>Async task.</returns> private static async Task AddEventRule(string roleArn) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Creating an EventBridge event that sends an email when an Amazon S3 object is created."); var eventRuleName = _configuration["eventRuleName"]; var testBucketName = _configuration["testBucketName"]; await _eventBridgeWrapper.PutS3UploadRule(roleArn, eventRuleName, testBucketName); Console.WriteLine($"\tAdded event rule {eventRuleName} for bucket {testBucketName}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Add an SNS target to the rule. /// </summary> /// <param name="topicArn">The ARN of the SNS topic.</param> /// <returns>Async task.</returns> private static async Task AddSnsTarget(string topicArn) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Adding a target to the rule to that sends an email when the rule is triggered."); var eventRuleName = _configuration["eventRuleName"]; var testBucketName = _configuration["testBucketName"]; var topicName = _configuration["topicName"]; await _eventBridgeWrapper.AddSnsTargetToRule(eventRuleName, topicArn); Console.WriteLine($"\tAdded event rule {eventRuleName} with Amazon SNS target {topicName} for bucket {testBucketName}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// List the event rules on the default event bus. /// </summary> /// <returns>Async task.</returns> private static async Task ListEventRules() { Console.WriteLine(new string('-', 80)); Console.WriteLine("Current event rules:"); var rules = await _eventBridgeWrapper.ListAllRulesForEventBus(); rules.ForEach(r => Console.WriteLine($"\tRule: {r.Name} Description: {r.Description} State: {r.State}")); Console.WriteLine(new string('-', 80)); } /// <summary> /// Update the event target to use a transform. /// </summary> /// <param name="topicArn">The SNS topic ARN target to update.</param> /// <returns>Async task.</returns> private static async Task UpdateSnsEventRule(string topicArn) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Let's update the event target with a transform."); var eventRuleName = _configuration["eventRuleName"]; var testBucketName = _configuration["testBucketName"]; await _eventBridgeWrapper.UpdateS3UploadRuleTargetWithTransform(eventRuleName, topicArn); Console.WriteLine($"\tUpdated event rule {eventRuleName} with Amazon SNS target {topicArn} for bucket {testBucketName}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Update the rule to use a custom event pattern. /// </summary> /// <returns>Async task.</returns> private static async Task UpdateToCustomRule(string topicArn) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Updating the event pattern to be triggered by a custom event instead."); var eventRuleName = _configuration["eventRuleName"]; await _eventBridgeWrapper.UpdateCustomEventPattern(eventRuleName); Console.WriteLine($"\tUpdated event rule {eventRuleName} to custom pattern."); await _eventBridgeWrapper.UpdateCustomRuleTargetWithTransform(eventRuleName, topicArn); Console.WriteLine($"\tUpdated event target {topicArn}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Send rule events for a custom rule using the user's email address. /// </summary> /// <param name="email">The email address to include.</param> /// <returns>Async task.</returns> private static async Task TriggerCustomRule(string email) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Sending an event to trigger the rule. This will trigger a subscription email."); await _eventBridgeWrapper.PutCustomEmailEvent(email); Console.WriteLine($"\tEvents have been sent. Press Enter to continue."); Console.ReadLine(); Console.WriteLine(new string('-', 80)); } /// <summary> /// List all of the targets for a rule. /// </summary> /// <returns>Async task.</returns> private static async Task ListTargets() { Console.WriteLine(new string('-', 80)); Console.WriteLine("List all of the targets for a particular rule."); var eventRuleName = _configuration["eventRuleName"]; var targets = await _eventBridgeWrapper.ListAllTargetsOnRule(eventRuleName); targets.ForEach(t => Console.WriteLine($"\tTarget: {t.Arn} Id: {t.Id} Input: {t.Input}")); Console.WriteLine(new string('-', 80)); } /// <summary> /// List all of the rules for a particular target. /// </summary> /// <param name="topicArn">The ARN of the SNS topic.</param> /// <returns>Async task.</returns> private static async Task ListRulesForTarget(string topicArn) { Console.WriteLine(new string('-', 80)); Console.WriteLine("List all of the rules for a particular target."); var rules = await _eventBridgeWrapper.ListAllRuleNamesByTarget(topicArn); rules.ForEach(r => Console.WriteLine($"\tRule: {r}")); Console.WriteLine(new string('-', 80)); } /// <summary> /// Enable or disable a particular rule. /// </summary> /// <param name="isEnabled">True to enable the rule, otherwise false.</param> /// <returns>Async task.</returns> private static async Task ChangeRuleState(bool isEnabled) { Console.WriteLine(new string('-', 80)); var eventRuleName = _configuration["eventRuleName"]; if (!isEnabled) { Console.WriteLine($"Disabling the rule: {eventRuleName}"); await _eventBridgeWrapper.DisableRuleByName(eventRuleName); } else { Console.WriteLine($"Enabling the rule: {eventRuleName}"); await _eventBridgeWrapper.EnableRuleByName(eventRuleName); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Get the current state of the rule. /// </summary> /// <returns>Async task.</returns> private static async Task GetRuleState() { Console.WriteLine(new string('-', 80)); var eventRuleName = _configuration["eventRuleName"]; var state = await _eventBridgeWrapper.GetRuleStateByRuleName(eventRuleName); Console.WriteLine($"Rule {eventRuleName} is in current state {state}."); Console.WriteLine(new string('-', 80)); } /// <summary> /// Clean up the resources from the scenario. /// </summary> /// <param name="topicArn">The ARN of the SNS topic to clean up.</param> /// <returns>Async task.</returns> private static async Task CleanupResources(string topicArn) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Clean up resources."); var eventRuleName = _configuration["eventRuleName"]; if (GetYesNoResponse($"\tDelete all targets and event rule {eventRuleName}? (y/n)")) { Console.WriteLine($"\tRemoving all targets from the event rule."); await _eventBridgeWrapper.RemoveAllTargetsFromRule(eventRuleName); Console.WriteLine($"\tDeleting event rule."); await _eventBridgeWrapper.DeleteRuleByName(eventRuleName); } var topicName = _configuration["topicName"]; if (GetYesNoResponse($"\tDelete Amazon SNS subscription topic {topicName}? (y/n)")) { Console.WriteLine($"\tDeleting topic."); await _snsClient!.DeleteTopicAsync(new DeleteTopicRequest() { TopicArn = topicArn }); } var bucketName = _configuration["testBucketName"]; if (GetYesNoResponse($"\tDelete Amazon S3 bucket {bucketName}? (y/n)")) { Console.WriteLine($"\tDeleting bucket."); // Delete all objects in the bucket. var deleteList = await _s3Client.ListObjectsV2Async(new ListObjectsV2Request() { BucketName = bucketName }); await _s3Client.DeleteObjectsAsync(new DeleteObjectsRequest() { BucketName = bucketName, Objects = deleteList.S3Objects .Select(o => new KeyVersion { Key = o.Key }).ToList() }); // Now delete the bucket. await _s3Client.DeleteBucketAsync(new DeleteBucketRequest() { BucketName = bucketName }); } var roleName = _configuration["roleName"]; if (GetYesNoResponse($"\tDelete role {roleName}? (y/n)")) { Console.WriteLine($"\tDetaching policy and deleting role."); await _iamClient!.DetachRolePolicyAsync(new DetachRolePolicyRequest() { RoleName = roleName, PolicyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess", }); await _iamClient!.DeleteRoleAsync(new DeleteRoleRequest() { RoleName = roleName }); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Helper method to get a yes or no response from the user. /// </summary> /// <param name="question">The question string to print on the console.</param> /// <returns>True if the user responds with a yes.</returns> private static bool GetYesNoResponse(string question) { Console.WriteLine(question); var ynResponse = Console.ReadLine(); var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase); return response; } }
Créez une classe qui englobe les EventBridge opérations.
/// <summary> /// Wrapper for Amazon EventBridge operations. /// </summary> public class EventBridgeWrapper { private readonly IAmazonEventBridge _amazonEventBridge; private readonly ILogger<EventBridgeWrapper> _logger; /// <summary> /// Constructor for the EventBridge wrapper. /// </summary> /// <param name="amazonEventBridge">The injected EventBridge client.</param> /// <param name="logger">The injected logger for the wrapper.</param> public EventBridgeWrapper(IAmazonEventBridge amazonEventBridge, ILogger<EventBridgeWrapper> logger) { _amazonEventBridge = amazonEventBridge; _logger = logger; } /// <summary> /// Get the state for a rule by the rule name. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <param name="eventBusName">The optional name of the event bus. If empty, uses the default event bus.</param> /// <returns>The state of the rule.</returns> public async Task<RuleState> GetRuleStateByRuleName(string ruleName, string? eventBusName = null) { var ruleResponse = await _amazonEventBridge.DescribeRuleAsync( new DescribeRuleRequest() { Name = ruleName, EventBusName = eventBusName }); return ruleResponse.State; } /// <summary> /// Enable a particular rule on an event bus. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <returns>True if successful.</returns> public async Task<bool> EnableRuleByName(string ruleName) { var ruleResponse = await _amazonEventBridge.EnableRuleAsync( new EnableRuleRequest() { Name = ruleName }); return ruleResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Disable a particular rule on an event bus. /// </summary /// <param name="ruleName">The name of the rule.</param> /// <returns>True if successful.</returns> public async Task<bool> DisableRuleByName(string ruleName) { var ruleResponse = await _amazonEventBridge.DisableRuleAsync( new DisableRuleRequest() { Name = ruleName }); return ruleResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// List the rules on an event bus. /// </summary> /// <param name="eventBusArn">The optional ARN of the event bus. If empty, uses the default event bus.</param> /// <returns>The list of rules.</returns> public async Task<List<Rule>> ListAllRulesForEventBus(string? eventBusArn = null) { var results = new List<Rule>(); var request = new ListRulesRequest() { EventBusName = eventBusArn }; // Get all of the pages of rules. ListRulesResponse response; do { response = await _amazonEventBridge.ListRulesAsync(request); results.AddRange(response.Rules); request.NextToken = response.NextToken; } while (response.NextToken is not null); return results; } /// <summary> /// List all of the targets matching a rule by name. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <returns>The list of targets.</returns> public async Task<List<Target>> ListAllTargetsOnRule(string ruleName) { var results = new List<Target>(); var request = new ListTargetsByRuleRequest() { Rule = ruleName }; ListTargetsByRuleResponse response; do { response = await _amazonEventBridge.ListTargetsByRuleAsync(request); results.AddRange(response.Targets); request.NextToken = response.NextToken; } while (response.NextToken is not null); return results; } /// <summary> /// List names of all rules matching a target. /// </summary> /// <param name="targetArn">The ARN of the target.</param> /// <returns>The list of rule names.</returns> public async Task<List<string>> ListAllRuleNamesByTarget(string targetArn) { var results = new List<string>(); var request = new ListRuleNamesByTargetRequest() { TargetArn = targetArn }; ListRuleNamesByTargetResponse response; do { response = await _amazonEventBridge.ListRuleNamesByTargetAsync(request); results.AddRange(response.RuleNames); request.NextToken = response.NextToken; } while (response.NextToken is not null); return results; } /// <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; } /// <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; } /// <summary> /// Update a custom 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> UpdateCustomRuleTargetWithTransform(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() { InputTemplate = "\"Notification: sample event was received.\"" } } }; 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> /// Add an event to the event bus that includes an email, message, and time. /// </summary> /// <param name="email">The email to use in the event detail of the custom event.</param> /// <returns>True if successful.</returns> public async Task<bool> PutCustomEmailEvent(string email) { var eventDetail = new { UserEmail = email, Message = "This event was generated by example code.", UtcTime = DateTime.UtcNow.ToString("g") }; var response = await _amazonEventBridge.PutEventsAsync( new PutEventsRequest() { Entries = new List<PutEventsRequestEntry>() { new PutEventsRequestEntry() { Source = "ExampleSource", Detail = JsonSerializer.Serialize(eventDetail), DetailType = "ExampleType" } } }); return response.FailedEntryCount == 0; } /// <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; } /// <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> /// Delete an event rule by name. /// </summary> /// <param name="ruleName">The name of the event rule.</param> /// <returns>True if successful.</returns> public async Task<bool> RemoveAllTargetsFromRule(string ruleName) { var targetIds = new List<string>(); var request = new ListTargetsByRuleRequest() { Rule = ruleName }; ListTargetsByRuleResponse targetsResponse; do { targetsResponse = await _amazonEventBridge.ListTargetsByRuleAsync(request); targetIds.AddRange(targetsResponse.Targets.Select(t => t.Id)); request.NextToken = targetsResponse.NextToken; } while (targetsResponse.NextToken is not null); var removeResponse = await _amazonEventBridge.RemoveTargetsAsync( new RemoveTargetsRequest() { Rule = ruleName, Ids = targetIds }); if (removeResponse.FailedEntryCount > 0) { removeResponse.FailedEntries.ForEach(e => { _logger.LogError( $"Failed to remove target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}"); }); } return removeResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Delete an event rule by name. /// </summary> /// <param name="ruleName">The name of the event rule.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteRuleByName(string ruleName) { var response = await _amazonEventBridge.DeleteRuleAsync( new DeleteRuleRequest() { Name = ruleName }); return response.HttpStatusCode == HttpStatusCode.OK; } }
-
Pour API plus de détails, consultez les rubriques suivantes dans AWS SDK for .NET APIRéférence.
-
Actions
L'exemple de code suivant montre comment utiliserDeleteRule
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Supprimez une règle par son nom.
/// <summary> /// Delete an event rule by name. /// </summary> /// <param name="ruleName">The name of the event rule.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteRuleByName(string ruleName) { var response = await _amazonEventBridge.DeleteRuleAsync( new DeleteRuleRequest() { Name = ruleName }); return response.HttpStatusCode == HttpStatusCode.OK; }
-
Pour API plus de détails, voir DeleteRulela section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserDescribeRule
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Obtenez l’état d’une règle à l’aide de sa description.
/// <summary> /// Get the state for a rule by the rule name. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <param name="eventBusName">The optional name of the event bus. If empty, uses the default event bus.</param> /// <returns>The state of the rule.</returns> public async Task<RuleState> GetRuleStateByRuleName(string ruleName, string? eventBusName = null) { var ruleResponse = await _amazonEventBridge.DescribeRuleAsync( new DescribeRuleRequest() { Name = ruleName, EventBusName = eventBusName }); return ruleResponse.State; }
-
Pour API plus de détails, voir DescribeRulela section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserDisableRule
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Désactivez une règle par son nom.
/// <summary> /// Disable a particular rule on an event bus. /// </summary /// <param name="ruleName">The name of the rule.</param> /// <returns>True if successful.</returns> public async Task<bool> DisableRuleByName(string ruleName) { var ruleResponse = await _amazonEventBridge.DisableRuleAsync( new DisableRuleRequest() { Name = ruleName }); return ruleResponse.HttpStatusCode == HttpStatusCode.OK; }
-
Pour API plus de détails, voir DisableRulela section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserEnableRule
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Activez une règle par son nom.
/// <summary> /// Enable a particular rule on an event bus. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <returns>True if successful.</returns> public async Task<bool> EnableRuleByName(string ruleName) { var ruleResponse = await _amazonEventBridge.EnableRuleAsync( new EnableRuleRequest() { Name = ruleName }); return ruleResponse.HttpStatusCode == HttpStatusCode.OK; }
-
Pour API plus de détails, voir EnableRulela section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserListRuleNamesByTarget
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Répertoriez tous les noms de règle à l’aide de la cible.
/// <summary> /// List names of all rules matching a target. /// </summary> /// <param name="targetArn">The ARN of the target.</param> /// <returns>The list of rule names.</returns> public async Task<List<string>> ListAllRuleNamesByTarget(string targetArn) { var results = new List<string>(); var request = new ListRuleNamesByTargetRequest() { TargetArn = targetArn }; ListRuleNamesByTargetResponse response; do { response = await _amazonEventBridge.ListRuleNamesByTargetAsync(request); results.AddRange(response.RuleNames); request.NextToken = response.NextToken; } while (response.NextToken is not null); return results; }
-
Pour API plus de détails, voir ListRuleNamesByTargetla section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserListRules
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Répertoriez toutes les règles pour un bus d’événements.
/// <summary> /// List the rules on an event bus. /// </summary> /// <param name="eventBusArn">The optional ARN of the event bus. If empty, uses the default event bus.</param> /// <returns>The list of rules.</returns> public async Task<List<Rule>> ListAllRulesForEventBus(string? eventBusArn = null) { var results = new List<Rule>(); var request = new ListRulesRequest() { EventBusName = eventBusArn }; // Get all of the pages of rules. ListRulesResponse response; do { response = await _amazonEventBridge.ListRulesAsync(request); results.AddRange(response.Rules); request.NextToken = response.NextToken; } while (response.NextToken is not null); return results; }
-
Pour API plus de détails, voir ListRulesla section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserListTargetsByRule
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Répertoriez toutes les cibles d’une règle à l’aide de son nom.
/// <summary> /// List all of the targets matching a rule by name. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <returns>The list of targets.</returns> public async Task<List<Target>> ListAllTargetsOnRule(string ruleName) { var results = new List<Target>(); var request = new ListTargetsByRuleRequest() { Rule = ruleName }; ListTargetsByRuleResponse response; do { response = await _amazonEventBridge.ListTargetsByRuleAsync(request); results.AddRange(response.Targets); request.NextToken = response.NextToken; } while (response.NextToken is not null); return results; }
-
Pour API plus de détails, voir ListTargetsByRulela section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserPutEvents
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Envoyez un événement qui correspond à un modèle personnalisé pour une règle.
/// <summary> /// Add an event to the event bus that includes an email, message, and time. /// </summary> /// <param name="email">The email to use in the event detail of the custom event.</param> /// <returns>True if successful.</returns> public async Task<bool> PutCustomEmailEvent(string email) { var eventDetail = new { UserEmail = email, Message = "This event was generated by example code.", UtcTime = DateTime.UtcNow.ToString("g") }; var response = await _amazonEventBridge.PutEventsAsync( new PutEventsRequest() { Entries = new List<PutEventsRequestEntry>() { new PutEventsRequestEntry() { Source = "ExampleSource", Detail = JsonSerializer.Serialize(eventDetail), DetailType = "ExampleType" } } }); return response.FailedEntryCount == 0; }
-
Pour API plus de détails, voir PutEventsla section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserPutRule
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Créez une règle qui se déclenche lorsqu’un objet est ajouté à un compartiment 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; }
Créez une règle qui utilise un modèle personnalisé.
/// <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; }
-
Pour API plus de détails, voir PutRulela section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserPutTargets
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Ajoutez un SNS sujet Amazon comme cible pour une règle.
/// <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; }
Ajoutez un transformateur d’entrée à une cible pour une règle.
/// <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; }
-
Pour API plus de détails, voir PutTargetsla section AWS SDK for .NET APIRéférence.
-
L'exemple de code suivant montre comment utiliserRemoveTargets
.
- AWS SDK for .NET
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Retirez toutes les cibles d’une règle à l’aide de son nom.
/// <summary> /// Delete an event rule by name. /// </summary> /// <param name="ruleName">The name of the event rule.</param> /// <returns>True if successful.</returns> public async Task<bool> RemoveAllTargetsFromRule(string ruleName) { var targetIds = new List<string>(); var request = new ListTargetsByRuleRequest() { Rule = ruleName }; ListTargetsByRuleResponse targetsResponse; do { targetsResponse = await _amazonEventBridge.ListTargetsByRuleAsync(request); targetIds.AddRange(targetsResponse.Targets.Select(t => t.Id)); request.NextToken = targetsResponse.NextToken; } while (targetsResponse.NextToken is not null); var removeResponse = await _amazonEventBridge.RemoveTargetsAsync( new RemoveTargetsRequest() { Rule = ruleName, Ids = targetIds }); if (removeResponse.FailedEntryCount > 0) { removeResponse.FailedEntries.ForEach(e => { _logger.LogError( $"Failed to remove target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}"); }); } return removeResponse.HttpStatusCode == HttpStatusCode.OK; }
-
Pour API plus de détails, voir RemoveTargetsla section AWS SDK for .NET APIRéférence.
-