本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
EventBridge 用SDK于 Ruby 的示例
以下代码示例向您展示了如何使用with来执行操作和实现常见场景 EventBridge。 AWS SDK for Ruby
场景是向您展示如何通过在一个服务中调用多个函数或与其他 AWS 服务结合来完成特定任务的代码示例。
每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
主题
场景
以下代码示例展示了如何在 Amazon 中创建和触发规则 EventBridge。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 按照正确的顺序调用函数。
require 'aws-sdk-sns' require 'aws-sdk-iam' require 'aws-sdk-cloudwatchevents' require 'aws-sdk-ec2' require 'aws-sdk-cloudwatch' require 'aws-sdk-cloudwatchlogs' require 'securerandom'
检查为该功能提供的主题中是否存在指定的亚马逊简单通知服务 (AmazonSNS) 主题。
# Checks whether the specified Amazon SNS # topic exists among those provided to this function. # This is a helper function that is called by the topic_exists? function. # # @param topics [Array] An array of Aws::SNS::Types::Topic objects. # @param topic_arn [String] The ARN of the topic to find. # @return [Boolean] true if the topic ARN was found; otherwise, false. # @example # sns_client = Aws::SNS::Client.new(region: 'us-east-1') # response = sns_client.list_topics # if topic_found?( # response.topics, # 'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic' # ) # puts 'Topic found.' # end def topic_found?(topics, topic_arn) topics.each do |topic| return true if topic.topic_arn == topic_arn end false end
检查指定主题是否存在于 Amazon 中可供呼叫者使用的主题中SNS。
# Checks whether the specified topic exists among those available to the # caller in Amazon SNS. # # @param sns_client [Aws::SNS::Client] An initialized Amazon SNS client. # @param topic_arn [String] The ARN of the topic to find. # @return [Boolean] true if the topic ARN was found; otherwise, false. # @example # exit 1 unless topic_exists?( # Aws::SNS::Client.new(region: 'us-east-1'), # 'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic' # ) def topic_exists?(sns_client, topic_arn) puts "Searching for topic with ARN '#{topic_arn}'..." response = sns_client.list_topics if response.topics.count.positive? if topic_found?(response.topics, topic_arn) puts 'Topic found.' return true end while response.next_page? response = response.next_page next unless response.topics.count.positive? if topic_found?(response.topics, topic_arn) puts 'Topic found.' return true end end end puts 'Topic not found.' false rescue StandardError => e puts "Topic not found: #{e.message}" false end
在 Amazon 中创建主题,SNS然后订阅电子邮件地址以接收有关该主题的通知。
# Creates a topic in Amazon SNS # and then subscribes an email address to receive notifications to that topic. # # @param sns_client [Aws::SNS::Client] An initialized Amazon SNS client. # @param topic_name [String] The name of the topic to create. # @param email_address [String] The email address of the recipient to notify. # @return [String] The ARN of the topic that was created. # @example # puts create_topic( # Aws::SNS::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-topic', # 'mary@example.com' # ) def create_topic(sns_client, topic_name, email_address) puts "Creating the topic named '#{topic_name}'..." topic_response = sns_client.create_topic(name: topic_name) puts "Topic created with ARN '#{topic_response.topic_arn}'." subscription_response = sns_client.subscribe( topic_arn: topic_response.topic_arn, protocol: 'email', endpoint: email_address, return_subscription_arn: true ) puts 'Subscription created with ARN ' \ "'#{subscription_response.subscription_arn}'. Have the owner of the " \ "email address '#{email_address}' check their inbox in a few minutes " \ 'and confirm the subscription to start receiving notification emails.' topic_response.topic_arn rescue StandardError => e puts "Error creating or subscribing to topic: #{e.message}" 'Error' end
检查为该函数提供的角色中是否存在指定的 AWS Identity and Access Management (IAM) 角色。
# Checks whether the specified AWS Identity and Access Management (IAM) # role exists among those provided to this function. # This is a helper function that is called by the role_exists? function. # # @param roles [Array] An array of Aws::IAM::Role objects. # @param role_arn [String] The ARN of the role to find. # @return [Boolean] true if the role ARN was found; otherwise, false. # @example # iam_client = Aws::IAM::Client.new(region: 'us-east-1') # response = iam_client.list_roles # if role_found?( # response.roles, # 'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-ec2-state-change' # ) # puts 'Role found.' # end def role_found?(roles, role_arn) roles.each do |role| return true if role.arn == role_arn end false end
检查中调用者可用的角色中是否存在指定的角色IAM。
# Checks whether the specified role exists among those available to the # caller in AWS Identity and Access Management (IAM). # # @param iam_client [Aws::IAM::Client] An initialized IAM client. # @param role_arn [String] The ARN of the role to find. # @return [Boolean] true if the role ARN was found; otherwise, false. # @example # exit 1 unless role_exists?( # Aws::IAM::Client.new(region: 'us-east-1'), # 'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-ec2-state-change' # ) def role_exists?(iam_client, role_arn) puts "Searching for role with ARN '#{role_arn}'..." response = iam_client.list_roles if response.roles.count.positive? if role_found?(response.roles, role_arn) puts 'Role found.' return true end while response.next_page? response = response.next_page next unless response.roles.count.positive? if role_found?(response.roles, role_arn) puts 'Role found.' return true end end end puts 'Role not found.' false rescue StandardError => e puts "Role not found: #{e.message}" false end
在中创建角色IAM。
# Creates a role in AWS Identity and Access Management (IAM). # This role is used by a rule in Amazon EventBridge to allow # that rule to operate within the caller's account. # This role is designed to be used specifically by this code example. # # @param iam_client [Aws::IAM::Client] An initialized IAM client. # @param role_name [String] The name of the role to create. # @return [String] The ARN of the role that was created. # @example # puts create_role( # Aws::IAM::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-ec2-state-change' # ) def create_role(iam_client, role_name) puts "Creating the role named '#{role_name}'..." response = iam_client.create_role( assume_role_policy_document: { 'Version': '2012-10-17', 'Statement': [ { 'Sid': '', 'Effect': 'Allow', 'Principal': { 'Service': 'events.amazonaws.com' }, 'Action': 'sts:AssumeRole' } ] }.to_json, path: '/', role_name: role_name ) puts "Role created with ARN '#{response.role.arn}'." puts 'Adding access policy to role...' iam_client.put_role_policy( policy_document: { 'Version': '2012-10-17', 'Statement': [ { 'Sid': 'CloudWatchEventsFullAccess', 'Effect': 'Allow', 'Resource': '*', 'Action': 'events:*' }, { 'Sid': 'IAMPassRoleForCloudWatchEvents', 'Effect': 'Allow', 'Resource': 'arn:aws:iam::*:role/AWS_Events_Invoke_Targets', 'Action': 'iam:PassRole' } ] }.to_json, policy_name: 'CloudWatchEventsPolicy', role_name: role_name ) puts 'Access policy added to role.' response.role.arn rescue StandardError => e puts "Error creating role or adding policy to it: #{e.message}" puts 'If the role was created, you must add the access policy ' \ 'to the role yourself, or delete the role yourself and try again.' 'Error' end
检查为该函数提供的 EventBridge 规则中是否存在指定的规则。
# Checks whether the specified Amazon EventBridge rule exists among # those provided to this function. # This is a helper function that is called by the rule_exists? function. # # @param rules [Array] An array of Aws::CloudWatchEvents::Types::Rule objects. # @param rule_arn [String] The name of the rule to find. # @return [Boolean] true if the name of the rule was found; otherwise, false. # @example # cloudwatchevents_client = Aws::CloudWatch::Client.new(region: 'us-east-1') # response = cloudwatchevents_client.list_rules # if rule_found?(response.rules, 'aws-doc-sdk-examples-ec2-state-change') # puts 'Rule found.' # end def rule_found?(rules, rule_name) rules.each do |rule| return true if rule.name == rule_name end false end
检查指定规则是否存在于中调用者可用的规则中 EventBridge。
# Checks whether the specified rule exists among those available to the # caller in Amazon EventBridge. # # @param cloudwatchevents_client [Aws::CloudWatchEvents::Client] # An initialized Amazon EventBridge client. # @param rule_name [String] The name of the rule to find. # @return [Boolean] true if the rule name was found; otherwise, false. # @example # exit 1 unless rule_exists?( # Aws::CloudWatch::Client.new(region: 'us-east-1') # 'aws-doc-sdk-examples-ec2-state-change' # ) def rule_exists?(cloudwatchevents_client, rule_name) puts "Searching for rule with name '#{rule_name}'..." response = cloudwatchevents_client.list_rules if response.rules.count.positive? if rule_found?(response.rules, rule_name) puts 'Rule found.' return true end while response.next_page? response = response.next_page next unless response.rules.count.positive? if rule_found?(response.rules, rule_name) puts 'Rule found.' return true end end end puts 'Rule not found.' false rescue StandardError => e puts "Rule not found: #{e.message}" false end
在中创建规则 EventBridge。
# Creates a rule in Amazon EventBridge. # This rule is triggered whenever an available instance in # Amazon EC2 changes to the specified state. # This rule is designed to be used specifically by this code example. # # Prerequisites: # # - A role in AWS Identity and Access Management (IAM) that is designed # to be used specifically by this code example. # - A topic in Amazon SNS. # # @param cloudwatchevents_client [Aws::CloudWatchEvents::Client] # An initialized Amazon EventBridge client. # @param rule_name [String] The name of the rule to create. # @param rule_description [String] Some description for this rule. # @param instance_state [String] The state that available instances in # Amazon EC2 must change to, to # trigger this rule. # @param role_arn [String] The Amazon Resource Name (ARN) of the IAM role. # @param target_id [String] Some identifying string for the rule's target. # @param topic_arn [String] The ARN of the Amazon SNS topic. # @return [Boolean] true if the rule was created; otherwise, false. # @example # exit 1 unless rule_created?( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-ec2-state-change', # 'Triggers when any available EC2 instance starts.', # 'running', # 'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-ec2-state-change', # 'sns-topic', # 'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic' # ) def rule_created?( cloudwatchevents_client, rule_name, rule_description, instance_state, role_arn, target_id, topic_arn ) puts "Creating rule with name '#{rule_name}'..." put_rule_response = cloudwatchevents_client.put_rule( name: rule_name, description: rule_description, event_pattern: { 'source': [ 'aws.ec2' ], 'detail-type': [ 'EC2 Instance State-change Notification' ], 'detail': { 'state': [ instance_state ] } }.to_json, state: 'ENABLED', role_arn: role_arn ) puts "Rule created with ARN '#{put_rule_response.rule_arn}'." put_targets_response = cloudwatchevents_client.put_targets( rule: rule_name, targets: [ { id: target_id, arn: topic_arn } ] ) if put_targets_response.key?(:failed_entry_count) && put_targets_response.failed_entry_count.positive? puts 'Error(s) adding target to rule:' put_targets_response.failed_entries.each do |failure| puts failure.error_message end false else true end rescue StandardError => e puts "Error creating rule or adding target to rule: #{e.message}" puts 'If the rule was created, you must add the target ' \ 'to the rule yourself, or delete the rule yourself and try again.' false end
在 Amazon Logs 中查看调用者可用的日志组中是否存在指定的 CloudWatch 日志组。
# Checks to see whether the specified log group exists among those available # to the caller in Amazon CloudWatch Logs. # # @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] An initialized # Amazon CloudWatch Logs client. # @param log_group_name [String] The name of the log group to find. # @return [Boolean] true if the log group name was found; otherwise, false. # @example # exit 1 unless log_group_exists?( # Aws::CloudWatchLogs::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-cloudwatch-log' # ) def log_group_exists?(cloudwatchlogs_client, log_group_name) puts "Searching for log group with name '#{log_group_name}'..." response = cloudwatchlogs_client.describe_log_groups( log_group_name_prefix: log_group_name ) if response.log_groups.count.positive? response.log_groups.each do |log_group| if log_group.log_group_name == log_group_name puts 'Log group found.' return true end end end puts 'Log group not found.' false rescue StandardError => e puts "Log group not found: #{e.message}" false end
在 “日志” 中创建 CloudWatch 日志组。
# Creates a log group in Amazon CloudWatch Logs. # # @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] An initialized # Amazon CloudWatch Logs client. # @param log_group_name [String] The name of the log group to create. # @return [Boolean] true if the log group name was created; otherwise, false. # @example # exit 1 unless log_group_created?( # Aws::CloudWatchLogs::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-cloudwatch-log' # ) def log_group_created?(cloudwatchlogs_client, log_group_name) puts "Attempting to create log group with the name '#{log_group_name}'..." cloudwatchlogs_client.create_log_group(log_group_name: log_group_name) puts 'Log group created.' true rescue StandardError => e puts "Error creating log group: #{e.message}" false end
在 Logs 中将事件写入 CloudWatch 日志流。
# Writes an event to a log stream in Amazon CloudWatch Logs. # # Prerequisites: # # - A log group in Amazon CloudWatch Logs. # - A log stream within the log group. # # @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] An initialized # Amazon CloudWatch Logs client. # @param log_group_name [String] The name of the log group. # @param log_stream_name [String] The name of the log stream within # the log group. # @param message [String] The message to write to the log stream. # @param sequence_token [String] If available, the sequence token from the # message that was written immediately before this message. This sequence # token is returned by Amazon CloudWatch Logs whenever you programmatically # write a message to the log stream. # @return [String] The sequence token that is returned by # Amazon CloudWatch Logs after successfully writing the message to the # log stream. # @example # puts log_event( # Aws::EC2::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-cloudwatch-log' # '2020/11/19/53f985be-199f-408e-9a45-fc242df41fEX', # "Instance 'i-033c48ef067af3dEX' restarted.", # '495426724868310740095796045676567882148068632824696073EX' # ) def log_event( cloudwatchlogs_client, log_group_name, log_stream_name, message, sequence_token ) puts "Attempting to log '#{message}' to log stream '#{log_stream_name}'..." event = { log_group_name: log_group_name, log_stream_name: log_stream_name, log_events: [ { timestamp: (Time.now.utc.to_f.round(3) * 1_000).to_i, message: message } ] } event[:sequence_token] = sequence_token unless sequence_token.empty? response = cloudwatchlogs_client.put_log_events(event) puts 'Message logged.' response.next_sequence_token rescue StandardError => e puts "Message not logged: #{e.message}" end
重启亚马逊弹性计算云 (AmazonEC2) 实例,并将有关相关活动的信息添加到日志中的 CloudWatch 日志流中。
# Restarts an Amazon EC2 instance # and adds information about the related activity to a log stream # in Amazon CloudWatch Logs. # # Prerequisites: # # - The Amazon EC2 instance to restart. # - The log group in Amazon CloudWatch Logs to add related activity # information to. # # @param ec2_client [Aws::EC2::Client] An initialized Amazon EC2 client. # @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] # An initialized Amazon CloudWatch Logs client. # @param instance_id [String] The ID of the instance. # @param log_group_name [String] The name of the log group. # @return [Boolean] true if the instance was restarted and the information # was written to the log stream; otherwise, false. # @example # exit 1 unless instance_restarted?( # Aws::EC2::Client.new(region: 'us-east-1'), # Aws::CloudWatchLogs::Client.new(region: 'us-east-1'), # 'i-033c48ef067af3dEX', # 'aws-doc-sdk-examples-cloudwatch-log' # ) def instance_restarted?( ec2_client, cloudwatchlogs_client, instance_id, log_group_name ) log_stream_name = "#{Time.now.year}/#{Time.now.month}/#{Time.now.day}/" \ "#{SecureRandom.uuid}" cloudwatchlogs_client.create_log_stream( log_group_name: log_group_name, log_stream_name: log_stream_name ) sequence_token = '' puts "Attempting to stop the instance with the ID '#{instance_id}'. " \ 'This might take a few minutes...' ec2_client.stop_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_stopped, instance_ids: [instance_id]) puts 'Instance stopped.' sequence_token = log_event( cloudwatchlogs_client, log_group_name, log_stream_name, "Instance '#{instance_id}' stopped.", sequence_token ) puts 'Attempting to restart the instance. This might take a few minutes...' ec2_client.start_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_running, instance_ids: [instance_id]) puts 'Instance restarted.' sequence_token = log_event( cloudwatchlogs_client, log_group_name, log_stream_name, "Instance '#{instance_id}' restarted.", sequence_token ) true rescue StandardError => e puts 'Error creating log stream or stopping or restarting the instance: ' \ "#{e.message}" log_event( cloudwatchlogs_client, log_group_name, log_stream_name, "Error stopping or starting instance '#{instance_id}': #{e.message}", sequence_token ) false end
显示有关中规则活动的信息 EventBridge。
# Displays information about activity for a rule in Amazon EventBridge. # # Prerequisites: # # - A rule in Amazon EventBridge. # # @param cloudwatch_client [Amazon::CloudWatch::Client] An initialized # Amazon CloudWatch client. # @param rule_name [String] The name of the rule. # @param start_time [Time] The timestamp that determines the first datapoint # to return. Can also be expressed as DateTime, Date, Integer, or String. # @param end_time [Time] The timestamp that determines the last datapoint # to return. Can also be expressed as DateTime, Date, Integer, or String. # @param period [Integer] The interval, in seconds, to check for activity. # @example # display_rule_activity( # Aws::CloudWatch::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-ec2-state-change', # Time.now - 600, # Start checking from 10 minutes ago. # Time.now, # Check up until now. # 60 # Check every minute during those 10 minutes. # ) def display_rule_activity( cloudwatch_client, rule_name, start_time, end_time, period ) puts 'Attempting to display rule activity...' response = cloudwatch_client.get_metric_statistics( namespace: 'AWS/Events', metric_name: 'Invocations', dimensions: [ { name: 'RuleName', value: rule_name } ], start_time: start_time, end_time: end_time, period: period, statistics: ['Sum'], unit: 'Count' ) if response.key?(:datapoints) && response.datapoints.count.positive? puts "The event rule '#{rule_name}' was triggered:" response.datapoints.each do |datapoint| puts " #{datapoint.sum} time(s) at #{datapoint.timestamp}" end else puts "The event rule '#{rule_name}' was not triggered during the " \ 'specified time period.' end rescue StandardError => e puts "Error getting information about event rule activity: #{e.message}" end
显示日志组中所有日志流的 CloudWatch 日志信息。
# Displays log information for all of the log streams in a log group in # Amazon CloudWatch Logs. # # Prerequisites: # # - A log group in Amazon CloudWatch Logs. # # @param cloudwatchlogs_client [Amazon::CloudWatchLogs::Client] An initialized # Amazon CloudWatch Logs client. # @param log_group_name [String] The name of the log group. # @example # display_log_data( # Amazon::CloudWatchLogs::Client.new(region: 'us-east-1'), # 'aws-doc-sdk-examples-cloudwatch-log' # ) def display_log_data(cloudwatchlogs_client, log_group_name) puts 'Attempting to display log stream data for the log group ' \ "named '#{log_group_name}'..." describe_log_streams_response = cloudwatchlogs_client.describe_log_streams( log_group_name: log_group_name, order_by: 'LastEventTime', descending: true ) if describe_log_streams_response.key?(:log_streams) && describe_log_streams_response.log_streams.count.positive? describe_log_streams_response.log_streams.each do |log_stream| get_log_events_response = cloudwatchlogs_client.get_log_events( log_group_name: log_group_name, log_stream_name: log_stream.log_stream_name ) puts "\nLog messages for '#{log_stream.log_stream_name}':" puts '-' * (log_stream.log_stream_name.length + 20) if get_log_events_response.key?(:events) && get_log_events_response.events.count.positive? get_log_events_response.events.each do |event| puts event.message end else puts 'No log messages for this log stream.' end end end rescue StandardError => e puts 'Error getting information about the log streams or their messages: ' \ "#{e.message}" end
向来电者显示提醒,提醒他们手动清理他们不再需要的任何关联 AWS 资源。
# Displays a reminder to the caller to manually clean up any associated # AWS resources that they no longer need. # # @param topic_name [String] The name of the Amazon SNS topic. # @param role_name [String] The name of the IAM role. # @param rule_name [String] The name of the Amazon EventBridge rule. # @param log_group_name [String] The name of the Amazon CloudWatch Logs log group. # @param instance_id [String] The ID of the Amazon EC2 instance. # @example # manual_cleanup_notice( # 'aws-doc-sdk-examples-topic', # 'aws-doc-sdk-examples-cloudwatch-events-rule-role', # 'aws-doc-sdk-examples-ec2-state-change', # 'aws-doc-sdk-examples-cloudwatch-log', # 'i-033c48ef067af3dEX' # ) def manual_cleanup_notice( topic_name, role_name, rule_name, log_group_name, instance_id ) puts '-' * 10 puts 'Some of the following AWS resources might still exist in your account.' puts 'If you no longer want to use this code example, then to clean up' puts 'your AWS account and avoid unexpected costs, you might want to' puts 'manually delete any of the following resources if they exist:' puts "- The Amazon SNS topic named '#{topic_name}'." puts "- The IAM role named '#{role_name}'." puts "- The Amazon EventBridge rule named '#{rule_name}'." puts "- The Amazon CloudWatch Logs log group named '#{log_group_name}'." puts "- The Amazon EC2 instance with the ID '#{instance_id}'." end