EventBridge SDK for Ruby を使用する例 - AWS SDK コード例

AWS Doc SDK Examples GitHub リポジトリには他にも AWS SDK例があります。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

EventBridge SDK for Ruby を使用する例

次のコード例は、 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています EventBridge。

「シナリオ」は、1 つのサービス内から、または他の 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'

指定された Amazon Simple Notification Service (Amazon SNS) トピックが、この関数に提供されるトピックの中に存在するかどうかを確認します。

# 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、E メールアドレスをサブスクライブして、そのトピックの通知を受信します。

# 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 CloudWatch Logs で発信者が利用できるロググループ内に存在しているかどうかをチェックします。

# 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

Logs で 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

CloudWatch Logs でログストリームにイベントを書き込みます。

# 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

Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを再起動し、関連するアクティビティに関する情報を CloudWatch Logs のログストリームに追加します。

# 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 Logs ロググループ内のすべてのログストリームのログ情報を表示します。

# 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
  • API 詳細については、 AWS SDK for Ruby APIリファレンスの以下のトピックを参照してください。