To subscribe an email address to an Amazon SNS topic in Ruby, you can use the AWS SDK for Ruby (aws-sdk-sns). Below is an example script that subscribes an email address to the `GeeksTopic` SNS topic and includes the confirmation step:
```
require 'aws-sdk-sns'
require 'securerandom'
# AWS credentials and region setup
Aws.config.update({
region: 'your-region', # replace with your AWS region
credentials: Aws::Credentials.new('your-access-key-id', 'your-secret-access-key') # replace with your AWS access key ID and secret access key
})
# AWS SNS client setup
sns_client = Aws::SNS::Client.new
# Specify the topic ARN or name
topic_name = 'GeeksTopic'
# Get the topic ARN by name
topic_arn = sns_client.create_topic(name: topic_name).topic_arn
# Get user email input
print 'Enter your email address: '
email_address = gets.chomp
# Generate a unique subscription confirmation endpoint
confirmation_endpoint = "https://example.com/confirm_subscription/#{SecureRandom.hex}"
# Subscribe to the topic
subscribe_response = sns_client.subscribe({
topic_arn: topic_arn,
protocol: 'email',
endpoint: email_address,
return_subscription_arn: true,
attributes: {
'ConfirmationEndpoint': confirmation_endpoint
}
})
puts "Subscription ARN: #{subscribe_response.subscription_arn}"
# Wait for user to confirm the subscription via email
puts 'Please check your email for a confirmation message and follow the instructions to confirm the subscription.'
puts "Confirmation endpoint: #{confirmation_endpoint}"
puts 'Press Enter when the subscription is confirmed...'
gets.chomp
puts 'Subscription confirmed!'
```
This Ruby script uses the AWS SDK for SNS to subscribe an email address to the `GeeksTopic` topic. It sets up AWS credentials and region, creates an SNS client, and prompts the user for their email address. The script generates a unique confirmation endpoint and subscribes the email address to the topic. It instructs the user to check their email for confirmation instructions, then waits for the user to press Enter when the subscription is confirmed. The script confirms the subscription and outputs the subscription ARN upon successful confirmation. This allows users to receive notifications from the specified SNS topic.