diff --git a/.github/linters/.ruby-lint.yml b/.github/linters/.ruby-lint.yml index 4c15abe289d..079af2a51e9 100644 --- a/.github/linters/.ruby-lint.yml +++ b/.github/linters/.ruby-lint.yml @@ -3,18 +3,21 @@ # Rubocop Config file # ####################### Metrics/MethodLength: - Max: 25 + Max: 50 +Layout/LineLength: + Max: 150 Metrics/BlockLength: - Max: 75 + Max: 150 Metrics/AbcSize: - Max: 20 + Enabled: false +Metrics/PerceivedComplexity: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false Style/FrozenStringLiteralComment: Enabled: false Layout/EndOfLine: Enabled: false -Layout/LineLength: - Exclude: - - ruby/example_code/kms/decrypt_data.rb Naming/FileName: Enabled: false Style/HashSyntax: diff --git a/ruby/Gemfile b/ruby/Gemfile index e095acd5763..4cafb94cfc6 100644 --- a/ruby/Gemfile +++ b/ruby/Gemfile @@ -1,23 +1,23 @@ -source "https://rubygems.org" -ruby "3.1.2" +source 'https://rubygems.org' +ruby '3.1.2' -gem "aws-sdk" -gem "cli-ui" -gem "json" -gem "mail" -gem "mime" -gem "multi_json" -gem "openssl" -gem "open-uri" -gem "pp" -gem "rack" -gem "rack-test" -gem "rake" -gem "rspec" -gem "rubocop" -gem "rubocop-github" -gem "rubocop-rake" -gem "rubyzip" -gem "sequel" -gem "sinatra" -gem "zip" +gem 'aws-sdk' +gem 'cli-ui' +gem 'json' +gem 'mail' +gem 'mime' +gem 'multi_json' +gem 'openssl' +gem 'open-uri' +gem 'pp' +gem 'rack' +gem 'rack-test' +gem 'rake' +gem 'rspec' +gem 'rubocop' +gem 'rubocop-github' +gem 'rubocop-rake' +gem 'rubyzip' +gem 'sequel' +gem 'sinatra' +gem 'zip' diff --git a/ruby/Rakefile b/ruby/Rakefile index e89585237b4..4282079393e 100644 --- a/ruby/Rakefile +++ b/ruby/Rakefile @@ -1,27 +1,27 @@ # frozen_string_literal: true -require "rake/testtask" -require "rspec/core/rake_task" -require "rubocop" -require "rubocop/rake_task" -require "rubocop-rake" +require 'rake/testtask' +require 'rspec/core/rake_task' +require 'rubocop' +require 'rubocop/rake_task' +require 'rubocop-rake' task default: [:spec] Rake::TestTask.new do |t| - t.pattern = "*/**/tests/test_*.rb" + t.pattern = '*/**/tests/test_*.rb' t.verbose = true t.warning = false end -desc "Run specs." +desc 'Run specs.' RSpec::Core::RakeTask.new do |t| - t.pattern = "*/**/*_spec.rb" - t.rspec_opts = ["--tag", "integ", "--tag", "~@quarantine"] + t.pattern = '*/**/*_spec.rb' + t.rspec_opts = ['--tag', 'integ', '--tag', '~@quarantine'] end -desc "Run rubocop" +desc 'Run rubocop' RuboCop::RakeTask.new(:rubocop) do |t| - t.options = ["--config", "../.github/linters/.ruby-lint.yml"] - t.requires << "rubocop-rake" + t.options = ['--config', '../.github/linters/.ruby-lint.yml'] + t.requires << 'rubocop-rake' end diff --git a/ruby/cross_service_examples/feedback_sentiment_analyzer/comprehend_lambda_handler.rb b/ruby/cross_service_examples/feedback_sentiment_analyzer/comprehend_lambda_handler.rb index cd288945fb8..15a824ccd82 100644 --- a/ruby/cross_service_examples/feedback_sentiment_analyzer/comprehend_lambda_handler.rb +++ b/ruby/cross_service_examples/feedback_sentiment_analyzer/comprehend_lambda_handler.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: Apache-2.0 # frozen_string_literal: true -require "json" -require "aws-sdk-comprehend" -require "logger" +require 'json' +require 'aws-sdk-comprehend' +require 'logger' def lambda_handler(event:, context:) logger = Logger.new($stdout) @@ -12,19 +12,19 @@ def lambda_handler(event:, context:) logger.info("event:\n #{event}\n") logger.info("context:\n #{context}\n") - rekognition_client = Aws::Comprehend::Client.new(region: event["region"]) + comprehend_client = Aws::Comprehend::Client.new(region: event['region']) - source_text = event["source_text"] + source_text = event['source_text'] logger.info("payload:\n #{source_text}") - response = rekognition_client.detect_dominant_language({ text: source_text }) + response = comprehend_client.detect_dominant_language({ text: source_text }) language_code = response.languages[0].language_code logger.info("detected dominant language: #{language_code}") - response = rekognition_client.detect_sentiment({ + response = comprehend_client.detect_sentiment({ text: source_text, language_code: }) @@ -32,5 +32,5 @@ def lambda_handler(event:, context:) logger.info("Sentiment: #{response.sentiment}") logger.info("Sentiment Score: #{response.sentiment_score}") - { "sentiment" => response.sentiment, "language_code" => language_code } + { 'sentiment' => response.sentiment, 'language_code' => language_code } end diff --git a/ruby/cross_service_examples/feedback_sentiment_analyzer/polly_lambda_handler.rb b/ruby/cross_service_examples/feedback_sentiment_analyzer/polly_lambda_handler.rb index dfab46cb537..902887639cc 100644 --- a/ruby/cross_service_examples/feedback_sentiment_analyzer/polly_lambda_handler.rb +++ b/ruby/cross_service_examples/feedback_sentiment_analyzer/polly_lambda_handler.rb @@ -2,10 +2,10 @@ # SPDX-License-Identifier: Apache-2.0 # frozen_string_literal: true -require "json" -require "aws-sdk-polly" -require "aws-sdk-s3" -require "logger" +require 'json' +require 'aws-sdk-polly' +require 'aws-sdk-s3' +require 'logger' def lambda_handler(event, context) logger = Logger.new($stdout) @@ -14,22 +14,22 @@ def lambda_handler(event, context) logger.info("context:\n #{context}") # Create an instance of the Polly client - polly_client = Aws::Polly::Client.new(region: event["region"]) + polly_client = Aws::Polly::Client.new(region: event['region']) resp = polly_client.synthesize_speech({ - engine: "neural", - output_format: "mp3", - text: event["translated_text"], - voice_id: "Ruth" + engine: 'neural', + output_format: 'mp3', + text: event['translated_text'], + voice_id: 'Ruth' }) logger.info(resp.to_s) # Define the bucket name and file name for the MP3 file in S3 - bucket_name = event["bucket"] + bucket_name = event['bucket'] object_key = "#{event['object']}.mp3" - s3_client = Aws::S3::Client.new(region: event["region"]) + s3_client = Aws::S3::Client.new(region: event['region']) # Put the MP3 file to S3 s3_client.put_object( diff --git a/ruby/cross_service_examples/feedback_sentiment_analyzer/textract_lambda_handler.rb b/ruby/cross_service_examples/feedback_sentiment_analyzer/textract_lambda_handler.rb index 0ceaa839288..7d30de0e4cc 100644 --- a/ruby/cross_service_examples/feedback_sentiment_analyzer/textract_lambda_handler.rb +++ b/ruby/cross_service_examples/feedback_sentiment_analyzer/textract_lambda_handler.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: Apache-2.0 # frozen_string_literal: true -require "json" -require "aws-sdk-textract" -require "logger" +require 'json' +require 'aws-sdk-textract' +require 'logger' def lambda_handler(event:, context:) logger = Logger.new($stdout) @@ -13,13 +13,13 @@ def lambda_handler(event:, context:) logger.info("context:\n #{context}\n") # Create an instance of the Textract client - client = Aws::Textract::Client.new(region: event["region"]) + client = Aws::Textract::Client.new(region: event['region']) params = { document: { s3_object: { - bucket: event["bucket"], - name: event["object"] + bucket: event['bucket'], + name: event['object'] } } } @@ -30,12 +30,12 @@ def lambda_handler(event:, context:) extracted_words = [] response.blocks.each do |obj| - next unless obj.block_type.include?("LINE") + next unless obj.block_type.include?('LINE') extracted_words.append(obj.text) if obj.respond_to?(:text) && obj.text end logger.info("extracted words: #{extracted_words}") - extracted_words.join(" ") + extracted_words.join(' ') end diff --git a/ruby/cross_service_examples/feedback_sentiment_analyzer/translate_lambda_handler.rb b/ruby/cross_service_examples/feedback_sentiment_analyzer/translate_lambda_handler.rb index 8ed54062e96..bf390eebbe1 100644 --- a/ruby/cross_service_examples/feedback_sentiment_analyzer/translate_lambda_handler.rb +++ b/ruby/cross_service_examples/feedback_sentiment_analyzer/translate_lambda_handler.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: Apache-2.0 # frozen_string_literal: true -require "json" -require "aws-sdk-translate" -require "logger" +require 'json' +require 'aws-sdk-translate' +require 'logger' def lambda_handler(event:, context:) logger = Logger.new($stdout) @@ -13,11 +13,11 @@ def lambda_handler(event:, context:) logger.info("context:\n #{context}") # Create an instance of the Translate client - client = Aws::Translate::Client.new(region: event["region"]) + client = Aws::Translate::Client.new(region: event['region']) client.translate_text({ - text: event["extracted_text"], # required - source_language_code: event["source_language_code"], # required - target_language_code: "en" + text: event['extracted_text'], # required + source_language_code: event['source_language_code'], # required + target_language_code: 'en' }) end diff --git a/ruby/cross_service_examples/item_tracker/env/setup_scripts/create_table.rb b/ruby/cross_service_examples/item_tracker/env/setup_scripts/create_table.rb index 5f7c3dbe4de..c2679015011 100644 --- a/ruby/cross_service_examples/item_tracker/env/setup_scripts/create_table.rb +++ b/ruby/cross_service_examples/item_tracker/env/setup_scripts/create_table.rb @@ -3,16 +3,15 @@ # frozen_string_literal: true -require "yaml" -require "aws-sdk-rdsdataservice" -require "aws-sdk-rds" -require "aws-sdk-ses" +require 'yaml' +require 'aws-sdk-rdsdataservice' +require 'aws-sdk-rds' +require 'aws-sdk-ses' # A simple class for checking for databases and tables in an Amazon Aurora DB cluster. class SetupDatabase - def initialize - @config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), "../", "config.yml"))) + @config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), '../', 'config.yml'))) @data_client = Aws::RDSDataService::Client.new @rds_client = Aws::RDS::Client.new end @@ -20,12 +19,12 @@ def initialize # Checks if database exists. # @return [Boolean] false if DBClusterNotFoundFault; else true. def database_exists? - identifier = Aws::ARNParser.parse(@config["resource_arn"]) + identifier = Aws::ARNParser.parse(@config['resource_arn']) @rds_client.wait_until(:db_cluster_available, db_cluster_identifier: identifier.resource) do |w| w.max_attempts = 5 w.delay = 5 end - rescue Aws::RDS::Errors::DBClusterNotFoundFault => e + rescue Aws::RDS::Errors::DBClusterNotFoundFault false end @@ -34,18 +33,16 @@ def database_exists? def table_exists? resp = @data_client.execute_statement( { - resource_arn: @config["resource_arn"], - secret_arn: @config["secret_arn"], - sql: "show tables;", - database: @config["database"] + resource_arn: @config['resource_arn'], + secret_arn: @config['secret_arn'], + sql: 'show tables;', + database: @config['database'] } ) - resp[0].each { |table| - if table[0].string_value == @config["table_name"] - return true - end - } + resp[0].each do |table| + return true if table[0].string_value == @config['table_name'] + end false end @@ -54,27 +51,28 @@ def table_exists? def create_table @data_client.execute_statement( { - resource_arn: @config["resource_arn"], - secret_arn: @config["secret_arn"], - sql: "CREATE TABLE work_items (work_item_id INT AUTO_INCREMENT PRIMARY KEY, description VARCHAR(400), guide VARCHAR(45), status VARCHAR(400), username VARCHAR(45), archived TINYINT(4));", - database: @config["database"], + resource_arn: @config['resource_arn'], + secret_arn: @config['secret_arn'], + sql: 'CREATE TABLE work_items (work_item_id INT AUTO_INCREMENT PRIMARY KEY, +description VARCHAR(400), +guide VARCHAR(45), +status VARCHAR(400), +username VARCHAR(45), +archived TINYINT(4));', + + database: @config['database'] } ) end - end -if __FILE__ == $0 - # Checks for a database cluster & creates a table if none exists. +if __FILE__ == $PROGRAM_NAME + # Checks for a database cluster & creates a table if none exists. begin setup = SetupDatabase.new - if setup.database_exists? - unless setup.table_exists? - setup.create_table - end - else - raise "No DB cluster exists! Please run CDK script found in resources/cdk/aurora_serverless_app." - end + raise 'No DB cluster exists! Please run CDK script found in resources/cdk/aurora_serverless_app.' unless setup.database_exists? + + setup.create_table unless setup.table_exists? rescue StandardError => e raise "Failed while checking for or creating existing database/tables:\n#{e}" end diff --git a/ruby/cross_service_examples/item_tracker/env/setup_scripts/populate_table.rb b/ruby/cross_service_examples/item_tracker/env/setup_scripts/populate_table.rb index fafc55f9e45..74cc97399c5 100644 --- a/ruby/cross_service_examples/item_tracker/env/setup_scripts/populate_table.rb +++ b/ruby/cross_service_examples/item_tracker/env/setup_scripts/populate_table.rb @@ -3,25 +3,25 @@ # frozen_string_literal: true -require "yaml" -require "aws-sdk-rdsdataservice" -require_relative "../../src/aurora" +require 'yaml' +require 'aws-sdk-rdsdataservice' +require_relative '../../src/aurora' # A simple class for creating items in the database. class PopulateTable def initialize client = Aws::RDSDataService::Client.new - config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), "./../", "config.yml"))) + config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), './../', 'config.yml'))) @wrapper = AuroraActions.new(config, client) end def add_records 10.times do - username = ["ltolstoy", "jsteinbeck", "jkerouac", "wkhalifa"].sample + username = %w[ltolstoy jsteinbeck jkerouac wkhalifa].sample item_data = { - description: ["New feature", "Quick bugfix", "User research", "Tech debt"].sample, - guide: ["cpp", "python", "go", "ruby", "dotnet", "js", "php"].sample, - status: ["backlog", "icebox", "unrefined", "done", "in-progress"].sample, + description: ['New feature', 'Quick bugfix', 'User research', 'Tech debt'].sample, + guide: %w[cpp python go ruby dotnet js php].sample, + status: %w[backlog icebox unrefined done in-progress].sample, username: username, name: username, archived: [0, 1].sample @@ -31,8 +31,8 @@ def add_records end end -if __FILE__ == $0 - # Checks for Aurora DB cluster & creates table if none exists. +if __FILE__ == $PROGRAM_NAME + # Checks for Aurora DB cluster & creates table if none exists. begin setup = PopulateTable.new setup.add_records diff --git a/ruby/cross_service_examples/item_tracker/spec/aurora_actions_spec.rb b/ruby/cross_service_examples/item_tracker/spec/aurora_actions_spec.rb index 693f582fefe..bfde600edf7 100644 --- a/ruby/cross_service_examples/item_tracker/spec/aurora_actions_spec.rb +++ b/ruby/cross_service_examples/item_tracker/spec/aurora_actions_spec.rb @@ -3,65 +3,64 @@ # frozen_string_literal: true -require "yaml" -require "rspec" -require "aws-sdk-rdsdataservice" -require "aws-sdk-ses" -require_relative "../src/aurora" -require_relative "../src/report" -require_relative "../env/setup_scripts/create_table" -require_relative "../env/setup_scripts/create_table" +require 'yaml' +require 'rspec' +require 'aws-sdk-rdsdataservice' +require 'aws-sdk-ses' +require_relative '../src/aurora' +require_relative '../src/report' +require_relative '../env/setup_scripts/create_table' -describe "CRUD commands on Aurora > " do +describe 'CRUD commands on Aurora > ' do rds_client = Aws::RDSDataService::Client.new ses_client = Aws::SES::Client.new - config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), "./../env", "config.yml"))) + config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), './../env', 'config.yml'))) let(:wrapper) { AuroraActions.new(config, rds_client) } # TODO: Create DB & Table # TODO: Populate Table - it "Adds a new item" do + it 'Adds a new item' do item_data = { - description: "User research", - guide: "dotnet", - status: "active", - username: "krodgers" + description: 'User research', + guide: 'dotnet', + status: 'active', + username: 'krodgers' } id = wrapper.add_work_item(item_data) expect(id).to be_an_instance_of(Integer) end - it "Gets a specific item" do + it 'Gets a specific item' do data = wrapper.get_work_items(1) expect(data[0]).to be_an_instance_of(Hash) end - it "Gets multiple items" do + it 'Gets multiple items' do item_data = { - description: "Tech debt", - guide: "python", - status: "active", - username: "jmayer", + description: 'Tech debt', + guide: 'python', + status: 'active', + username: 'jmayer' } wrapper.add_work_item(item_data) data = wrapper.get_work_items expect(data[0]).to be_an_instance_of(Hash) end - it "Archives a specific item" do + it 'Archives a specific item' do id = wrapper.archive_work_item(5) expect(id).to be_an_instance_of(Array) expect(id.empty?) end - it "Gets archived items" do + it 'Gets archived items' do data = wrapper.get_work_items(nil, false) expect(data[0]).to be_an_instance_of(Hash) end - it "Make report" do - report = Report.new(wrapper, config["recipient_email"], ses_client) - report.post_report(config["recipient_email"]) + it 'Make report' do + report = Report.new(wrapper, config['recipient_email'], ses_client) + report.post_report(config['recipient_email']) end end diff --git a/ruby/cross_service_examples/item_tracker/src/app.rb b/ruby/cross_service_examples/item_tracker/src/app.rb index 02957826ea6..ceb5552ccd1 100644 --- a/ruby/cross_service_examples/item_tracker/src/app.rb +++ b/ruby/cross_service_examples/item_tracker/src/app.rb @@ -3,60 +3,60 @@ # frozen_string_literal: true -require "sinatra" -require "sinatra/cors" -require_relative "aurora" -require_relative "report" -require "aws-sdk-rdsdataservice" -require "aws-sdk-ses" +require 'sinatra' +require 'sinatra/cors' +require_relative 'aurora' +require_relative 'report' +require 'aws-sdk-rdsdataservice' +require 'aws-sdk-ses' client = Aws::RDSDataService::Client.new ses_client = Aws::SES::Client.new -config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), "../", "env", "config.yml"))) +config = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), '../', 'env', 'config.yml'))) wrapper = AuroraActions.new(config, client) -reporter = Report.new(wrapper, config["recipient_email"], ses_client) +reporter = Report.new(wrapper, config['recipient_email'], ses_client) configure do set :port, 8080 - set :allow_origin, "*" + set :allow_origin, '*' enable :cross_origin end before do - response.headers["Access-Control-Allow-Origin"] = "*" - response.headers["Access-Control-Allow-Methods"] = "HEAD,GET,PUT,POST,DELETE,OPTIONS" - response.headers["Access-Control-Allow-Headers"] = "Content-Type" + response.headers['Access-Control-Allow-Origin'] = '*' + response.headers['Access-Control-Allow-Methods'] = 'HEAD,GET,PUT,POST,DELETE,OPTIONS' + response.headers['Access-Control-Allow-Headers'] = 'Content-Type' end -get "/api/items" do +get '/api/items' do items = wrapper.get_work_items(nil, params[:archived]) items.to_json halt 204 end -post "/api/items" do +post '/api/items' do payload = MultiJson.load(request.body.read) wrapper.add_work_item(payload) halt 204 end -get "/api/items/:item_id" do +get '/api/items/:item_id' do wrapper.get_work_items(:item_id, nil) halt 204 end -put %r{/api/items/([\w]+):archive} do |id| - body wrapper.archive_work_item(id) ? "true" : "false" +put %r{/api/items/(\w+):archive} do |id| + body wrapper.archive_work_item(id) ? 'true' : 'false' halt 204 end post %r{/api/items:report} do - reporter.post_report(config["recipient_email"]) + reporter.post_report(config['recipient_email']) halt 204 end -options "*" do - response.headers["Access-Control-Allow-Methods"] = "HEAD,GET,PUT,POST,DELETE,OPTIONS" - response.headers["Access-Control-Allow-Headers"] = "Content-Type" +options '*' do + response.headers['Access-Control-Allow-Methods'] = 'HEAD,GET,PUT,POST,DELETE,OPTIONS' + response.headers['Access-Control-Allow-Headers'] = 'Content-Type' halt 204 end diff --git a/ruby/cross_service_examples/item_tracker/src/aurora.rb b/ruby/cross_service_examples/item_tracker/src/aurora.rb index 020f675a51d..4b50854ed15 100644 --- a/ruby/cross_service_examples/item_tracker/src/aurora.rb +++ b/ruby/cross_service_examples/item_tracker/src/aurora.rb @@ -3,21 +3,20 @@ # frozen_string_literal: true -require "logger" -require "sequel" -require "multi_json" -require_relative "report" +require 'logger' +require 'sequel' +require 'multi_json' +require_relative 'report' # Issues commands directly to the Amazon Relational Database Service (Amazon RDS), including SQL statements. class AuroraActions - # @param config [List] # @param rds_client [AWS::RDS::Client] An Amazon RDS client. def initialize(config, rds_client) - @cluster = config["resource_arn"] - @secret = config["secret_arn"] - @db_name = config["database"] - @table_name = config["table_name"] + @cluster = config['resource_arn'] + @secret = config['secret_arn'] + @db_name = config['database'] + @table_name = config['table_name'] @rds_client = rds_client @model = Sequel::Database.new @logger = Logger.new($stdout) @@ -34,7 +33,7 @@ def get_work_items(item_id = nil, include_archived = nil) sql = sql.where(work_item_id: item_id.to_i) if item_id sql = _format_sql(sql.sql) @logger.info("Prepared GET query: #{sql}") - results = run_statement(sql, "get") + results = run_statement(sql, 'get') response = parse_work_items(results) @logger.info("Received GET response: #{response}") response @@ -54,7 +53,7 @@ def add_work_item(data) ) sql = _format_sql(sql) @logger.info("Prepared POST query: #{sql}") - response = run_statement(sql, "post") + response = run_statement(sql, 'post') id = response[0][:long_value] @logger.info("Successfully created work_item_id: #{id}") id @@ -67,7 +66,7 @@ def archive_work_item(item_id) sql = @model.from(@table_name.to_sym).where(work_item_id: item_id).update_sql(archived: 1) # 1 is true, 0 is false sql = _format_sql(sql) @logger.info("Prepared PUT query: #{sql}") - run_statement(sql, "put") + run_statement(sql, 'put') end private @@ -84,7 +83,7 @@ def _format_sql(sql) # @param [String] # @return [Boolean] def true?(obj) - obj.to_s.downcase == "true" + obj.to_s.downcase == 'true' end # Helper method to centralize error formatting. @@ -100,8 +99,8 @@ def handle_error(msg) def parse_work_items(results) output = [] results.each do |x| - x["name"] = x["username"] # Note: Duplicative name/username field added due to front-end bug. - x["id"] = x["work_item_id"] # Note: Duplicative id/work_item_id field added due to front-end bug. + x['name'] = x['username'] # NOTE: Duplicative name/username field added due to front-end bug. + x['id'] = x['work_item_id'] # NOTE: Duplicative id/work_item_id field added due to front-end bug. output.append(x) end output @@ -113,16 +112,12 @@ def parse_work_items(results) # @return [RuntimeError, Boolean] If valid response, true; otherwise, RuntimeError. def validate_response(response, method) case method - when "get" - if response[:formatted_records].nil? - raise "Expected formatted records returned from GET action." - end - when "post" - if response[:number_of_records_updated] < 1 - raise "Expected at least 1 updated record from POST action." - end + when 'get' + raise 'Expected formatted records returned from GET action.' if response[:formatted_records].nil? + when 'post' + raise 'Expected at least 1 updated record from POST action.' if response[:number_of_records_updated] < 1 end - @logger.info("SQL call successful. Response body validated.") + @logger.info('SQL call successful. Response body validated.') end # Transforms inconsistent return bodies into something API-friendly. @@ -131,7 +126,7 @@ def validate_response(response, method) # @return [Array] Containing zero or more hashes of response data. def format_response(response, method) case method - when "get" + when 'get' JSON.parse(response[:formatted_records]) # response example: # [{"work_item_id"=>1, @@ -140,14 +135,14 @@ def format_response(response, method) # "status"=>"in-progress", # "username"=>"wkhalifa", # "archived"=>1}] - when "post" + when 'post' [response[:generated_fields][0].to_h] # response example: # [{:long_value=>21}] - when "put" + when 'put' [] else - raise "Configuration method. Must provide: get, post, or put." + raise 'Configuration method. Must provide: get, post, or put.' end end @@ -161,12 +156,11 @@ def run_statement(sql, method) 'resource_arn': @cluster, 'secret_arn': @secret, 'sql': sql, - 'format_records_as': "JSON" + 'format_records_as': 'JSON' } response = @rds_client.execute_statement(**run_args) validate_response(response, method) format_response(response, method) - rescue Aws::RDS::Errors::ServiceError => e handle_error("SQL execution on #{@db_name} failed within RDS:\n#{e}") rescue StandardError => e diff --git a/ruby/cross_service_examples/item_tracker/src/report.rb b/ruby/cross_service_examples/item_tracker/src/report.rb index d299b6c1d50..f1de6dbf809 100644 --- a/ruby/cross_service_examples/item_tracker/src/report.rb +++ b/ruby/cross_service_examples/item_tracker/src/report.rb @@ -10,13 +10,13 @@ # When the list of items is longer than a specified threshold, it is included as a CSV # attachment to the email instead of in the body of the email itself. -require "logger" -require "erb" -require "json" -require "csv" -require "mail" -require "mime" -require_relative "aurora" +require 'logger' +require 'erb' +require 'json' +require 'csv' +require 'mail' +require 'mime' +require_relative 'aurora' # Encapsulates a report resource that gets work items from an # Amazon Aurora database and uses Amazon SES to send emails about them. @@ -29,21 +29,21 @@ def initialize(db_wrapper, email_sender, ses_client) @db_wrapper = db_wrapper @email_sender = email_sender @ses_client = ses_client - @timestamp = Time.now.strftime("%H:%M on %h %d %Y") + @timestamp = Time.now.strftime('%H:%M on %h %d %Y') end # Formats the report as a ready-to-send email message, including attachment def format_mime_message(email_recipient, text, html, attachment) - @logger.info("Beginning to format message...") + @logger.info('Beginning to format message...') mail = Mail.new mail.sender = @email_sender mail.to = email_recipient - mail.subject = "Work Items Report" - mail.content_type = "multipart/mixed" + mail.subject = 'Work Items Report' + mail.content_type = 'multipart/mixed' html_part = Mail::Part.new do - content_type "text/html; charset=UTF-8" + content_type 'text/html; charset=UTF-8' body html end @@ -51,16 +51,16 @@ def format_mime_message(email_recipient, text, html, attachment) body text end - mail.part content_type: "multipart/alternative" do |p| + mail.part content_type: 'multipart/alternative' do |p| p.html_part = html_part p.text_part = text_part end mail.attachments[attachment] = File.read(attachment) - mail.content_type = mail.content_type.gsub("alternative", "mixed") - mail.charset= "UTF-8" - mail.content_transfer_encoding = "quoted-printable" + mail.content_type = mail.content_type.gsub('alternative', 'mixed') + mail.charset = 'UTF-8' + mail.content_transfer_encoding = 'quoted-printable' @logger.info(mail) mail end @@ -70,7 +70,7 @@ def format_mime_message(email_recipient, text, html, attachment) # @param work_items: The work items to include in the CSV output. # @return: Work items rendered to a string in CSV format. def render_csv(work_items, file_name) - CSV.open(file_name, "w", headers: work_items.first.keys) do |csv| + CSV.open(file_name, 'w', headers: work_items.first.keys) do |csv| work_items.each do |h| csv << h.values end @@ -79,9 +79,9 @@ def render_csv(work_items, file_name) # @return html_part def render_template(template_file, work_items) - erb = ERB.new(File.read(template_file), trim_mode: "%<>") + erb = ERB.new(File.read(template_file), trim_mode: '%<>') @work_items = work_items - @timestamp = Time.now.strftime("%H:%M on %h %d %Y") + @timestamp = Time.now.strftime('%H:%M on %h %d %Y') erb.result(binding) end @@ -97,23 +97,23 @@ def render_template(template_file, work_items) # @param recipient_email [String] # @return [Integer] An HTTP result code. def post_report(recipient_email) - @logger.info("Getting work items for report.") + @logger.info('Getting work items for report.') work_items = @db_wrapper.get_work_items @logger.debug("Prepared the following items for a report:\n#{work_items}") - file_name = File.join(File.dirname(__FILE__), "templates", "report.html.erb") + file_name = File.join(File.dirname(__FILE__), 'templates', 'report.html.erb') html_report = render_template(file_name, work_items) @logger.debug("HTML report: \n#{html_report}") - text_report = "" + text_report = '' work_items.each do |work_item| text_report += "\n#{work_item.to_json}" end @logger.debug("Text report: \n#{text_report}") - @logger.info("Successfully rendered work_items into HTML & text.") + @logger.info('Successfully rendered work_items into HTML & text.') - csv_file = "data.csv" + csv_file = 'data.csv' render_csv(work_items, csv_file) @logger.info("Successfully saved work items as CSV attachment: #{csv_file}") @@ -121,35 +121,34 @@ def post_report(recipient_email) if work_items.count > 5 mime_msg = format_mime_message(recipient_email, text_report, html_report, csv_file) @ses_client.send_raw_email({ - source: @email_sender, - destinations: [recipient_email], - raw_message: { - data: mime_msg.to_s - } - }) - 204 + source: @email_sender, + destinations: [recipient_email], + raw_message: { + data: mime_msg.to_s + } + }) else @ses_client.send_email({ - source: @email_sender, - destination: { - to_addresses: [recipient_email] - }, - message: { - subject: { - data: "Work Items Report" - }, - body: { - text: { - data: text_report - }, - html: { - data: html_report - } - } - } - }) - 204 + source: @email_sender, + destination: { + to_addresses: [recipient_email] + }, + message: { + subject: { + data: 'Work Items Report' + }, + body: { + text: { + data: text_report + }, + html: { + data: html_report + } + } + } + }) end + 204 rescue StandardError => e @logger.error("Couldn't send email: #{e}") 500 diff --git a/ruby/example_code/cloudtrail/create_trail.rb b/ruby/example_code/cloudtrail/create_trail.rb index a75b86a81a6..9362da4743c 100644 --- a/ruby/example_code/cloudtrail/create_trail.rb +++ b/ruby/example_code/cloudtrail/create_trail.rb @@ -6,12 +6,11 @@ # Demonstrates how to create an AWS CloudTrail trail # snippet-start:[cloudtrail.Ruby.createTrail] -require "aws-sdk-cloudtrail" # v2: require 'aws-sdk' -require "aws-sdk-s3" -require "aws-sdk-sts" +require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' +require 'aws-sdk-s3' +require 'aws-sdk-sts' def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, bucket_name) - resp = sts_client.get_caller_identity({}) account_id = resp.account @@ -19,28 +18,28 @@ def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, b s3_client.create_bucket(bucket: bucket_name) begin policy = { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Sid" => "AWSCloudTrailAclCheck20150319", - "Effect" => "Allow", - "Principal" => { - "Service" => "cloudtrail.amazonaws.com" + 'Sid' => 'AWSCloudTrailAclCheck20150319', + 'Effect' => 'Allow', + 'Principal' => { + 'Service' => 'cloudtrail.amazonaws.com' }, - "Action" => "s3:GetBucketAcl", - "Resource" => "arn:aws:s3:::#{bucket_name}" + 'Action' => 's3:GetBucketAcl', + 'Resource' => "arn:aws:s3:::#{bucket_name}" }, { - "Sid" => "AWSCloudTrailWrite20150319", - "Effect" => "Allow", - "Principal" => { - "Service" => "cloudtrail.amazonaws.com" + 'Sid' => 'AWSCloudTrailWrite20150319', + 'Effect' => 'Allow', + 'Principal' => { + 'Service' => 'cloudtrail.amazonaws.com' }, - "Action" => "s3:PutObject", - "Resource" => "arn:aws:s3:::#{bucket_name}/AWSLogs/#{account_id}/*", - "Condition" => { - "StringEquals" => { - "s3:x-amz-acl" => "bucket-owner-full-control" + 'Action' => 's3:PutObject', + 'Resource' => "arn:aws:s3:::#{bucket_name}/AWSLogs/#{account_id}/*", + 'Condition' => { + 'StringEquals' => { + 's3:x-amz-acl' => 'bucket-owner-full-control' } } } @@ -56,9 +55,9 @@ def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, b begin cloudtrail_client.create_trail({ - name: trail_name, # required - s3_bucket_name: bucket_name # required - }) + name: trail_name, # required + s3_bucket_name: bucket_name # required + }) puts "Successfully created trail: #{trail_name}." rescue StandardError => e @@ -69,7 +68,7 @@ def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, b # snippet-end:[cloudtrail.Ruby.createTrail] end -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME @s3_client = Aws::S3::Client.new @sts_client = Aws::STS::Client.new @cloudtrail_client = Aws::CloudTrail::Client.new diff --git a/ruby/example_code/cloudtrail/delete_trail.rb b/ruby/example_code/cloudtrail/delete_trail.rb index cba7c567afb..fc5a667712a 100644 --- a/ruby/example_code/cloudtrail/delete_trail.rb +++ b/ruby/example_code/cloudtrail/delete_trail.rb @@ -1,25 +1,25 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Demonstrates how to delete an AWS CloudTrail trail - -require "aws-sdk-cloudtrail" # v2: require 'aws-sdk' - -def delete_trail_example(client, trail_name) - # snippet-start:[cloudtrail.Ruby.deleteTrail] - client.delete_trail({ - name: trail_name # required - }) - puts "Successfully deleted trail: " + trail_name -rescue StandardError => err - puts "Got error trying to delete trail: " + trail_name + ":" - puts err - exit 1 -end -# snippet-end:[cloudtrail.Ruby.deleteTrail] - -if __FILE__ == $0 - client = Aws::CloudTrail::Client.new - trail_name = "example-code-trail-9830" - delete_trail_example(client, trail_name) -end +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Demonstrates how to delete an AWS CloudTrail trail + +require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' + +def delete_trail_example(client, trail_name) + # snippet-start:[cloudtrail.Ruby.deleteTrail] + client.delete_trail({ + name: trail_name # required + }) + puts "Successfully deleted trail: #{trail_name}" +rescue StandardError => e + puts "Got error trying to delete trail: #{trail_name}:" + puts e + exit 1 +end +# snippet-end:[cloudtrail.Ruby.deleteTrail] + +if __FILE__ == $PROGRAM_NAME + client = Aws::CloudTrail::Client.new + trail_name = 'example-code-trail-9830' + delete_trail_example(client, trail_name) +end diff --git a/ruby/example_code/cloudtrail/describe_trails.rb b/ruby/example_code/cloudtrail/describe_trails.rb index fa10719c953..5318d9ee21a 100644 --- a/ruby/example_code/cloudtrail/describe_trails.rb +++ b/ruby/example_code/cloudtrail/describe_trails.rb @@ -4,21 +4,21 @@ # Demonstrates how to retrieve details about AWS CloudTrail trails # snippet-start:[cloudtrail.Ruby.describeTrails] -require "aws-sdk-cloudtrail" # v2: require 'aws-sdk' +require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' def describe_trails_example(client) resp = client.describe_trails({}) puts "Found #{resp.trail_list.count} trail(s)." resp.trail_list.each do |trail| - puts "Name: " + trail.name - puts "S3 bucket name: " + trail.s3_bucket_name + puts "Name: #{trail.name}" + puts "S3 bucket name: #{trail.s3_bucket_name}" puts end # snippet-end:[cloudtrail.Ruby.describeTrails] end -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME client = Aws::CloudTrail::Client.new describe_trails_example(client) end diff --git a/ruby/example_code/cloudtrail/lookup_events.rb b/ruby/example_code/cloudtrail/lookup_events.rb index f4c086d67f7..6dc6f3c4bcd 100644 --- a/ruby/example_code/cloudtrail/lookup_events.rb +++ b/ruby/example_code/cloudtrail/lookup_events.rb @@ -6,7 +6,7 @@ # Demonstrates how to look up AWS CloudTrail trail events # snippet-start:[cloudtrail.Ruby.lookupEvents] -require "aws-sdk-cloudtrail" # v2: require 'aws-sdk' +require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' # @param [Object] client def lookup_events_example(client) @@ -16,18 +16,18 @@ def lookup_events_example(client) puts "Event name: #{e.event_name}" puts "Event ID: #{e.event_id}" puts "Event time: #{e.event_time}" - puts "Resources:" + puts 'Resources:' e.resources.each do |r| puts " Name: #{r.resource_name}" puts " Type: #{r.resource_type}" - puts "" + puts '' end end end # snippet-end:[cloudtrail.Ruby.lookupEvents] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME client = Aws::CloudTrail::Client.new lookup_events_example(client) end diff --git a/ruby/example_code/cloudtrail/spec/cloudtrail_spec.rb b/ruby/example_code/cloudtrail/spec/cloudtrail_spec.rb index d7598cfb3cb..4a6ab6d86a4 100644 --- a/ruby/example_code/cloudtrail/spec/cloudtrail_spec.rb +++ b/ruby/example_code/cloudtrail/spec/cloudtrail_spec.rb @@ -3,32 +3,32 @@ # frozen_string_literal: true -require_relative "../create_trail" -require_relative "../delete_trail" -require_relative "../describe_trails" -require_relative "../lookup_events" -require "rspec" +require_relative '../create_trail' +require_relative '../delete_trail' +require_relative '../describe_trails' +require_relative '../lookup_events' +require 'rspec' -describe "TestTrail" do +describe 'TestTrail' do let(:s3_client) { Aws::S3::Client.new } let(:sts_client) { Aws::STS::Client.new } let(:cloudtrail_client) { Aws::CloudTrail::Client.new } let(:trail_name) { "example-code-trail-#{rand(10**4)}" } let(:bucket_name) { "example-code-bucket-#{rand(10**4)}" } - it "create" do + it 'create' do create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, bucket_name) end - it "describe" do + it 'describe' do describe_trails_example(cloudtrail_client) end - it "lookup" do + it 'lookup' do lookup_events_example(cloudtrail_client) end - it "delete" do + it 'delete' do delete_trail_example(cloudtrail_client, trail_name) end end diff --git a/ruby/example_code/cloudwatch/README.md b/ruby/example_code/cloudwatch/README.md index 5e18e07506c..e0d65667ec6 100644 --- a/ruby/example_code/cloudwatch/README.md +++ b/ruby/example_code/cloudwatch/README.md @@ -35,9 +35,9 @@ Code excerpts that show you how to call individual service functions. - [DescribeAlarms](alarm_basics.rb#L8) - [DescribeAlarmsForMetric](show_alarms.rb#L8) -- [DisableAlarmActions](alarm_actions.rb#L93) -- [ListMetrics](metrics_basics.rb#L69) -- [PutMetricAlarm](alarm_basics.rb#L30) +- [DisableAlarmActions](alarm_actions.rb#L94) +- [ListMetrics](metrics_basics.rb#L70) +- [PutMetricAlarm](alarm_basics.rb#L31) - [PutMetricData](metrics_basics.rb#L8) diff --git a/ruby/example_code/cloudwatch/alarm_actions.rb b/ruby/example_code/cloudwatch/alarm_actions.rb index 0a684292952..b2cd312672b 100644 --- a/ruby/example_code/cloudwatch/alarm_actions.rb +++ b/ruby/example_code/cloudwatch/alarm_actions.rb @@ -6,7 +6,7 @@ # 2. Disable all actions for an alarm. # snippet-start:[cloudwatch.Ruby.createAnAlarm] -require "aws-sdk-cloudwatch" +require 'aws-sdk-cloudwatch' # Creates or updates an alarm in Amazon CloudWatch. @@ -84,11 +84,12 @@ def alarm_created_or_updated?( threshold: threshold, comparison_operator: comparison_operator ) - return true + true rescue StandardError => e puts "Error creating alarm: #{e.message}" - return false + false end + # snippet-end:[cloudwatch.Ruby.createAnAlarm] # snippet-start:[cloudwatch.Ruby.disableAnAlarm] # Disables an alarm in Amazon CloudWatch. @@ -108,39 +109,44 @@ def alarm_created_or_updated?( # ) def alarm_actions_disabled?(cloudwatch_client, alarm_name) cloudwatch_client.disable_alarm_actions(alarm_names: [alarm_name]) - return true + true rescue StandardError => e puts "Error disabling alarm actions: #{e.message}" - return false + false end # Example usage: def run_me - alarm_name = "ObjectsInBucket" - alarm_description = "Objects exist in this bucket for more than 1 day." - metric_name = "NumberOfObjects" + alarm_name = 'ObjectsInBucket' + alarm_description = 'Objects exist in this bucket for more than 1 day.' + metric_name = 'NumberOfObjects' # Notify this Amazon Simple Notification Service (Amazon SNS) topic when # the alarm transitions to the ALARM state. - alarm_actions = ["arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic"] - namespace = "AWS/S3" - statistic = "Average" + alarm_actions = ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'] + namespace = 'AWS/S3' + statistic = 'Average' dimensions = [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] period = 86_400 # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds). - unit = "Count" + unit = 'Count' evaluation_periods = 1 # More than one day. threshold = 1 # One object. - comparison_operator = "GreaterThanThreshold" # More than one object. + comparison_operator = 'GreaterThanThreshold' # More than one object. # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. - region = "us-east-1" + region = 'us-east-1' cloudwatch_client = Aws::CloudWatch::Client.new(region: region) diff --git a/ruby/example_code/cloudwatch/alarm_basics.rb b/ruby/example_code/cloudwatch/alarm_basics.rb index a4e57d055d7..bafbbbbdac7 100644 --- a/ruby/example_code/cloudwatch/alarm_basics.rb +++ b/ruby/example_code/cloudwatch/alarm_basics.rb @@ -6,7 +6,7 @@ # 2. Create or update an alarm. # 3. Delete an alarm. # snippet-start:[cloudwatch.Ruby.getAlarmList] -require "aws-sdk-cloudwatch" +require 'aws-sdk-cloudwatch' # Lists the names of available Amazon CloudWatch alarms. # @@ -21,11 +21,12 @@ def list_alarms(cloudwatch_client) puts alarm.alarm_name end else - puts "No alarms found." + puts 'No alarms found.' end rescue StandardError => e puts "Error getting information about alarms: #{e.message}" end + # snippet-end:[cloudwatch.Ruby.getAlarmList] # snippet-start:[cloudwatch.Ruby.PutMetricAlarm] # Creates or updates an alarm in Amazon CloudWatch. @@ -104,11 +105,12 @@ def alarm_created_or_updated?( threshold: threshold, comparison_operator: comparison_operator ) - return true + true rescue StandardError => e puts "Error creating alarm: #{e.message}" - return false + false end + # snippet-end:[cloudwatch.Ruby.PutMetricAlarm] # snippet-start:[cloudwatch.Ruby.deleteAlarm] # Deletes an alarm in Amazon CloudWatch. @@ -128,43 +130,48 @@ def alarm_created_or_updated?( # ) def alarm_deleted?(cloudwatch_client, alarm_name) cloudwatch_client.delete_alarms(alarm_names: [alarm_name]) - return true + true rescue StandardError => e puts "Error deleting alarm: #{e.message}" - return false + false end # Example usage: def run_me - alarm_name = "ObjectsInBucket" - alarm_description = "Objects exist in this bucket for more than 1 day." - metric_name = "NumberOfObjects" + alarm_name = 'ObjectsInBucket' + alarm_description = 'Objects exist in this bucket for more than 1 day.' + metric_name = 'NumberOfObjects' # Notify this Amazon Simple Notification Service (Amazon SNS) topic when # the alarm transitions to the ALARM state. - alarm_actions = ["arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic"] - namespace = "AWS/S3" - statistic = "Average" + alarm_actions = ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'] + namespace = 'AWS/S3' + statistic = 'Average' dimensions = [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] period = 86_400 # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds). - unit = "Count" + unit = 'Count' evaluation_periods = 1 # More than one day. threshold = 1 # One object. - comparison_operator = "GreaterThanThreshold" # More than one object. + comparison_operator = 'GreaterThanThreshold' # More than one object. # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. - region = "us-east-1" + region = 'us-east-1' cloudwatch_client = Aws::CloudWatch::Client.new(region: region) - puts "Available Amazon CloudWatch alarms:" + puts 'Available Amazon CloudWatch alarms:' list_alarms(cloudwatch_client) if alarm_created_or_updated?( diff --git a/ruby/example_code/cloudwatch/create_alarm.rb b/ruby/example_code/cloudwatch/create_alarm.rb index 0712d7407aa..d40166c1def 100644 --- a/ruby/example_code/cloudwatch/create_alarm.rb +++ b/ruby/example_code/cloudwatch/create_alarm.rb @@ -5,7 +5,7 @@ # snippet-start:[cloudwatch.Ruby.createAlarm] -require "aws-sdk-cloudwatch" +require 'aws-sdk-cloudwatch' # @param cloudwatch_client [Aws::CloudWatch::Client] # An initialized CloudWatch client. @@ -81,39 +81,44 @@ def alarm_created_or_updated?( threshold: threshold, comparison_operator: comparison_operator ) - return true + true rescue StandardError => e puts "Error creating alarm: #{e.message}" - return false + false end # Example usage: def run_me - alarm_name = "ObjectsInBucket" - alarm_description = "Objects exist in this bucket for more than 1 day." - metric_name = "NumberOfObjects" + alarm_name = 'ObjectsInBucket' + alarm_description = 'Objects exist in this bucket for more than 1 day.' + metric_name = 'NumberOfObjects' # Notify this Amazon Simple Notification Service (Amazon SNS) topic when # the alarm transitions to the ALARM state. - alarm_actions = ["arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic"] - namespace = "AWS/S3" - statistic = "Average" + alarm_actions = ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'] + namespace = 'AWS/S3' + statistic = 'Average' dimensions = [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] period = 86_400 # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds). - unit = "Count" + unit = 'Count' evaluation_periods = 1 # More than one day. threshold = 1 # One object. - comparison_operator = "GreaterThanThreshold" # More than one object. + comparison_operator = 'GreaterThanThreshold' # More than one object. # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. - region = "us-east-1" + region = 'us-east-1' cloudwatch_client = Aws::CloudWatch::Client.new(region: region) diff --git a/ruby/example_code/cloudwatch/metrics_basics.rb b/ruby/example_code/cloudwatch/metrics_basics.rb index a255abccc69..085ce70e22e 100644 --- a/ruby/example_code/cloudwatch/metrics_basics.rb +++ b/ruby/example_code/cloudwatch/metrics_basics.rb @@ -6,7 +6,7 @@ # 2. List available metrics for a metric namespace in Amazon CloudWatch. # snippet-start:[cloudwatch.Ruby.addDataPoint] -require "aws-sdk-cloudwatch" +require 'aws-sdk-cloudwatch' # Adds a datapoint to a metric in Amazon CloudWatch. # @@ -59,12 +59,13 @@ def datapoint_added_to_metric?( ) puts "Added data about '#{metric_name}' to namespace " \ "'#{metric_namespace}'." - return true + true rescue StandardError => e puts "Error adding data about '#{metric_name}' to namespace " \ "'#{metric_namespace}': #{e.message}" - return false + false end + # snippet-end:[cloudwatch.Ruby.addDataPoint] # snippet-start:[cloudwatch.Ruby.listMetrics] # Lists available metrics for a metric namespace in Amazon CloudWatch. @@ -84,58 +85,58 @@ def list_metrics_for_namespace(cloudwatch_client, metric_namespace) response.metrics.each do |metric| puts " Metric name: #{metric.metric_name}" if metric.dimensions.count.positive? - puts " Dimensions:" + puts ' Dimensions:' metric.dimensions.each do |dimension| puts " Name: #{dimension.name}, Value: #{dimension.value}" end else - puts "No dimensions found." + puts 'No dimensions found.' end end else puts "No metrics found for namespace '#{metric_namespace}'. " \ - "Note that it could take up to 15 minutes for recently-added metrics " \ - "to become available." + 'Note that it could take up to 15 minutes for recently-added metrics ' \ + 'to become available.' end end # Example usage: def run_me - metric_namespace = "SITE/TRAFFIC" + metric_namespace = 'SITE/TRAFFIC' # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch. - region = "us-east-1" + region = 'us-east-1' cloudwatch_client = Aws::CloudWatch::Client.new(region: region) # Add three datapoints. - puts "Continuing..." unless datapoint_added_to_metric?( + puts 'Continuing...' unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, - "UniqueVisitors", - "SiteName", - "example.com", + 'UniqueVisitors', + 'SiteName', + 'example.com', 5_885.0, - "Count" + 'Count' ) - puts "Continuing..." unless datapoint_added_to_metric?( + puts 'Continuing...' unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, - "UniqueVisits", - "SiteName", - "example.com", + 'UniqueVisits', + 'SiteName', + 'example.com', 8_628.0, - "Count" + 'Count' ) - puts "Continuing..." unless datapoint_added_to_metric?( + puts 'Continuing...' unless datapoint_added_to_metric?( cloudwatch_client, metric_namespace, - "PageViews", - "PageURL", - "example.html", + 'PageViews', + 'PageURL', + 'example.html', 18_057.0, - "Count" + 'Count' ) puts "Metrics for namespace '#{metric_namespace}':" diff --git a/ruby/example_code/cloudwatch/show_alarms.rb b/ruby/example_code/cloudwatch/show_alarms.rb index e7f4fa7bf87..7ff734028dc 100644 --- a/ruby/example_code/cloudwatch/show_alarms.rb +++ b/ruby/example_code/cloudwatch/show_alarms.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-cloudwatch" +require 'aws-sdk-cloudwatch' # Displays information about available metric alarms in Amazon CloudWatch. @@ -17,52 +17,52 @@ def describe_metric_alarms(cloudwatch_client) if response.metric_alarms.count.positive? response.metric_alarms.each do |alarm| - puts "-" * 16 - puts "Name: " + alarm.alarm_name - puts "State value: " + alarm.state_value - puts "State reason: " + alarm.state_reason - puts "Metric: " + alarm.metric_name - puts "Namespace: " + alarm.namespace - puts "Statistic: " + alarm.statistic - puts "Period: " + alarm.period.to_s - puts "Unit: " + alarm.unit.to_s - puts "Eval. periods: " + alarm.evaluation_periods.to_s - puts "Threshold: " + alarm.threshold.to_s - puts "Comp. operator: " + alarm.comparison_operator + puts '-' * 16 + puts "Name: #{alarm.alarm_name}" + puts "State value: #{alarm.state_value}" + puts "State reason: #{alarm.state_reason}" + puts "Metric: #{alarm.metric_name}" + puts "Namespace: #{alarm.namespace}" + puts "Statistic: #{alarm.statistic}" + puts "Period: #{alarm.period}" + puts "Unit: #{alarm.unit}" + puts "Eval. periods: #{alarm.evaluation_periods}" + puts "Threshold: #{alarm.threshold}" + puts "Comp. operator: #{alarm.comparison_operator}" if alarm.key?(:ok_actions) && alarm.ok_actions.count.positive? - puts "OK actions:" + puts 'OK actions:' alarm.ok_actions.each do |a| - puts " " + a + puts " #{a}" end end if alarm.key?(:alarm_actions) && alarm.alarm_actions.count.positive? - puts "Alarm actions:" + puts 'Alarm actions:' alarm.alarm_actions.each do |a| - puts " " + a + puts " #{a}" end end if alarm.key?(:insufficient_data_actions) && - alarm.insufficient_data_actions.count.positive? - puts "Insufficient data actions:" + alarm.insufficient_data_actions.count.positive? + puts 'Insufficient data actions:' alarm.insufficient_data_actions.each do |a| - puts " " + a + puts " #{a}" end end - puts "Dimensions:" + puts 'Dimensions:' if alarm.key?(:dimensions) && alarm.dimensions.count.positive? alarm.dimensions.each do |d| - puts " Name: " + d.name + ", Value: " + d.value + puts " Name: #{d.name}, Value: #{d.value}" end else - puts " None for this alarm." + puts ' None for this alarm.' end end else - puts "No alarms found." + puts 'No alarms found.' end rescue StandardError => e puts "Error getting information about alarms: #{e.message}" @@ -70,23 +70,23 @@ def describe_metric_alarms(cloudwatch_client) # Example usage: def run_me - region = "" + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby cw-ruby-example-show-alarms.rb REGION" - puts "Example: ruby cw-ruby-example-show-alarms.rb us-east-1" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby cw-ruby-example-show-alarms.rb REGION' + puts 'Example: ruby cw-ruby-example-show-alarms.rb us-east-1' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - region = "us-east-1" + region = 'us-east-1' # Otherwise, use the values as specified at the command prompt. else region = ARGV[0] end cloudwatch_client = Aws::CloudWatch::Client.new(region: region) - puts "Available alarms:" + puts 'Available alarms:' describe_metric_alarms(cloudwatch_client) end diff --git a/ruby/example_code/cloudwatch/spec/alarm_actions_spec.rb b/ruby/example_code/cloudwatch/spec/alarm_actions_spec.rb index 956b0d5531c..18db5c2cea5 100644 --- a/ruby/example_code/cloudwatch/spec/alarm_actions_spec.rb +++ b/ruby/example_code/cloudwatch/spec/alarm_actions_spec.rb @@ -1,33 +1,38 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../alarm_actions" -require "rspec" +require_relative '../alarm_actions' +require 'rspec' -describe "#alarm_created_or_updated?", :quarantine do - let(:alarm_name) { "ObjectsInBucket" } - let(:alarm_description) { "Objects exist in this bucket for more than 1 day." } - let(:metric_name) { "NumberOfObjects" } - let(:alarm_actions) { ["arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic"] } - let(:namespace) { "AWS/S3" } - let(:statistic) { "Average" } +describe '#alarm_created_or_updated?', :quarantine do + let(:alarm_name) { 'ObjectsInBucket' } + let(:alarm_description) { 'Objects exist in this bucket for more than 1 day.' } + let(:metric_name) { 'NumberOfObjects' } + let(:alarm_actions) { ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'] } + let(:namespace) { 'AWS/S3' } + let(:statistic) { 'Average' } let(:dimensions) do [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] end let(:period) { 86_400 } - let(:unit) { "Count" } + let(:unit) { 'Count' } let(:evaluation_periods) { 1 } let(:threshold) { 1 } - let(:comparison_operator) { "GreaterThanThreshold" } + let(:comparison_operator) { 'GreaterThanThreshold' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { @@ -36,7 +41,7 @@ ) end - it "creates or updates an alarm" do + it 'creates or updates an alarm' do expect( alarm_created_or_updated?( cloudwatch_client, @@ -57,8 +62,8 @@ end end -describe "#alarm_actions_disabled?", :integ do - let(:alarm_name) { "ObjectsInBucket" } +describe '#alarm_actions_disabled?', :integ do + let(:alarm_name) { 'ObjectsInBucket' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { @@ -67,7 +72,7 @@ ) end - it "disables actions for an alarm" do + it 'disables actions for an alarm' do expect( alarm_actions_disabled?(cloudwatch_client, alarm_name) ).to be(true) diff --git a/ruby/example_code/cloudwatch/spec/alarm_basics_spec.rb b/ruby/example_code/cloudwatch/spec/alarm_basics_spec.rb index d2bc268d413..da3b926ca39 100644 --- a/ruby/example_code/cloudwatch/spec/alarm_basics_spec.rb +++ b/ruby/example_code/cloudwatch/spec/alarm_basics_spec.rb @@ -1,17 +1,17 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../alarm_basics" -require "rspec" +require_relative '../alarm_basics' +require 'rspec' -describe "#list_alarms", :integ do +describe '#list_alarms', :integ do let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { describe_alarms: { metric_alarms: [ { - alarm_name: "ObjectsInBucket" + alarm_name: 'ObjectsInBucket' } ] } @@ -19,35 +19,40 @@ ) end - it "lists information about alarms" do + it 'lists information about alarms' do expect { list_alarms(cloudwatch_client) }.not_to raise_error end end -describe "#alarm_created_or_updated?", :integ do - let(:alarm_name) { "ObjectsInBucket" } - let(:alarm_description) { "Objects exist in this bucket for more than 1 day." } - let(:metric_name) { "NumberOfObjects" } - let(:alarm_actions) { ["arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic"] } - let(:namespace) { "AWS/S3" } - let(:statistic) { "Average" } +describe '#alarm_created_or_updated?', :integ do + let(:alarm_name) { 'ObjectsInBucket' } + let(:alarm_description) { 'Objects exist in this bucket for more than 1 day.' } + let(:metric_name) { 'NumberOfObjects' } + let(:alarm_actions) { ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'] } + let(:namespace) { 'AWS/S3' } + let(:statistic) { 'Average' } let(:dimensions) do [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] end let(:period) { 86_400 } - let(:unit) { "Count" } + let(:unit) { 'Count' } let(:evaluation_periods) { 1 } let(:threshold) { 1 } - let(:comparison_operator) { "GreaterThanThreshold" } + let(:comparison_operator) { 'GreaterThanThreshold' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { @@ -56,7 +61,7 @@ ) end - it "creates or updates an alarm" do + it 'creates or updates an alarm' do expect( alarm_created_or_updated?( cloudwatch_client, @@ -77,8 +82,8 @@ end end -describe "#alarm_deleted?", :integ do - let(:alarm_name) { "ObjectsInBucket" } +describe '#alarm_deleted?', :integ do + let(:alarm_name) { 'ObjectsInBucket' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { @@ -87,7 +92,7 @@ ) end - it "deletes an alarm" do + it 'deletes an alarm' do expect( alarm_deleted?(cloudwatch_client, alarm_name) ).to be(true) diff --git a/ruby/example_code/cloudwatch/spec/create_alarm_spec.rb b/ruby/example_code/cloudwatch/spec/create_alarm_spec.rb index 39cfd6ffcb4..e22f91f787c 100644 --- a/ruby/example_code/cloudwatch/spec/create_alarm_spec.rb +++ b/ruby/example_code/cloudwatch/spec/create_alarm_spec.rb @@ -1,33 +1,38 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../create_alarm" -require "rspec" +require_relative '../create_alarm' +require 'rspec' -describe "#alarm_created_or_updated?", :integ do - let(:alarm_name) { "ObjectsInBucket" } - let(:alarm_description) { "Objects exist in this bucket for more than 1 day." } - let(:metric_name) { "NumberOfObjects" } - let(:alarm_actions) { ["arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic"] } - let(:namespace) { "AWS/S3" } - let(:statistic) { "Average" } +describe '#alarm_created_or_updated?', :integ do + let(:alarm_name) { 'ObjectsInBucket' } + let(:alarm_description) { 'Objects exist in this bucket for more than 1 day.' } + let(:metric_name) { 'NumberOfObjects' } + let(:alarm_actions) { ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'] } + let(:namespace) { 'AWS/S3' } + let(:statistic) { 'Average' } let(:dimensions) do [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] end let(:period) { 86_400 } - let(:unit) { "Count" } + let(:unit) { 'Count' } let(:evaluation_periods) { 1 } let(:threshold) { 1 } - let(:comparison_operator) { "GreaterThanThreshold" } + let(:comparison_operator) { 'GreaterThanThreshold' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { @@ -36,7 +41,7 @@ ) end - it "creates or updates an alarm" do + it 'creates or updates an alarm' do expect( alarm_created_or_updated?( cloudwatch_client, diff --git a/ruby/example_code/cloudwatch/spec/metrics_basic_spec.rb b/ruby/example_code/cloudwatch/spec/metrics_basic_spec.rb index b34f51fb501..16bf2f7ff9d 100644 --- a/ruby/example_code/cloudwatch/spec/metrics_basic_spec.rb +++ b/ruby/example_code/cloudwatch/spec/metrics_basic_spec.rb @@ -1,16 +1,16 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../metrics_basics" -require "rspec" +require_relative '../metrics_basics' +require 'rspec' -describe "#datapoint_added_to_metric?", :integ do - let(:metric_namespace) { "SITE/TRAFFIC" } - let(:metric_name) { "UniqueVisitors" } - let(:dimension_name) { "SiteName" } - let(:dimension_value) { "example.com" } +describe '#datapoint_added_to_metric?', :integ do + let(:metric_namespace) { 'SITE/TRAFFIC' } + let(:metric_name) { 'UniqueVisitors' } + let(:dimension_name) { 'SiteName' } + let(:dimension_value) { 'example.com' } let(:metric_value) { 5_885.0 } - let(:metric_unit) { "Count" } + let(:metric_unit) { 'Count' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { @@ -19,7 +19,7 @@ ) end - it "adds a datapoint to a metric" do + it 'adds a datapoint to a metric' do expect( datapoint_added_to_metric?( cloudwatch_client, @@ -34,19 +34,19 @@ end end -describe "list_metrics_for_namespace", :integ do - let(:metric_namespace) { "SITE/TRAFFIC" } +describe 'list_metrics_for_namespace', :integ do + let(:metric_namespace) { 'SITE/TRAFFIC' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { list_metrics: { metrics: [ { - metric_name: "UniqueVisitors", + metric_name: 'UniqueVisitors', dimensions: [ { - name: "SiteName", - value: "example.com" + name: 'SiteName', + value: 'example.com' } ] } @@ -56,9 +56,9 @@ ) end - it "lists the metrics for a namespace" do - expect { + it 'lists the metrics for a namespace' do + expect do list_metrics_for_namespace(cloudwatch_client, metric_namespace) - }.not_to raise_error + end.not_to raise_error end end diff --git a/ruby/example_code/cloudwatch/spec/send_events_ec2_spec.rb b/ruby/example_code/cloudwatch/spec/send_events_ec2_spec.rb index acc0957d6ae..1541d96db07 100644 --- a/ruby/example_code/cloudwatch/spec/send_events_ec2_spec.rb +++ b/ruby/example_code/cloudwatch/spec/send_events_ec2_spec.rb @@ -1,11 +1,11 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../show_alarms" -require "rspec" +require_relative '../show_alarms' +require 'rspec' -describe "#topic_exists?", :quarantine do - let(:topic_arn) { "arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic" } +describe '#topic_exists?', :quarantine do + let(:topic_arn) { 'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic' } let(:sns_client) do Aws::SNS::Client.new( stub_responses: { @@ -18,16 +18,16 @@ ) end - it "checks whether a topic exists" do + it 'checks whether a topic exists' do expect( topic_exists?(sns_client, topic_arn) ).to be(true) end end -describe "#create_topic", :quarantine do - let(:topic_name) { "aws-doc-sdk-examples-topic" } - let(:email_address) { "mary@example.com" } +describe '#create_topic', :quarantine do + let(:topic_name) { 'aws-doc-sdk-examples-topic' } + let(:email_address) { 'mary@example.com' } let(:topic_arn) { "arn:aws:sns:us-east-1:111111111111:#{topic_name}" } let(:sns_client) do Aws::SNS::Client.new( @@ -42,15 +42,15 @@ ) end - it "creates a topic" do + it 'creates a topic' do expect( create_topic(sns_client, topic_name, email_address) ).to eq(topic_arn) end end -describe "#role_exists?", :quarantine do - let(:role_name) { "aws-doc-sdk-examples-cloudwatch-events-rule-role" } +describe '#role_exists?', :quarantine do + let(:role_name) { 'aws-doc-sdk-examples-cloudwatch-events-rule-role' } let(:role_arn) { "arn:aws:iam::111111111111:role/#{role_name}" } let(:iam_client) do Aws::IAM::Client.new( @@ -58,25 +58,25 @@ list_roles: { roles: [ arn: role_arn, - path: "/", + path: '/', role_name: role_name, - role_id: "AIDAJQABLZS4A3EXAMPLE", - create_date: Time.iso8601("2020-11-17T14:19:00-08:00") + role_id: 'AIDAJQABLZS4A3EXAMPLE', + create_date: Time.iso8601('2020-11-17T14:19:00-08:00') ] } } ) end - it "checks whether a role exists" do + it 'checks whether a role exists' do expect( role_exists?(iam_client, role_arn) ).to be(true) end end -describe "#create_role", :quarantine do - let(:role_name) { "aws-doc-sdk-examples-cloudwatch-events-rule-role" } +describe '#create_role', :quarantine do + let(:role_name) { 'aws-doc-sdk-examples-cloudwatch-events-rule-role' } let(:role_arn) { "arn:aws:iam::111111111111:role/#{role_name}" } let(:iam_client) do Aws::IAM::Client.new( @@ -84,25 +84,25 @@ create_role: { role: { arn: role_arn, - path: "/", + path: '/', role_name: role_name, - role_id: "AIDAJQABLZS4A3EXAMPLE", - create_date: Time.iso8601("2020-11-17T14:19:00-08:00") + role_id: 'AIDAJQABLZS4A3EXAMPLE', + create_date: Time.iso8601('2020-11-17T14:19:00-08:00') } } } ) end - it "creates a role" do + it 'creates a role' do expect( create_role(iam_client, role_name) ).to eq(role_arn) end end -describe "#rule_exists?", :quarantine do - let(:rule_name) { "aws-doc-sdk-examples-ec2-state-change" } +describe '#rule_exists?', :quarantine do + let(:rule_name) { 'aws-doc-sdk-examples-ec2-state-change' } let(:cloudwatchevents_client) do Aws::CloudWatchEvents::Client.new( stub_responses: { @@ -117,20 +117,20 @@ ) end - it "checks whether a rule exists" do + it 'checks whether a rule exists' do expect( rule_exists?(cloudwatchevents_client, rule_name) ).to be(true) end end -describe "#rule_created?", :quarantine do - let(:rule_name) { "aws-doc-sdk-examples-ec2-state-change" } - let(:rule_description) { "Triggers when any available EC2 instance starts." } - let(:instance_state) { "running" } - let(:role_arn) { "arn:aws:iam::111111111111:role/aws-doc-sdk-examples-cloudwatch-events-rule-role" } - let(:target_id) { "sns-topic" } - let(:topic_arn) { "arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic" } +describe '#rule_created?', :quarantine do + let(:rule_name) { 'aws-doc-sdk-examples-ec2-state-change' } + let(:rule_description) { 'Triggers when any available EC2 instance starts.' } + let(:instance_state) { 'running' } + let(:role_arn) { 'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-cloudwatch-events-rule-role' } + let(:target_id) { 'sns-topic' } + let(:topic_arn) { 'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic' } let(:cloudwatchevents_client) do Aws::CloudWatchEvents::Client.new( stub_responses: { @@ -142,7 +142,7 @@ ) end - it "creates a rule" do + it 'creates a rule' do expect( rule_created?( cloudwatchevents_client, @@ -157,8 +157,8 @@ end end -describe "#log_group_exists?", :quarantine do - let(:log_group_name) { "aws-doc-sdk-examples-cloudwatch-log" } +describe '#log_group_exists?', :quarantine do + let(:log_group_name) { 'aws-doc-sdk-examples-cloudwatch-log' } let(:cloudwatchlogs_client) do Aws::CloudWatchLogs::Client.new( stub_responses: { @@ -171,15 +171,15 @@ ) end - it "checks whether a log group exists" do + it 'checks whether a log group exists' do expect( log_group_exists?(cloudwatchlogs_client, log_group_name) ).to be(true) end end -describe "#log_group_created?", :quarantine do - let(:log_group_name) { "aws-doc-sdk-examples-cloudwatch-log" } +describe '#log_group_created?', :quarantine do + let(:log_group_name) { 'aws-doc-sdk-examples-cloudwatch-log' } let(:cloudwatchlogs_client) do Aws::CloudWatchLogs::Client.new( stub_responses: { @@ -188,20 +188,21 @@ ) end - it "creates a log group" do + it 'creates a log group' do expect( log_group_created?(cloudwatchlogs_client, log_group_name) ).to be(true) end end -describe "#log_event", :quarantine do - let(:log_group_name) { "aws-doc-sdk-examples-cloudwatch-log" } - let(:log_stream_name) { "#{Time.now.year}/#{Time.now.month}/#{Time.now.day}/" \ +describe '#log_event', :quarantine do + let(:log_group_name) { 'aws-doc-sdk-examples-cloudwatch-log' } + let(:log_stream_name) do + "#{Time.now.year}/#{Time.now.month}/#{Time.now.day}/" \ "#{SecureRandom.uuid}" - } + end let(:message) { "Instance 'i-033c48ef067af3dEX' restarted." } - let(:sequence_token) { "495426724868310740095796045676567882148068632824696073EX" } + let(:sequence_token) { '495426724868310740095796045676567882148068632824696073EX' } let(:cloudwatchlogs_client) do Aws::CloudWatchLogs::Client.new( stub_responses: { @@ -212,7 +213,7 @@ ) end - it "logs an event" do + it 'logs an event' do expect( log_event( cloudwatchlogs_client, @@ -220,14 +221,14 @@ log_stream_name, message, sequence_token - ) + ) ).to eq(sequence_token) end end -describe "#instance_restarted?", :quarantine do - let(:instance_id) { "i-033c48ef067af3dEX" } - let(:log_group_name) { "aws-doc-sdk-examples-cloudwatch-log" } +describe '#instance_restarted?', :quarantine do + let(:instance_id) { 'i-033c48ef067af3dEX' } + let(:log_group_name) { 'aws-doc-sdk-examples-cloudwatch-log' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -236,12 +237,12 @@ { current_state: { code: 80, - name: "stopped" + name: 'stopped' }, instance_id: instance_id, previous_state: { code: 16, - name: "running" + name: 'running' } } ] @@ -251,12 +252,12 @@ { current_state: { code: 16, - name: "running" + name: 'running' }, instance_id: instance_id, previous_state: { code: 80, - name: "stopped" + name: 'stopped' } } ] @@ -268,7 +269,7 @@ instance_id: instance_id, state: { code: 80, - name: "stopped" + name: 'stopped' } ] ] @@ -279,7 +280,7 @@ instance_id: instance_id, state: { code: 16, - name: "running" + name: 'running' } ] ] @@ -296,7 +297,7 @@ ) end - it "restarts an instance and logs related events" do + it 'restarts an instance and logs related events' do expect( instance_restarted?( ec2_client, @@ -308,8 +309,8 @@ end end -describe "#display_rule_activity", :quarantine do - let(:rule_name) { "aws-doc-sdk-examples-ec2-state-change" } +describe '#display_rule_activity', :quarantine do + let(:rule_name) { 'aws-doc-sdk-examples-ec2-state-change' } let(:start_time) { Time.now - 600 } let(:end_time) { Time.now } let(:period) { 60 } @@ -320,11 +321,11 @@ datapoints: [ { sum: 1.0, - timestamp: Time.iso8601("2020-11-17T14:19:00-08:00") + timestamp: Time.iso8601('2020-11-17T14:19:00-08:00') }, { sum: 2.0, - timestamp: Time.iso8601("2020-11-17T14:32:00-08:00") + timestamp: Time.iso8601('2020-11-17T14:32:00-08:00') } ] } @@ -332,8 +333,8 @@ ) end - it "displays activity for a rule" do - expect { + it 'displays activity for a rule' do + expect do display_rule_activity( cloudwatch_client, rule_name, @@ -341,15 +342,16 @@ end_time, period ) - }.not_to raise_error + end.not_to raise_error end end -describe "#display_log_data", :quarantine do - let(:log_group_name) { "aws-doc-sdk-examples-cloudwatch-log" } - let(:log_stream_name) { "#{Time.now.year}/#{Time.now.month}/#{Time.now.day}/" \ +describe '#display_log_data', :quarantine do + let(:log_group_name) { 'aws-doc-sdk-examples-cloudwatch-log' } + let(:log_stream_name) do + "#{Time.now.year}/#{Time.now.month}/#{Time.now.day}/" \ "#{SecureRandom.uuid}" - } + end let(:cloudwatchlogs_client) do Aws::CloudWatchLogs::Client.new( stub_responses: { @@ -374,9 +376,9 @@ ) end - it "displays log streams data" do - expect { + it 'displays log streams data' do + expect do display_log_data(cloudwatchlogs_client, log_group_name) - }.not_to raise_error + end.not_to raise_error end end diff --git a/ruby/example_code/cloudwatch/spec/show_alarms_spec.rb b/ruby/example_code/cloudwatch/spec/show_alarms_spec.rb index 910fdbeb80f..51b71bf2b65 100644 --- a/ruby/example_code/cloudwatch/spec/show_alarms_spec.rb +++ b/ruby/example_code/cloudwatch/spec/show_alarms_spec.rb @@ -1,44 +1,49 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../show_alarms" -require "rspec" +require_relative '../show_alarms' +require 'rspec' -describe "#describe_metric_alarms", :integ do - let(:metric_namespace) { "SITE/TRAFFIC" } - let(:metric_name) { "UniqueVisitors" } - let(:dimension_name) { "SiteName" } - let(:dimension_value) { "example.com" } +describe '#describe_metric_alarms', :integ do + let(:metric_namespace) { 'SITE/TRAFFIC' } + let(:metric_name) { 'UniqueVisitors' } + let(:dimension_name) { 'SiteName' } + let(:dimension_value) { 'example.com' } let(:metric_value) { 5_885.0 } - let(:metric_unit) { "Count" } + let(:metric_unit) { 'Count' } let(:cloudwatch_client) do Aws::CloudWatch::Client.new( stub_responses: { describe_alarms: { metric_alarms: [ { - alarm_name: "ObjectsInBucket", - state_value: "INSUFFICIENT_DATA", - state_reason: "Unchecked: Initial alarm creation", - metric_name: "NumberOfObjects", - namespace: "AWS/S3", - statistic: "Average", + alarm_name: 'ObjectsInBucket', + state_value: 'INSUFFICIENT_DATA', + state_reason: 'Unchecked: Initial alarm creation', + metric_name: 'NumberOfObjects', + namespace: 'AWS/S3', + statistic: 'Average', period: 86_400, - unit: "Count", + unit: 'Count', evaluation_periods: 1, threshold: 1.0, - comparison_operator: "GreaterThanThreshold", + comparison_operator: 'GreaterThanThreshold', ok_actions: [ - "arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic" + 'arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic' ], dimensions: [ { +<<<<<<< HEAD name: "BucketName", value: "amzn-s3-demo-bucket" +======= + name: 'BucketName', + value: 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) }, { - name: "StorageType", - value: "AllStorageTypes" + name: 'StorageType', + value: 'AllStorageTypes' } ] } @@ -48,7 +53,7 @@ ) end - it "shows information about metric alarms" do + it 'shows information about metric alarms' do expect { describe_metric_alarms(cloudwatch_client) }.not_to raise_error end end diff --git a/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-build-project.rb b/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-build-project.rb index c67c70b19fd..bc4c0036ae8 100644 --- a/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-build-project.rb +++ b/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-build-project.rb @@ -2,12 +2,12 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[codebuild.Ruby.buildProject] -require "aws-sdk-codebuild" # v2: require 'aws-sdk' +require 'aws-sdk-codebuild' # v2: require 'aws-sdk' -project_name = "" +project_name = '' if ARGV.length != 1 - puts "You must supply the name of the project to build" + puts 'You must supply the name of the project to build' exit 1 else project_name = ARGV[0] @@ -17,8 +17,8 @@ begin client.start_build(project_name: project_name) - puts "Building project " + project_name -rescue StandardError => ex - puts "Error building project: " + ex.message + puts "Building project #{project_name}" +rescue StandardError => e + puts "Error building project: #{e.message}" end # snippet-end:[codebuild.Ruby.buildProject] diff --git a/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-builds.rb b/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-builds.rb index 458c0816a20..4bb292ef5ef 100644 --- a/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-builds.rb +++ b/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-builds.rb @@ -2,21 +2,21 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[codebuild.Ruby.listBuilds] -require "aws-sdk-codebuild" # v2: require 'aws-sdk' +require 'aws-sdk-codebuild' # v2: require 'aws-sdk' client = Aws::CodeBuild::Client.new -build_list = client.list_builds({sort_order: "ASCENDING", }) +build_list = client.list_builds({ sort_order: 'ASCENDING' }) if build_list.ids.empty? - puts "No builds found!" + puts 'No builds found!' else - builds = client.batch_get_builds({ids: build_list.ids}) + builds = client.batch_get_builds({ ids: build_list.ids }) builds.builds.each do |build| - puts "Project: " + build.project_name - puts "Phase: " + build.current_phase - puts "Status: " + build.build_status + puts "Project: #{build.project_name}" + puts "Phase: #{build.current_phase}" + puts "Status: #{build.build_status}" end end # snippet-end:[codebuild.Ruby.listBuilds] diff --git a/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-projects.rb b/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-projects.rb index fd45ae52bcd..9ade57beb81 100644 --- a/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-projects.rb +++ b/ruby/example_code/codebuild/aws-ruby-sdk-codebuild-example-list-projects.rb @@ -2,17 +2,17 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[codebuild.Ruby.listProjects] -require "aws-sdk-codebuild" # v2: require 'aws-sdk' +require 'aws-sdk-codebuild' # v2: require 'aws-sdk' client = Aws::CodeBuild::Client.new resp = client.list_projects({ - sort_by: "NAME", # accepts NAME, CREATED_TIME, LAST_MODIFIED_TIME - sort_order: "ASCENDING" # accepts ASCENDING, DESCENDING -}) + sort_by: 'NAME', # accepts NAME, CREATED_TIME, LAST_MODIFIED_TIME + sort_order: 'ASCENDING' # accepts ASCENDING, DESCENDING + }) if resp.projects.empty? - puts "No projects found!" + puts 'No projects found!' else resp.projects.each { |p| puts p } end diff --git a/ruby/example_code/dynamodb/README.md b/ruby/example_code/dynamodb/README.md index 846bc5af01b..4256dd73186 100644 --- a/ruby/example_code/dynamodb/README.md +++ b/ruby/example_code/dynamodb/README.md @@ -45,18 +45,18 @@ Code examples that show you how to perform the essential operations within a ser Code excerpts that show you how to call individual service functions. -- [BatchExecuteStatement](partiql/partiql_batch.rb#L25) -- [BatchWriteItem](scaffold.rb#L83) -- [CreateTable](scaffold.rb#L56) -- [DeleteItem](basics/dynamodb_basics.rb#L127) -- [DeleteTable](scaffold.rb#L109) -- [DescribeTable](scaffold.rb#L37) -- [ExecuteStatement](partiql/partiql_single.rb#L25) +- [BatchExecuteStatement](partiql/partiql_batch.rb#L22) +- [BatchWriteItem](scaffold.rb#L81) +- [CreateTable](scaffold.rb#L53) +- [DeleteItem](basics/dynamodb_basics.rb#L129) +- [DeleteTable](scaffold.rb#L108) +- [DescribeTable](scaffold.rb#L34) +- [ExecuteStatement](partiql/partiql_single.rb#L22) - [GetItem](basics/dynamodb_basics.rb#L40) -- [ListTables](scaffold.rb#L37) -- [PutItem](basics/dynamodb_basics.rb#L23) +- [ListTables](scaffold.rb#L34) +- [PutItem](basics/dynamodb_basics.rb#L21) - [Query](basics/dynamodb_basics.rb#L75) -- [Scan](basics/dynamodb_basics.rb#L94) +- [Scan](basics/dynamodb_basics.rb#L95) - [UpdateItem](basics/dynamodb_basics.rb#L55) ### Scenarios diff --git a/ruby/example_code/dynamodb/basics/dynamodb_basics.rb b/ruby/example_code/dynamodb/basics/dynamodb_basics.rb index f4762f59d9d..06e6ae96787 100644 --- a/ruby/example_code/dynamodb/basics/dynamodb_basics.rb +++ b/ruby/example_code/dynamodb/basics/dynamodb_basics.rb @@ -1,20 +1,18 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-dynamodb" -require "json" -require "open-uri" -require "pp" -require "zip" +require 'aws-sdk-dynamodb' +require 'json' +require 'open-uri' +require 'zip' # snippet-start:[ruby.example_code.ruby.DynamoDBBasics.full] # snippet-start:[ruby.example_code.ruby.DynamoDBBasics.decl] class DynamoDBBasics - attr_reader :dynamo_resource - attr_reader :table + attr_reader :dynamo_resource, :table def initialize(table_name) - client = Aws::DynamoDB::Client.new(region: "us-east-1") + client = Aws::DynamoDB::Client.new(region: 'us-east-1') @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table = @dynamo_resource.table(table_name) end @@ -27,9 +25,11 @@ def initialize(table_name) def add_item(movie) @table.put_item( item: { - "year" => movie[:year], - "title" => movie[:title], - "info" => {"plot" => movie[:plot], "rating" => movie[:rating]}}) + 'year' => movie[:year], + 'title' => movie[:title], + 'info' => { 'plot' => movie[:plot], 'rating' => movie[:rating] } + } + ) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't add movie #{title} to table #{@table.name}. Here's why:") puts("\t#{e.code}: #{e.message}") @@ -44,7 +44,7 @@ def add_item(movie) # @param year [Integer] The release year of the movie. # @return [Hash] The data about the requested movie. def get_item(title, year) - @table.get_item(key: {"year" => year, "title" => title}) + @table.get_item(key: { 'year' => year, 'title' => title }) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't get movie #{title} (#{year}) from table #{@table.name}:\n") puts("\t#{e.code}: #{e.message}") @@ -57,12 +57,12 @@ def get_item(title, year) # # @param movie [Hash] The title, year, plot, rating of the movie. def update_item(movie) - response = @table.update_item( - key: {"year" => movie[:year], "title" => movie[:title]}, - update_expression: "set info.rating=:r", - expression_attribute_values: { ":r" => movie[:rating] }, - return_values: "UPDATED_NEW") + key: { 'year' => movie[:year], 'title' => movie[:title] }, + update_expression: 'set info.rating=:r', + expression_attribute_values: { ':r' => movie[:rating] }, + return_values: 'UPDATED_NEW' + ) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't update movie #{movie[:title]} (#{movie[:year]}) in table #{@table.name}\n") puts("\t#{e.code}: #{e.message}") @@ -79,9 +79,10 @@ def update_item(movie) # @return [Array] The list of movies that were released in the specified year. def query_items(year) response = @table.query( - key_condition_expression: "#yr = :year", - expression_attribute_names: {"#yr" => "year"}, - expression_attribute_values: {":year" => year}) + key_condition_expression: '#yr = :year', + expression_attribute_names: { '#yr' => 'year' }, + expression_attribute_values: { ':year' => year } + ) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't query for movies released in #{year}. Here's why:") puts("\t#{e.code}: #{e.message}") @@ -100,11 +101,12 @@ def query_items(year) def scan_items(year_range) movies = [] scan_hash = { - filter_expression: "#yr between :start_yr and :end_yr", - projection_expression: "#yr, title, info.rating", - expression_attribute_names: {"#yr" => "year"}, + filter_expression: '#yr between :start_yr and :end_yr', + projection_expression: '#yr, title, info.rating', + expression_attribute_names: { '#yr' => 'year' }, expression_attribute_values: { - ":start_yr" => year_range[:start], ":end_yr" => year_range[:end]} + ':start_yr' => year_range[:start], ':end_yr' => year_range[:end] + } } done = false start_key = nil @@ -130,7 +132,7 @@ def scan_items(year_range) # @param title [String] The title of the movie to delete. # @param year [Integer] The release year of the movie to delete. def delete_item(title, year) - @table.delete_item(key: {"year" => year, "title" => title}) + @table.delete_item(key: { 'year' => year, 'title' => title }) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't delete movie #{title}. Here's why:") puts("\t#{e.code}: #{e.message}") diff --git a/ruby/example_code/dynamodb/basics/scenario_getting_started_dynamodb.rb b/ruby/example_code/dynamodb/basics/scenario_getting_started_dynamodb.rb index 898129d99dd..0ef739c0a83 100644 --- a/ruby/example_code/dynamodb/basics/scenario_getting_started_dynamodb.rb +++ b/ruby/example_code/dynamodb/basics/scenario_getting_started_dynamodb.rb @@ -5,37 +5,37 @@ # For more information, see: # https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/README.md -require "aws-sdk-dynamodb" -require "logger" -require "json" -require "zip" -require "cli/ui" -require_relative("../../../helpers/disclaimers") -require_relative("../../../helpers/decorators") -require_relative("dynamodb_basics") -require_relative("../scaffold") +require 'aws-sdk-dynamodb' +require 'logger' +require 'json' +require 'zip' +require 'cli/ui' +require_relative('../../../helpers/disclaimers') +require_relative('../../../helpers/decorators') +require_relative('dynamodb_basics') +require_relative('../scaffold') # Runs the Amazon DynamoDB demo. # @return [Nil] def run_scenario - banner("../../../helpers/banner.txt") - puts "######################################################################################################".yellow - puts "# #".yellow - puts "# EXAMPLE CODE DEMO: #".yellow - puts "# Amazon DynamoDB #".yellow - puts "# #".yellow - puts "######################################################################################################".yellow - puts "" - puts "You have launched a demo of Amazon DynamoDB using the AWS for Ruby v3 SDK. Over the next 60 seconds, it will" - puts "do the following:" - puts " 1. Create a new DynamoDB table." - puts " 2. Write batch data into the table" - puts " 3. Update an item in the table" - puts " 4. Delete an item in the table." - puts " 5. Query the table using PartiQL." - puts " 6. Scan the table using PartiQL." - puts " 7. Destroy the DynamoDB table." - puts "" + banner('../../../helpers/banner.txt') + puts '######################################################################################################'.yellow + puts '# #'.yellow + puts '# EXAMPLE CODE DEMO: #'.yellow + puts '# Amazon DynamoDB #'.yellow + puts '# #'.yellow + puts '######################################################################################################'.yellow + puts '' + puts 'You have launched a demo of Amazon DynamoDB using the AWS for Ruby v3 SDK. Over the next 60 seconds, it will' + puts 'do the following:' + puts ' 1. Create a new DynamoDB table.' + puts ' 2. Write batch data into the table' + puts ' 3. Update an item in the table' + puts ' 4. Delete an item in the table.' + puts ' 5. Query the table using PartiQL.' + puts ' 6. Scan the table using PartiQL.' + puts ' 7. Destroy the DynamoDB table.' + puts '' confirm_begin billing @@ -47,39 +47,39 @@ def run_scenario scaffold = Scaffold.new(table_name) dynamodb_wrapper = DynamoDBBasics.new(table_name) - new_step(1, "Create a new DynamoDB table if none already exists.") + new_step(1, 'Create a new DynamoDB table if none already exists.') unless scaffold.exists?(table_name) puts("\nNo such table: #{table_name}. Creating it...") scaffold.create_table(table_name) print "Done!\n".green end - new_step(2, "Add a new record to the DynamoDB table.") + new_step(2, 'Add a new record to the DynamoDB table.') my_movie = {} - my_movie[:title] = CLI::UI::Prompt.ask("Enter the title of a movie to add to the table. E.g. The Matrix") - my_movie[:year] = CLI::UI::Prompt.ask("What year was it released? E.g. 1989").to_i - my_movie[:rating] = CLI::UI::Prompt.ask("On a scale of 1 - 10, how do you rate it? E.g. 7").to_i - my_movie[:plot] = CLI::UI::Prompt.ask("Enter a brief summary of the plot. E.g. A man awakens to a new reality.") + my_movie[:title] = CLI::UI::Prompt.ask('Enter the title of a movie to add to the table. E.g. The Matrix') + my_movie[:year] = CLI::UI::Prompt.ask('What year was it released? E.g. 1989').to_i + my_movie[:rating] = CLI::UI::Prompt.ask('On a scale of 1 - 10, how do you rate it? E.g. 7').to_i + my_movie[:plot] = CLI::UI::Prompt.ask('Enter a brief summary of the plot. E.g. A man awakens to a new reality.') dynamodb_wrapper.add_item(my_movie) puts("\nNew record added:") puts JSON.pretty_generate(my_movie).green print "Done!\n".green - new_step(3, "Update a record in the DynamoDB table.") + new_step(3, 'Update a record in the DynamoDB table.') my_movie[:rating] = CLI::UI::Prompt.ask("Let's update the movie you added with a new rating, e.g. 3:").to_i response = dynamodb_wrapper.update_item(my_movie) puts("Updated '#{my_movie[:title]}' with new attributes:") puts JSON.pretty_generate(response).green print "Done!\n".green - new_step(4, "Get a record from the DynamoDB table.") + new_step(4, 'Get a record from the DynamoDB table.') puts("Searching for #{my_movie[:title]} (#{my_movie[:year]})...") response = dynamodb_wrapper.get_item(my_movie[:title], my_movie[:year]) puts JSON.pretty_generate(response).green print "Done!\n".green - new_step(5, "Write a batch of items into the DynamoDB table.") - download_file = "moviedata.json" + new_step(5, 'Write a batch of items into the DynamoDB table.') + download_file = 'moviedata.json' puts("Downloading movie database to #{download_file}...") movie_data = scaffold.fetch_movie_data(download_file) puts("Writing movie data from #{download_file} into your table...") @@ -87,35 +87,36 @@ def run_scenario puts("Records added: #{movie_data.length}.") print "Done!\n".green - new_step(5, "Query for a batch of items by key.") + new_step(5, 'Query for a batch of items by key.') loop do - release_year = CLI::UI::Prompt.ask("Enter a year between 1972 and 2018, e.g. 1999:").to_i + release_year = CLI::UI::Prompt.ask('Enter a year between 1972 and 2018, e.g. 1999:').to_i results = dynamodb_wrapper.query_items(release_year) if results.any? puts("There were #{results.length} movies released in #{release_year}:") results.each do |movie| - print "\t #{movie["title"]}".green + print "\t #{movie['title']}".green end break else continue = CLI::UI::Prompt.ask("Found no movies released in #{release_year}! Try another year? (y/n)") - break if !continue.eql?("y") + break unless continue.eql?('y') end end print "\nDone!\n".green - new_step(6, "Scan for a batch of items using a filter expression.") + new_step(6, 'Scan for a batch of items using a filter expression.') years = {} - years[:start] = CLI::UI::Prompt.ask("Enter a starting year between 1972 and 2018:") - years[:end] = CLI::UI::Prompt.ask("Enter an ending year between 1972 and 2018:") + years[:start] = CLI::UI::Prompt.ask('Enter a starting year between 1972 and 2018:') + years[:end] = CLI::UI::Prompt.ask('Enter an ending year between 1972 and 2018:') releases = dynamodb_wrapper.scan_items(years) if !releases.empty? puts("Found #{releases.length} movies.") count = Question.ask( - "How many do you want to see? ", method(:is_int), in_range(1, releases.length)) + 'How many do you want to see? ', method(:is_int), in_range(1, releases.length) + ) puts("Here are your #{count} movies:") releases.take(count).each do |release| - puts("\t#{release["title"]}") + puts("\t#{release['title']}") end else puts("I don't know about any movies released between #{years[:start]} "\ @@ -123,17 +124,17 @@ def run_scenario end print "\nDone!\n".green - new_step(7, "Delete an item from the DynamoDB table.") + new_step(7, 'Delete an item from the DynamoDB table.') answer = CLI::UI::Prompt.ask("Do you want to remove '#{my_movie[:title]}'? (y/n) ") - if answer.eql?("y") + if answer.eql?('y') dynamodb_wrapper.delete_item(my_movie[:title], my_movie[:year]) puts("Removed '#{my_movie[:title]}' from the table.") print "\nDone!\n".green end - new_step(8, "Delete the DynamoDB table.") - answer = CLI::UI::Prompt.ask("Delete the table? (y/n)") - if answer.eql?("y") + new_step(8, 'Delete the DynamoDB table.') + answer = CLI::UI::Prompt.ask('Delete the table? (y/n)') + if answer.eql?('y') scaffold.delete_table puts("Deleted #{table_name}.") else @@ -141,7 +142,7 @@ def run_scenario end print "\nThanks for watching!\n".green rescue Aws::Errors::ServiceError - puts("Something went wrong with the demo.") + puts('Something went wrong with the demo.') rescue Errno::ENOENT true end diff --git a/ruby/example_code/dynamodb/basics/spec/scenario_getting_started_dynamodb_spec.rb b/ruby/example_code/dynamodb/basics/spec/scenario_getting_started_dynamodb_spec.rb index fe378cf20ff..384eb7c1995 100644 --- a/ruby/example_code/dynamodb/basics/spec/scenario_getting_started_dynamodb_spec.rb +++ b/ruby/example_code/dynamodb/basics/spec/scenario_getting_started_dynamodb_spec.rb @@ -3,67 +3,65 @@ # frozen_string_literal: true -require "json" -require "rspec" -require_relative "../dynamodb_basics" -require_relative "../../scaffold" +require 'json' +require 'rspec' +require_relative '../dynamodb_basics' +require_relative '../../scaffold' describe DynamoDBBasics do - context "DynamoDBWrapper" do + context 'DynamoDBWrapper' do table_name = "doc-example-table-movies-#{rand(10**4)}" scaffold = Scaffold.new(table_name) sdk = DynamoDBBasics.new(table_name) - it "Create a new DynamoDB table", integ: true do + it 'Create a new DynamoDB table', integ: true do scaffold.create_table(table_name) expect(scaffold.exists?(table_name)).to be_truthy end - it "Write a batch of famous movies into the DynamoDB table", integ: true do - movie_data = scaffold.fetch_movie_data("moviedata.json") + it 'Write a batch of famous movies into the DynamoDB table', integ: true do + movie_data = scaffold.fetch_movie_data('moviedata.json') scaffold.write_batch(movie_data) expect(movie_data.length).to be > 200 end - it "Get a record from the DynamoDB table", integ: true do - response = sdk.get_item("12 Years a Slave", 2013) - expect(response.item["info"]["rating"].to_i).to eq(7) + it 'Get a record from the DynamoDB table', integ: true do + response = sdk.get_item('12 Years a Slave', 2013) + expect(response.item['info']['rating'].to_i).to eq(7) end - it "Add a new record to the DynamoDB table", integ: true do - test_record = { title: "The Matrix 5", year: 2023, rating: 3, plot: "A man awakens to yet another new reality." } + it 'Add a new record to the DynamoDB table', integ: true do + test_record = { title: 'The Matrix 5', year: 2023, rating: 3, plot: 'A man awakens to yet another new reality.' } response = sdk.add_item(test_record) expect(response).not_to be_nil end - it "Update a record in the DynamoDB table", integ: true do - test_record = { title: "12 Years a Slave", year: 2013, rating: 8, plot: "A man awakens to a new reality." } + it 'Update a record in the DynamoDB table', integ: true do + test_record = { title: '12 Years a Slave', year: 2013, rating: 8, plot: 'A man awakens to a new reality.' } sdk.update_item(test_record) - response = sdk.get_item("12 Years a Slave", 2013) - expect(response.item["info"]["rating"].to_i).to eq(8) + response = sdk.get_item('12 Years a Slave', 2013) + expect(response.item['info']['rating'].to_i).to eq(8) end - it "Query for a batch of items by key.", integ: true do + it 'Query for a batch of items by key.', integ: true do results = sdk.query_items(1999) expect(results.count).to be > 1 results.each do |movie| - expect(movie["title"]).to be + expect(movie['title']).to be end end - it "Scan for a batch of items using a filter expression.", integ: true do + it 'Scan for a batch of items using a filter expression.', integ: true do years = {} years[:start] = 1989 years[:end] = 1990 releases = sdk.scan_items(years) - expect(releases.count).to be > 0 - expect(releases[0]["title"]).to be + expect(releases.count).to be.positive? + expect(releases[0]['title']).to be end - it "Deletes DynamoDB table", integ: true do - if scaffold.exists?(table_name) - scaffold.delete_table - end + it 'Deletes DynamoDB table', integ: true do + scaffold.delete_table if scaffold.exists?(table_name) end end end diff --git a/ruby/example_code/dynamodb/partiql/partiql_batch.rb b/ruby/example_code/dynamodb/partiql/partiql_batch.rb index f352bba0de0..acd4e13fa28 100644 --- a/ruby/example_code/dynamodb/partiql/partiql_batch.rb +++ b/ruby/example_code/dynamodb/partiql/partiql_batch.rb @@ -1,22 +1,19 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-dynamodb" -require "json" -require "open-uri" -require "pp" -require "zip" -require_relative "../scaffold" +require 'aws-sdk-dynamodb' +require 'json' +require 'open-uri' +require 'zip' +require_relative '../scaffold' # snippet-start:[ruby.example_code.ruby.DynamoDBPartiQLBatch.full] # snippet-start:[ruby.example_code.ruby.DynamoDBPartiQLBatch.decl] class DynamoDBPartiQLBatch - - attr_reader :dynamo_resource - attr_reader :table + attr_reader :dynamo_resource, :table def initialize(table_name) - client = Aws::DynamoDB::Client.new(region: "us-east-1") + client = Aws::DynamoDB::Client.new(region: 'us-east-1') @dynamodb = Aws::DynamoDB::Resource.new(client: client) @table = @dynamodb.table(table_name) end @@ -34,11 +31,10 @@ def batch_execute_select(batch_titles) parameters: [title, year] } end - @dynamodb.client.batch_execute_statement({statements: request_items}) + @dynamodb.client.batch_execute_statement({ statements: request_items }) end # snippet-end:[ruby.example_code.dynamodb.partiql.batch_read] - # snippet-start:[ruby.example_code.dynamodb.partiql.batch_write] # Deletes a batch of items from a table using PartiQL # @@ -51,7 +47,7 @@ def batch_execute_write(batch_titles) parameters: [title, year] } end - @dynamodb.client.batch_execute_statement({statements: request_items}) + @dynamodb.client.batch_execute_statement({ statements: request_items }) end # snippet-end:[ruby.example_code.dynamodb.partiql.batch_write] end diff --git a/ruby/example_code/dynamodb/partiql/partiql_single.rb b/ruby/example_code/dynamodb/partiql/partiql_single.rb index fbbf37d9663..ba5cac8e990 100644 --- a/ruby/example_code/dynamodb/partiql/partiql_single.rb +++ b/ruby/example_code/dynamodb/partiql/partiql_single.rb @@ -1,22 +1,19 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-dynamodb" -require "json" -require "open-uri" -require "pp" -require "zip" -require_relative "../scaffold" +require 'aws-sdk-dynamodb' +require 'json' +require 'open-uri' +require 'zip' +require_relative '../scaffold' # snippet-start:[ruby.example_code.ruby.DynamoDBPartiQLSingle.full] # snippet-start:[ruby.example_code.ruby.DynamoDBPartiQLSingle.decl] class DynamoDBPartiQLSingle - - attr_reader :dynamo_resource - attr_reader :table + attr_reader :dynamo_resource, :table def initialize(table_name) - client = Aws::DynamoDB::Client.new(region: "us-east-1") + client = Aws::DynamoDB::Client.new(region: 'us-east-1') @dynamodb = Aws::DynamoDB::Resource.new(client: client) @table = @dynamodb.table(table_name) end @@ -54,7 +51,6 @@ def update_rating_by_title(title, year, rating) end # snippet-end:[ruby.example_code.dynamodb.partiql.single_update] - # snippet-start:[ruby.example_code.dynamodb.partiql.single_delete] # Deletes a single record from a table using PartiQL. # @@ -70,7 +66,6 @@ def delete_item_by_title(title, year) end # snippet-end:[ruby.example_code.dynamodb.partiql.single_delete] - # snippet-start:[ruby.example_code.dynamodb.partiql.single_insert] # Adds a single record to a table using PartiQL. # @@ -82,7 +77,7 @@ def delete_item_by_title(title, year) def insert_item(title, year, plot, rating) request = { statement: "INSERT INTO \"#{@table.name}\" VALUE {'title': ?, 'year': ?, 'info': ?}", - parameters: [title, year, {'plot': plot, 'rating': rating}] + parameters: [title, year, { 'plot': plot, 'rating': rating }] } @dynamodb.client.execute_statement(request) end diff --git a/ruby/example_code/dynamodb/partiql/scenario_partiql_batch.rb b/ruby/example_code/dynamodb/partiql/scenario_partiql_batch.rb index b494b11b6d1..ac6bc5a3b35 100644 --- a/ruby/example_code/dynamodb/partiql/scenario_partiql_batch.rb +++ b/ruby/example_code/dynamodb/partiql/scenario_partiql_batch.rb @@ -5,34 +5,35 @@ # For more information, see: # https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/README.md -require "aws-sdk-dynamodb" -require "logger" -require "json" -require "zip" -require "cli/ui" -require_relative("../../../helpers/disclaimers") -require_relative("../../../helpers/decorators") -require_relative("partiql_batch") +require 'aws-sdk-dynamodb' +require 'logger' +require 'json' +require 'zip' +require 'cli/ui' +require_relative('../../../helpers/disclaimers') +require_relative('../../../helpers/decorators') +require_relative('partiql_batch') # Runs the Amazon DynamoDB PartiQL demo. # @return [Nil] def run_scenario banner - puts "######################################################################################################".yellow - puts "# #".yellow - puts "# EXAMPLE CODE DEMO: #".yellow - puts "# Amazon DynamoDB - PartiQL #".yellow - puts "# #".yellow - puts "######################################################################################################".yellow - puts "" - puts "You have launched a demo of Amazon DynamoDB using PartiQL and the AWS for Ruby v3 SDK. Over the next 60 seconds, it will" - puts "do the following:" - puts " 1. Create a new DynamoDB table." - puts " 2. Write batch data into the table" - puts " 3. Get a batch of items from a table using PartiQL." - puts " 4. Delete a batch of from a table using PartiQL." - puts " 5. Destroy the DynamoDB table." - puts "" + puts '######################################################################################################'.yellow + puts '# #'.yellow + puts '# EXAMPLE CODE DEMO: #'.yellow + puts '# Amazon DynamoDB - PartiQL #'.yellow + puts '# #'.yellow + puts '######################################################################################################'.yellow + puts '' + puts 'You have launched a demo of Amazon DynamoDB using PartiQL and the AWS for Ruby v3 SDK. Over the next 60 seconds, +it will' + puts 'do the following:' + puts ' 1. Create a new DynamoDB table.' + puts ' 2. Write batch data into the table' + puts ' 3. Get a batch of items from a table using PartiQL.' + puts ' 4. Delete a batch of from a table using PartiQL.' + puts ' 5. Destroy the DynamoDB table.' + puts '' confirm_begin billing @@ -44,15 +45,15 @@ def run_scenario scaffold = Scaffold.new(table_name) sdk = DynamoDBPartiQLBatch.new(table_name) - new_step(1, "Create a new DynamoDB table if none already exists.") + new_step(1, 'Create a new DynamoDB table if none already exists.') unless scaffold.exists?(table_name) puts("\nNo such table: #{table_name}. Creating it...") scaffold.create_table(table_name) print "Done!\n".green end - new_step(2, "Populate DynamoDB table with movie data.") - download_file = "moviedata.json" + new_step(2, 'Populate DynamoDB table with movie data.') + download_file = 'moviedata.json' puts("Downloading movie database to #{download_file}...") movie_data = scaffold.fetch_movie_data(download_file) puts("Writing movie data from #{download_file} into your table...") @@ -60,20 +61,20 @@ def run_scenario puts("Records added: #{movie_data.length}.") print "Done!\n".green - new_step(3, "Select a batch of items from the movies table.") + new_step(3, 'Select a batch of items from the movies table.') puts "Let's select some popular movies for side-by-side comparison." - response = sdk.batch_execute_select([["Mean Girls", 2004], ["Goodfellas", 1977], ["The Prancing of the Lambs", 2005]]) + response = sdk.batch_execute_select([['Mean Girls', 2004], ['Goodfellas', 1977], ['The Prancing of the Lambs', 2005]]) puts("Items selected: #{response['responses'].length}\n") print "\nDone!\n".green - new_step(4, "Delete a batch of items from the movies table.") - sdk.batch_execute_write([["Mean Girls", 2004], ["Goodfellas", 1977], ["The Prancing of the Lambs", 2005]]) + new_step(4, 'Delete a batch of items from the movies table.') + sdk.batch_execute_write([['Mean Girls', 2004], ['Goodfellas', 1977], ['The Prancing of the Lambs', 2005]]) print "\nDone!\n".green - new_step(5, "Delete the table.") - if scaffold.exists?(table_name) - scaffold.delete_table - end + new_step(5, 'Delete the table.') + return unless scaffold.exists?(table_name) + + scaffold.delete_table end # snippet-end:[ruby.example_code.dynamodb.Scenario_PartiQL_Batch] diff --git a/ruby/example_code/dynamodb/partiql/scenario_partiql_single.rb b/ruby/example_code/dynamodb/partiql/scenario_partiql_single.rb index de237e9f9d0..1ad7a13fcd4 100644 --- a/ruby/example_code/dynamodb/partiql/scenario_partiql_single.rb +++ b/ruby/example_code/dynamodb/partiql/scenario_partiql_single.rb @@ -5,36 +5,37 @@ # For more information, see: # https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/README.md -require "aws-sdk-dynamodb" -require "logger" -require "json" -require "zip" -require "cli/ui" -require_relative("../../../helpers/disclaimers") -require_relative("../../../helpers/decorators") -require_relative("partiql_single") +require 'aws-sdk-dynamodb' +require 'logger' +require 'json' +require 'zip' +require 'cli/ui' +require_relative('../../../helpers/disclaimers') +require_relative('../../../helpers/decorators') +require_relative('partiql_single') # Runs the Amazon DynamoDB PartiQL demo. # @return [Nil] def run_scenario banner - puts "######################################################################################################".yellow - puts "# #".yellow - puts "# EXAMPLE CODE DEMO: #".yellow - puts "# Amazon DynamoDB - PartiQL #".yellow - puts "# #".yellow - puts "######################################################################################################".yellow - puts "" - puts "You have launched a demo of Amazon DynamoDB using PartiQL and the AWS for Ruby v3 SDK. Over the next 60 seconds,it will" - puts "do the following:" - puts " 1. Create a new DynamoDB table." - puts " 2. Write batch data into the table" - puts " 3. Get a single item from a table using PartiQL" - puts " 4. Update a single item in a table using PartiQL" - puts " 5. Delete a single item from a table using PartiQL" - puts " 6. Insert a single item into a table using PartiQL" - puts " 7. Destroy the DynamoDB table." - puts "" + puts '######################################################################################################'.yellow + puts '# #'.yellow + puts '# EXAMPLE CODE DEMO: #'.yellow + puts '# Amazon DynamoDB - PartiQL #'.yellow + puts '# #'.yellow + puts '######################################################################################################'.yellow + puts '' + puts 'You have launched a demo of Amazon DynamoDB using PartiQL and the AWS for Ruby v3 SDK. Over the next 60 seconds, +it will' + puts 'do the following:' + puts ' 1. Create a new DynamoDB table.' + puts ' 2. Write batch data into the table' + puts ' 3. Get a single item from a table using PartiQL' + puts ' 4. Update a single item in a table using PartiQL' + puts ' 5. Delete a single item from a table using PartiQL' + puts ' 6. Insert a single item into a table using PartiQL' + puts ' 7. Destroy the DynamoDB table.' + puts '' confirm_begin billing @@ -46,15 +47,15 @@ def run_scenario scaffold = Scaffold.new(table_name) sdk = DynamoDBPartiQLSingle.new(table_name) - new_step(1, "Create a new DynamoDB table if none already exists.") + new_step(1, 'Create a new DynamoDB table if none already exists.') unless scaffold.exists?(table_name) puts("\nNo such table: #{table_name}. Creating it...") scaffold.create_table(table_name) print "Done!\n".green end - new_step(2, "Populate DynamoDB table with movie data.") - download_file = "moviedata.json" + new_step(2, 'Populate DynamoDB table with movie data.') + download_file = 'moviedata.json' puts("Downloading movie database to #{download_file}...") movie_data = scaffold.fetch_movie_data(download_file) puts("Writing movie data from #{download_file} into your table...") @@ -62,31 +63,31 @@ def run_scenario puts("Records added: #{movie_data.length}.") print "Done!\n".green - new_step(3, "Select a single item from the movies table.") - response = sdk.select_item_by_title("Star Wars") + new_step(3, 'Select a single item from the movies table.') + response = sdk.select_item_by_title('Star Wars') puts("Items selected for title 'Star Wars': #{response.items.length}\n") - print "#{response.items.first}".yellow + print response.items.first.to_s.yellow print "\n\nDone!\n".green - new_step(4, "Update a single item from the movies table.") + new_step(4, 'Update a single item from the movies table.') puts "Let's correct the rating on The Big Lebowski to 10.0." - sdk.update_rating_by_title("The Big Lebowski", 1998, 10.0) + sdk.update_rating_by_title('The Big Lebowski', 1998, 10.0) print "\nDone!\n".green - new_step(5, "Delete a single item from the movies table.") + new_step(5, 'Delete a single item from the movies table.') puts "Let's delete The Silence of the Lambs because it's just too scary." - sdk.delete_item_by_title("The Silence of the Lambs", 1991) + sdk.delete_item_by_title('The Silence of the Lambs', 1991) print "\nDone!\n".green - new_step(6, "Insert a new item into the movies table.") + new_step(6, 'Insert a new item into the movies table.') puts "Let's create a less-scary movie called The Prancing of the Lambs." - sdk.insert_item("The Prancing of the Lambs", 2005, "A movie about happy livestock.", 5.0) + sdk.insert_item('The Prancing of the Lambs', 2005, 'A movie about happy livestock.', 5.0) print "\nDone!\n".green - new_step(7, "Delete the table.") - if scaffold.exists?(table_name) - scaffold.delete_table - end + new_step(7, 'Delete the table.') + return unless scaffold.exists?(table_name) + + scaffold.delete_table end # snippet-end:[ruby.example_code.dynamodb.Scenario_PartiQL_Single] diff --git a/ruby/example_code/dynamodb/partiql/spec/scenario_partiql_batch_spec.rb b/ruby/example_code/dynamodb/partiql/spec/scenario_partiql_batch_spec.rb index 49029ce20e6..a82a0997359 100644 --- a/ruby/example_code/dynamodb/partiql/spec/scenario_partiql_batch_spec.rb +++ b/ruby/example_code/dynamodb/partiql/spec/scenario_partiql_batch_spec.rb @@ -3,51 +3,49 @@ # frozen_string_literal: true -require "json" -require "rspec" -require_relative "../partiql_batch" -require_relative "../../scaffold" +require 'json' +require 'rspec' +require_relative '../partiql_batch' +require_relative '../../scaffold' describe DynamoDBPartiQLBatch do - context "DynamoDBPartiQLWrapper" do + context 'DynamoDBPartiQLWrapper' do table_name = "doc-example-table-movies-partiql-#{rand(10**4)}" scaffold = Scaffold.new(table_name) sdk = DynamoDBPartiQLBatch.new(table_name) - it "Create a new DynamoDB table", integ: true do + it 'Create a new DynamoDB table', integ: true do scaffold.create_table(table_name) expect(scaffold.exists?(table_name)).to be_truthy end - it "Write a batch of famous movies into the DynamoDB table", integ: true do - movie_data = scaffold.fetch_movie_data("moviedata.json") + it 'Write a batch of famous movies into the DynamoDB table', integ: true do + movie_data = scaffold.fetch_movie_data('moviedata.json') scaffold.write_batch(movie_data) expect(movie_data.length).to be > 200 end - it "returns a valid response when given a list of movies", integ: true do - movies = ["Star Wars", "The Big Lebowski", "The Prancing of the Lambs"] + it 'returns a valid response when given a list of movies', integ: true do + movies = ['Star Wars', 'The Big Lebowski', 'The Prancing of the Lambs'] response = sdk.batch_execute_select(movies) - expect(response["responses"]).to be_an(Array) - expect(response["responses"].count).to eq(movies.length) - response["responses"].each do |movie_response| + expect(response['responses']).to be_an(Array) + expect(response['responses'].count).to eq(movies.length) + response['responses'].each do |movie_response| expect(movie_response).to be_a(Aws::DynamoDB::Types::BatchStatementResponse) end end - it "deletes a list of movies", quarantine: true do - movies = [["Mean Girls", 2004], ["The Prancing of the Lambs", 2005]] + it 'deletes a list of movies', quarantine: true do + movies = [['Mean Girls', 2004], ['The Prancing of the Lambs', 2005]] sdk.batch_execute_write(movies) movies.each do |movie| response = sdk.select_item_by_title(movie[0]) - expect(response["items"]).to be_empty + expect(response['items']).to be_empty end end - it "deletes DynamoDB table", integ: true do - if scaffold.exists?(table_name) - scaffold.delete_table - end + it 'deletes DynamoDB table', integ: true do + scaffold.delete_table if scaffold.exists?(table_name) end end end diff --git a/ruby/example_code/dynamodb/scaffold.rb b/ruby/example_code/dynamodb/scaffold.rb index df229cc1e6b..b36f241f080 100644 --- a/ruby/example_code/dynamodb/scaffold.rb +++ b/ruby/example_code/dynamodb/scaffold.rb @@ -11,21 +11,18 @@ # 3. Delete table # snippet-start:[ruby.example_code.dynamodb.helper.DynamoDBBasics] -require "aws-sdk-dynamodb" -require "json" -require "open-uri" -require "pp" -require "zip" +require 'aws-sdk-dynamodb' +require 'json' +require 'open-uri' +require 'zip' # snippet-start:[ruby.example_code.dynamodb.Scaffold] # Encapsulates an Amazon DynamoDB table of movie data. class Scaffold - attr_reader :dynamo_resource - attr_reader :table_name - attr_reader :table + attr_reader :dynamo_resource, :table_name, :table def initialize(table_name) - client = Aws::DynamoDB::Client.new(region: "us-east-1") + client = Aws::DynamoDB::Client.new(region: 'us-east-1') @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table_name = table_name @table = nil @@ -64,14 +61,15 @@ def create_table(table_name) @table = @dynamo_resource.create_table( table_name: table_name, key_schema: [ - {attribute_name: "year", key_type: "HASH"}, # Partition key - {attribute_name: "title", key_type: "RANGE"} # Sort key + { attribute_name: 'year', key_type: 'HASH' }, # Partition key + { attribute_name: 'title', key_type: 'RANGE' } # Sort key ], attribute_definitions: [ - {attribute_name: "year", attribute_type: "N"}, - {attribute_name: "title", attribute_type: "S"} + { attribute_name: 'year', attribute_type: 'N' }, + { attribute_name: 'title', attribute_type: 'S' } ], - provisioned_throughput: {read_capacity_units: 10, write_capacity_units: 10}) + provisioned_throughput: { read_capacity_units: 10, write_capacity_units: 10 } + ) @dynamo_resource.client.wait_until(:table_exists, table_name: table_name) @table rescue Aws::DynamoDB::Errors::ServiceError => e @@ -93,14 +91,15 @@ def write_batch(movies) while index < movies.length movie_items = [] movies[index, slice_size].each do |movie| - movie_items.append({put_request: { item: movie }}) + movie_items.append({ put_request: { item: movie } }) end - @dynamo_resource.client.batch_write_item({request_items: { @table.name => movie_items }}) + @dynamo_resource.client.batch_write_item({ request_items: { @table.name => movie_items } }) index += slice_size end rescue Aws::DynamoDB::Errors::ServiceError => e puts( - "Couldn't load data into table #{@table.name}. Here's why:") + "Couldn't load data into table #{@table.name}. Here's why:" + ) puts("\t#{e.code}: #{e.message}") raise end @@ -128,9 +127,9 @@ def fetch_movie_data(movie_file_name) if !File.file?(movie_file_name) @logger.debug("Downloading #{movie_file_name}...") movie_content = URI.open( - "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/samples/moviedata.zip" + 'https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/samples/moviedata.zip' ) - movie_json = "" + movie_json = '' Zip::File.open_buffer(movie_content) do |zip| zip.each do |entry| movie_json = entry.get_input_stream.read diff --git a/ruby/example_code/ec2/README.md b/ruby/example_code/ec2/README.md index 55fbcdda03c..db5b47321d1 100644 --- a/ruby/example_code/ec2/README.md +++ b/ruby/example_code/ec2/README.md @@ -38,8 +38,8 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `ruby` Code excerpts that show you how to call individual service functions. -- [AllocateAddress](ec2-ruby-example-elastic-ips.rb#L47) -- [AssociateAddress](ec2-ruby-example-elastic-ips.rb#L63) +- [AllocateAddress](ec2-ruby-example-elastic-ips.rb#L46) +- [AssociateAddress](ec2-ruby-example-elastic-ips.rb#L62) - [CreateKeyPair](ec2-ruby-example-key-pairs.rb#L10) - [CreateRouteTable](ec2-ruby-example-create-route-table.rb#L9) - [CreateSecurityGroup](ec2-ruby-example-security-group.rb#L10) diff --git a/ruby/example_code/ec2/ec2-ruby-example-attach-igw-vpc.rb b/ruby/example_code/ec2/ec2-ruby-example-attach-igw-vpc.rb index bc2fdf3cd2a..ec4af01f840 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-attach-igw-vpc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-attach-igw-vpc.rb @@ -6,10 +6,9 @@ # create an Internet gateway and then attaches it to a virtual private cloud # (VPC) in Amazon Virtual Private Cloud (Amazon VPC). - # snippet-start:[ec2.Ruby.attachIgwVpc] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Prerequisites: # @@ -45,35 +44,35 @@ def internet_gateway_created_and_attached?( } ] ) - return true + true rescue StandardError => e puts "Error creating or attaching internet gateway: #{e.message}" - puts "If the internet gateway was created but not attached, you should " \ - "clean up by deleting the internet gateway." - return false + puts 'If the internet gateway was created but not attached, you should ' \ + 'clean up by deleting the internet gateway.' + false end # Example usage: def run_me - vpc_id = "" - tag_key = "" - tag_value = "" - region = "" + vpc_id = '' + tag_key = '' + tag_value = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-attach-igw-vpc.rb " \ - "VPC_ID TAG_KEY TAG_VALUE REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-attach-igw-vpc.rb ' \ + 'VPC_ID TAG_KEY TAG_VALUE REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-attach-igw-vpc.rb " \ - "vpc-6713dfEX my-key my-value us-west-2" + puts 'Example: ruby ec2-ruby-example-attach-igw-vpc.rb ' \ + 'vpc-6713dfEX my-key my-value us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - vpc_id = "vpc-6713dfEX" - tag_key = "my-key" - tag_value = "my-value" + vpc_id = 'vpc-6713dfEX' + tag_key = 'my-key' + tag_value = 'my-value' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else vpc_id = ARGV[0] diff --git a/ruby/example_code/ec2/ec2-ruby-example-create-instance.rb b/ruby/example_code/ec2/ec2-ruby-example-create-instance.rb index f613b3face3..f986d40484f 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-create-instance.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-create-instance.rb @@ -7,8 +7,8 @@ # snippet-start:[ec2.Ruby.createInstances] -require "aws-sdk-ec2" -require "base64" +require 'aws-sdk-ec2' +require 'base64' # Prerequisites: # @@ -44,12 +44,12 @@ def instance_created?( key_pair_name, tag_key, tag_value, - instance_type = "t2.micro", - user_data_file = "" + instance_type = 't2.micro', + user_data_file = '' ) - encoded_script = "" + encoded_script = '' - unless user_data_file == "" + unless user_data_file == '' script = File.read(user_data_file) encoded_script = Base64.encode64(script) end @@ -63,7 +63,7 @@ def instance_created?( user_data: encoded_script ) - puts "Creating instance..." + puts 'Creating instance...' # Check whether the new instance is in the "running" state. polls = 0 @@ -75,7 +75,7 @@ def instance_created?( ] ) # Stop polling after 10 minutes (40 polls * 15 seconds per poll) if not running. - break if response.reservations[0].instances[0].state.name == "running" || polls > 40 + break if response.reservations[0].instances[0].state.name == 'running' || polls > 40 sleep(15) end @@ -90,43 +90,43 @@ def instance_created?( } ] ) - puts "Instance tagged." + puts 'Instance tagged.' - return true + true rescue StandardError => e puts "Error creating or tagging instance: #{e.message}" - return false + false end # Example usage: def run_me - image_id = "" - key_pair_name = "" - tag_key = "" - tag_value = "" - instance_type = "" - region = "" - user_data_file = "" + image_id = '' + key_pair_name = '' + tag_key = '' + tag_value = '' + instance_type = '' + region = '' + user_data_file = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-create-instance.rb " \ - "IMAGE_ID KEY_PAIR_NAME TAG_KEY TAG_VALUE INSTANCE_TYPE " \ - "REGION [USER_DATA_FILE]" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-create-instance.rb " \ - "ami-0947d2ba12EXAMPLE my-key-pair my-key my-value t2.micro " \ - "us-west-2 my-user-data.txt" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-create-instance.rb ' \ + 'IMAGE_ID KEY_PAIR_NAME TAG_KEY TAG_VALUE INSTANCE_TYPE ' \ + 'REGION [USER_DATA_FILE]' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-create-instance.rb ' \ + 'ami-0947d2ba12EXAMPLE my-key-pair my-key my-value t2.micro ' \ + 'us-west-2 my-user-data.txt' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - image_id = "ami-0947d2ba12EXAMPLE" - key_pair_name = "my-key-pair" - tag_key = "my-key" - tag_value = "my-value" - instance_type = "t2.micro" + image_id = 'ami-0947d2ba12EXAMPLE' + key_pair_name = 'my-key-pair' + tag_key = 'my-key' + tag_value = 'my-value' + instance_type = 't2.micro' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" - user_data_file = "my-user-data.txt" + region = 'us-west-2' + user_data_file = 'my-user-data.txt' # Otherwise, use the values as specified at the command prompt. else image_id = ARGV[0] @@ -149,9 +149,9 @@ def run_me instance_type, user_data_file ) - puts "Created and tagged instance." + puts 'Created and tagged instance.' else - puts "Could not create or tag instance." + puts 'Could not create or tag instance.' end end diff --git a/ruby/example_code/ec2/ec2-ruby-example-create-key-pair.rb b/ruby/example_code/ec2/ec2-ruby-example-create-key-pair.rb index b3a7406d783..9d5790f8634 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-create-key-pair.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-create-key-pair.rb @@ -9,7 +9,7 @@ # snippet-start:[ec2.Ruby.createKeyPair] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param key_pair_name [String] The name for the key pair and private @@ -25,32 +25,32 @@ def key_pair_created?(ec2_client, key_pair_name) key_pair = ec2_client.create_key_pair(key_name: key_pair_name) puts "Created key pair '#{key_pair.key_name}' with fingerprint " \ "'#{key_pair.key_fingerprint}' and ID '#{key_pair.key_pair_id}'." - filename = File.join(Dir.home, key_pair_name + ".pem") - File.open(filename, "w") { |file| file.write(key_pair.key_material) } + filename = File.join(Dir.home, "#{key_pair_name}.pem") + File.open(filename, 'w') { |file| file.write(key_pair.key_material) } puts "Private key file saved locally as '#{filename}'." - return true + true rescue StandardError => e puts "Error creating key pair or saving private key file: #{e.message}" - return false + false end # Example usage: def run_me - key_pair_name = "" - region = "" + key_pair_name = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-create-key-pair.rb " \ - "KEY_PAIR_NAME REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-create-key-pair.rb ' \ + 'KEY_PAIR_NAME REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-create-key-pair.rb " \ - "my-key-pair us-west-2" + puts 'Example: ruby ec2-ruby-example-create-key-pair.rb ' \ + 'my-key-pair us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - key_pair_name = "my-key-pair" + key_pair_name = 'my-key-pair' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2 " + region = 'us-west-2 ' # Otherwise, use the values as specified at the command prompt. else key_pair_name = ARGV[0] @@ -60,9 +60,9 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) if key_pair_created?(ec2_client, key_pair_name) - puts "Key pair created and private key file saved." + puts 'Key pair created and private key file saved.' else - puts "Key pair not created or private key file not saved." + puts 'Key pair not created or private key file not saved.' end end diff --git a/ruby/example_code/ec2/ec2-ruby-example-create-route-table.rb b/ruby/example_code/ec2/ec2-ruby-example-create-route-table.rb index 0e8baafcd0a..3a9ed18d9fb 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-create-route-table.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-create-route-table.rb @@ -7,7 +7,7 @@ # and then associates the route table with a subnet in Amazon VPC. # snippet-start:[ec2.Ruby.createRouteTable] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Prerequisites: # @@ -55,53 +55,53 @@ def route_table_created_and_associated?( } ] ) - puts "Added tags to route table." + puts 'Added tags to route table.' route_table.create_route( destination_cidr_block: destination_cidr_block, gateway_id: gateway_id ) - puts "Created route with destination CIDR block " \ + puts 'Created route with destination CIDR block ' \ "'#{destination_cidr_block}' and associated with gateway " \ "with ID '#{gateway_id}'." route_table.associate_with_subnet(subnet_id: subnet_id) puts "Associated route table with subnet with ID '#{subnet_id}'." - return true + true rescue StandardError => e puts "Error creating or associating route table: #{e.message}" - puts "If the route table was created but not associated, you should " \ - "clean up by deleting the route table." - return false + puts 'If the route table was created but not associated, you should ' \ + 'clean up by deleting the route table.' + false end # Example usage: def run_me - vpc_id = "" - subnet_id = "" - gateway_id = "" - destination_cidr_block = "" - tag_key = "" - tag_value = "" - region = "" + vpc_id = '' + subnet_id = '' + gateway_id = '' + destination_cidr_block = '' + tag_key = '' + tag_value = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-create-route-table.rb " \ - "VPC_ID SUBNET_ID GATEWAY_ID DESTINATION_CIDR_BLOCK " \ - "TAG_KEY TAG_VALUE REGION" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-create-route-table.rb " \ - "vpc-0b6f769731EXAMPLE subnet-03d9303b57EXAMPLE igw-06ca90c011EXAMPLE " \ + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-create-route-table.rb ' \ + 'VPC_ID SUBNET_ID GATEWAY_ID DESTINATION_CIDR_BLOCK ' \ + 'TAG_KEY TAG_VALUE REGION' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-create-route-table.rb ' \ + 'vpc-0b6f769731EXAMPLE subnet-03d9303b57EXAMPLE igw-06ca90c011EXAMPLE ' \ "'0.0.0.0/0' my-key my-value us-west-2" exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - vpc_id = "vpc-0b6f769731EXAMPLE" - subnet_id = "subnet-03d9303b57EXAMPLE" - gateway_id = "igw-06ca90c011EXAMPLE" - destination_cidr_block = "0.0.0.0/0" - tag_key = "my-key" - tag_value = "my-value" + vpc_id = 'vpc-0b6f769731EXAMPLE' + subnet_id = 'subnet-03d9303b57EXAMPLE' + gateway_id = 'igw-06ca90c011EXAMPLE' + destination_cidr_block = '0.0.0.0/0' + tag_key = 'my-key' + tag_value = 'my-value' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else vpc_id = ARGV[0] @@ -124,9 +124,9 @@ def run_me tag_key, tag_value ) - puts "Route table created and associated." + puts 'Route table created and associated.' else - puts "Route table not created or not associated." + puts 'Route table not created or not associated.' end end diff --git a/ruby/example_code/ec2/ec2-ruby-example-create-security-group.rb b/ruby/example_code/ec2/ec2-ruby-example-create-security-group.rb index 1b1956f8643..57ddad59042 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-create-security-group.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-create-security-group.rb @@ -8,7 +8,7 @@ # snippet-start:[ec2.Ruby.createSecurityGroup] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Prerequisites: # @@ -70,43 +70,43 @@ def security_group_created_with_egress?( puts "Granted egress to security group '#{group_name}' for protocol " \ "'#{ip_protocol}' from port '#{from_port}' to port '#{to_port}' " \ "with CIDR IP range '#{cidr_ip_range}'." - return true + true rescue StandardError => e puts "Error creating security group or granting egress: #{e.message}" - return false + false end # Example usage: def run_me - group_name = "" - description = "" - vpc_id = "" - ip_protocol = "" - from_port = "" - to_port = "" - cidr_ip_range = "" - region = "" + group_name = '' + description = '' + vpc_id = '' + ip_protocol = '' + from_port = '' + to_port = '' + cidr_ip_range = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-create-security-group.rb " \ - "GROUP_NAME DESCRIPTION VPC_ID IP_PROTOCOL FROM_PORT TO_PORT " \ - "CIDR_IP_RANGE REGION" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-create-security-group.rb " \ + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-create-security-group.rb ' \ + 'GROUP_NAME DESCRIPTION VPC_ID IP_PROTOCOL FROM_PORT TO_PORT ' \ + 'CIDR_IP_RANGE REGION' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-create-security-group.rb ' \ "my-security-group 'This is my security group.' vpc-6713dfEX " \ "tcp 22 22 '0.0.0.0/0' us-west-2" exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - group_name = "my-security-group" - description = "This is my security group." - vpc_id = "vpc-6713dfEX" - ip_protocol = "tcp" - from_port = "22" - to_port = "22" - cidr_ip_range = "0.0.0.0/0" + group_name = 'my-security-group' + description = 'This is my security group.' + vpc_id = 'vpc-6713dfEX' + ip_protocol = 'tcp' + from_port = '22' + to_port = '22' + cidr_ip_range = '0.0.0.0/0' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else group_name = ARGV[0] @@ -131,9 +131,9 @@ def run_me to_port, cidr_ip_range ) - puts "Security group created and egress granted." + puts 'Security group created and egress granted.' else - puts "Security group not created or egress not granted." + puts 'Security group not created or egress not granted.' end end diff --git a/ruby/example_code/ec2/ec2-ruby-example-create-subnet.rb b/ruby/example_code/ec2/ec2-ruby-example-create-subnet.rb index 71970640781..bd84200c853 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-create-subnet.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-create-subnet.rb @@ -9,7 +9,7 @@ # snippet-start:[ec2.Ruby.createSubnet] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Creates a subnet within a virtual private cloud (VPC) in # Amazon Virtual Private Cloud (Amazon VPC) and then tags @@ -63,37 +63,37 @@ def subnet_created_and_tagged?( "and CIDR block '#{cidr_block}' in availability zone " \ "'#{availability_zone}' and tagged with key '#{tag_key}' and " \ "value '#{tag_value}'." - return true + true rescue StandardError => e puts "Error creating or tagging subnet: #{e.message}" - return false + false end # Example usage: def run_me - vpc_id = "" - cidr_block = "" - availability_zone = "" - tag_key = "" - tag_value = "" - region = "" + vpc_id = '' + cidr_block = '' + availability_zone = '' + tag_key = '' + tag_value = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-create-subnet.rb " \ - "VPC_ID CIDR_BLOCK AVAILABILITY_ZONE TAG_KEY TAG_VALUE REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-create-subnet.rb ' \ + 'VPC_ID CIDR_BLOCK AVAILABILITY_ZONE TAG_KEY TAG_VALUE REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-create-subnet.rb " \ - "vpc-6713dfEX 10.0.0.0/24 us-west-2a my-key my-value us-west-2" + puts 'Example: ruby ec2-ruby-example-create-subnet.rb ' \ + 'vpc-6713dfEX 10.0.0.0/24 us-west-2a my-key my-value us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - vpc_id = "vpc-6713dfEX" - cidr_block = "10.0.0.0/24" - availability_zone = "us-west-2a" - tag_key = "my-key" - tag_value = "my-value" + vpc_id = 'vpc-6713dfEX' + cidr_block = '10.0.0.0/24' + availability_zone = 'us-west-2a' + tag_key = 'my-key' + tag_value = 'my-value' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else vpc_id = ARGV[0] @@ -114,9 +114,9 @@ def run_me tag_key, tag_value ) - puts "Subnet created and tagged." + puts 'Subnet created and tagged.' else - puts "Subnet not created or not tagged." + puts 'Subnet not created or not tagged.' end end diff --git a/ruby/example_code/ec2/ec2-ruby-example-create-vpc.rb b/ruby/example_code/ec2/ec2-ruby-example-create-vpc.rb index da79fe5b0c9..fb99aefcfec 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-create-vpc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-create-vpc.rb @@ -7,7 +7,7 @@ # snippet-start:[ec2.Ruby.createVpc] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Creates a virtual private cloud (VPC) in # Amazon Virtual Private Cloud (Amazon VPC) and then tags @@ -43,33 +43,33 @@ def vpc_created_and_tagged?( puts "Created VPC with ID '#{vpc.id}' and tagged with key " \ "'#{tag_key}' and value '#{tag_value}'." - return true + true rescue StandardError => e - puts "#{e.message}" - return false + puts e.message + false end # Example usage: def run_me - cidr_block = "" - tag_key = "" - tag_value = "" - region = "" + cidr_block = '' + tag_key = '' + tag_value = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-create-vpc.rb " \ - "CIDR_BLOCK TAG_KEY TAG_VALUE REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-create-vpc.rb ' \ + 'CIDR_BLOCK TAG_KEY TAG_VALUE REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-create-vpc.rb " \ - "10.0.0.0/24 my-key my-value us-west-2" + puts 'Example: ruby ec2-ruby-example-create-vpc.rb ' \ + '10.0.0.0/24 my-key my-value us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - cidr_block = "10.0.0.0/24" - tag_key = "my-key" - tag_value = "my-value" + cidr_block = '10.0.0.0/24' + tag_key = 'my-key' + tag_value = 'my-value' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else cidr_block = ARGV[0] @@ -86,9 +86,9 @@ def run_me tag_key, tag_value ) - puts "VPC created and tagged." + puts 'VPC created and tagged.' else - puts "VPC not created or not tagged." + puts 'VPC not created or not tagged.' end end diff --git a/ruby/example_code/ec2/ec2-ruby-example-elastic-ips.rb b/ruby/example_code/ec2/ec2-ruby-example-elastic-ips.rb index 20384f0903d..14592e10b6e 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-elastic-ips.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-elastic-ips.rb @@ -6,7 +6,6 @@ # check whether the specified Amazon Elastic Compute Cloud # (Amazon EC2) instance exists. - # snippet-start:[ec2.Ruby.elasticIps] # This code example does the following: @@ -20,7 +19,7 @@ # 6. Displays information again about addresses associated with the instance. # This time, the released address should not display. -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Checks whether the specified Amazon Elastic Compute Cloud # (Amazon EC2) instance exists. @@ -39,9 +38,9 @@ # ) def instance_exists?(ec2_client, instance_id) ec2_client.describe_instances(instance_ids: [instance_id]) - return true + true rescue StandardError - return false + false end # snippet-start:[ec2.Ruby.allocateElasticIPs] @@ -52,11 +51,11 @@ def instance_exists?(ec2_client, instance_id) # @example # puts allocate_elastic_ip_address(Aws::EC2::Client.new(region: 'us-west-2')) def allocate_elastic_ip_address(ec2_client) - response = ec2_client.allocate_address(domain: "vpc") - return response.allocation_id + response = ec2_client.allocate_address(domain: 'vpc') + response.allocation_id rescue StandardError => e puts "Error allocating Elastic IP address: #{e.message}" - return "Error" + 'Error' end # snippet-end:[ec2.Ruby.allocateElasticIPs] @@ -87,13 +86,14 @@ def associate_elastic_ip_address_with_instance( ) response = ec2_client.associate_address( allocation_id: allocation_id, - instance_id: instance_id, + instance_id: instance_id ) - return response.association_id + response.association_id rescue StandardError => e puts "Error associating Elastic IP address with instance: #{e.message}" - return "Error" + 'Error' end + # snippet-end:[ec2.Ruby.associateElasticIPs] # # Gets information about addresses associated with an @@ -114,17 +114,17 @@ def describe_addresses_for_instance(ec2_client, instance_id) response = ec2_client.describe_addresses( filters: [ { - name: "instance-id", + name: 'instance-id', values: [instance_id] } ] ) addresses = response.addresses if addresses.count.zero? - puts "No addresses." + puts 'No addresses.' else addresses.each do |address| - puts "-" * 20 + puts '-' * 20 puts "Public IP: #{address.public_ip}" puts "Private IP: #{address.private_ip_address}" end @@ -153,30 +153,30 @@ def describe_addresses_for_instance(ec2_client, instance_id) # ) def elastic_ip_address_released?(ec2_client, allocation_id) ec2_client.release_address(allocation_id: allocation_id) - return true + true rescue StandardError => e puts("Error releasing Elastic IP address: #{e.message}") - return false + false end # snippet-end:[ec2.Ruby.releaseElasticIPs] # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-elastic-ips.rb " \ - "INSTANCE_ID REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-elastic-ips.rb ' \ + 'INSTANCE_ID REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-elastic-ips.rb " \ - "i-033c48ef067af3dEX us-west-2" + puts 'Example: ruby ec2-ruby-example-elastic-ips.rb ' \ + 'i-033c48ef067af3dEX us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - instance_id = "i-033c48ef067af3dEX" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" + instance_id = 'i-033c48ef067af3dEX' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] @@ -191,44 +191,44 @@ def run_me end puts "Addresses for instance with ID '#{instance_id}' before allocating " \ - "Elastic IP address:" + 'Elastic IP address:' describe_addresses_for_instance(ec2_client, instance_id) - puts "Allocating Elastic IP address..." + puts 'Allocating Elastic IP address...' allocation_id = allocate_elastic_ip_address(ec2_client) - if allocation_id.start_with?("Error") - puts "Stopping program." + if allocation_id.start_with?('Error') + puts 'Stopping program.' exit 1 else puts "Elastic IP address created with allocation ID '#{allocation_id}'." end - puts "Associating Elastic IP address with instance..." + puts 'Associating Elastic IP address with instance...' association_id = associate_elastic_ip_address_with_instance( ec2_client, allocation_id, instance_id ) - if association_id.start_with?("Error") - puts "Stopping program. You must associate the Elastic IP address yourself." + if association_id.start_with?('Error') + puts 'Stopping program. You must associate the Elastic IP address yourself.' exit 1 else - puts "Elastic IP address associated with instance with association ID " \ + puts 'Elastic IP address associated with instance with association ID ' \ "'#{association_id}'." end - puts "Addresses for instance after allocating Elastic IP address:" + puts 'Addresses for instance after allocating Elastic IP address:' describe_addresses_for_instance(ec2_client, instance_id) - puts "Releasing the Elastic IP address from the instance..." + puts 'Releasing the Elastic IP address from the instance...' if elastic_ip_address_released?(ec2_client, allocation_id) == false - puts "Stopping program. You must release the Elastic IP address yourself." + puts 'Stopping program. You must release the Elastic IP address yourself.' exit 1 else - puts "Address released." + puts 'Address released.' end - puts "Addresses for instance after releasing Elastic IP address:" + puts 'Addresses for instance after releasing Elastic IP address:' describe_addresses_for_instance(ec2_client, instance_id) end diff --git a/ruby/example_code/ec2/ec2-ruby-example-get-all-instance-info.rb b/ruby/example_code/ec2/ec2-ruby-example-get-all-instance-info.rb index 5bf07efa142..d72a5895279 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-get-all-instance-info.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-get-all-instance-info.rb @@ -8,7 +8,7 @@ # snippet-start:[ec2.Ruby.getAllInstances] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # @param ec2_resource [Aws::EC2::Resource] An initialized EC2 resource object. # @example @@ -16,9 +16,9 @@ def list_instance_ids_states(ec2_resource) response = ec2_resource.instances if response.count.zero? - puts "No instances found." + puts 'No instances found.' else - puts "Instances -- ID, state:" + puts 'Instances -- ID, state:' response.each do |instance| puts "#{instance.id}, #{instance.state.name}" end @@ -29,17 +29,17 @@ def list_instance_ids_states(ec2_resource) # Example usage: def run_me - region = "" + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-get-all-instance-info.rb REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-get-all-instance-info.rb REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-get-all-instance-info.rb us-west-2" + puts 'Example: ruby ec2-ruby-example-get-all-instance-info.rb us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else region = ARGV[0] diff --git a/ruby/example_code/ec2/ec2-ruby-example-get-instance-info-by-tag.rb b/ruby/example_code/ec2/ec2-ruby-example-get-instance-info-by-tag.rb index 6025c3666d9..a7c1b99e00e 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-get-instance-info-by-tag.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-get-instance-info-by-tag.rb @@ -6,10 +6,9 @@ # list the IDs, current states, and tag keys/values of matching # available Amazon Elastic Compute Cloud (Amazon EC2) instances. - # snippet-start:[ec2.Ruby.getInstanceInforByTag] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # @param ec2_resource [Aws::EC2::Resource] An initialized EC2 resource object. # @param tag_key [String] The key portion of the tag to search on. @@ -30,9 +29,9 @@ def list_instance_ids_states_by_tag(ec2_resource, tag_key, tag_value) ] ) if response.count.zero? - puts "No matching instances found." + puts 'No matching instances found.' else - puts "Matching instances -- ID, state, tag key/value:" + puts 'Matching instances -- ID, state, tag key/value:' response.each do |instance| print "#{instance.id}, #{instance.state.name}" instance.tags.each do |tag| @@ -47,23 +46,23 @@ def list_instance_ids_states_by_tag(ec2_resource, tag_key, tag_value) # Example usage: def run_me - tag_key = "" - tag_value = "" - region = "" + tag_key = '' + tag_value = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-get-instance-info-by-tag.rb " \ - "TAG_KEY TAG_VALUE REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-get-instance-info-by-tag.rb ' \ + 'TAG_KEY TAG_VALUE REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-get-instance-info-by-tag.rb " \ - "my-key my-value us-west-2" + puts 'Example: ruby ec2-ruby-example-get-instance-info-by-tag.rb ' \ + 'my-key my-value us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - tag_key = "my-key" - tag_value = "my-value" - region = "us-west-2" + tag_key = 'my-key' + tag_value = 'my-value' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else tag_key = ARGV[0] diff --git a/ruby/example_code/ec2/ec2-ruby-example-key-pairs.rb b/ruby/example_code/ec2/ec2-ruby-example-key-pairs.rb index ea57e7d91a5..df0a7201aa5 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-key-pairs.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-key-pairs.rb @@ -14,7 +14,7 @@ # 2. Displays information about available key pairs. # 3. Deletes the key pair. -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param key_pair_name [String] The name for the key pair and private @@ -30,17 +30,17 @@ def key_pair_created?(ec2_client, key_pair_name) key_pair = ec2_client.create_key_pair(key_name: key_pair_name) puts "Created key pair '#{key_pair.key_name}' with fingerprint " \ "'#{key_pair.key_fingerprint}' and ID '#{key_pair.key_pair_id}'." - filename = File.join(Dir.home, key_pair_name + ".pem") - File.open(filename, "w") { |file| file.write(key_pair.key_material) } + filename = File.join(Dir.home, "#{key_pair_name}.pem") + File.open(filename, 'w') { |file| file.write(key_pair.key_material) } puts "Private key file saved locally as '#{filename}'." - return true + true rescue Aws::EC2::Errors::InvalidKeyPairDuplicate puts "Error creating key pair: a key pair named '#{key_pair_name}' " \ - "already exists." - return false + 'already exists.' + false rescue StandardError => e puts "Error creating key pair or saving private key file: #{e.message}" - return false + false end # Displays information about available key pairs in @@ -52,9 +52,9 @@ def key_pair_created?(ec2_client, key_pair_name) def describe_key_pairs(ec2_client) result = ec2_client.describe_key_pairs if result.key_pairs.count.zero? - puts "No key pairs found." + puts 'No key pairs found.' else - puts "Key pair names:" + puts 'Key pair names:' result.key_pairs.each do |key_pair| puts key_pair.key_name end @@ -79,26 +79,26 @@ def describe_key_pairs(ec2_client) # ) def key_pair_deleted?(ec2_client, key_pair_name) ec2_client.delete_key_pair(key_name: key_pair_name) - return true + true rescue StandardError => e puts "Error deleting key pair: #{e.message}" - return false + false end # Example usage: def run_me - key_pair_name = "" - region = "" + key_pair_name = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-key-pairs.rb KEY_PAIR_NAME REGION" - puts "Example: ruby ec2-ruby-example-key-pairs.rb my-key-pair us-west-2" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-key-pairs.rb KEY_PAIR_NAME REGION' + puts 'Example: ruby ec2-ruby-example-key-pairs.rb my-key-pair us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - key_pair_name = "my-key-pair" - region = "us-west-2" + key_pair_name = 'my-key-pair' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else key_pair_name = ARGV[0] @@ -107,41 +107,41 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) - puts "Displaying existing key pair names before creating this key pair..." + puts 'Displaying existing key pair names before creating this key pair...' describe_key_pairs(ec2_client) - puts "-" * 10 - puts "Creating key pair..." + puts '-' * 10 + puts 'Creating key pair...' unless key_pair_created?(ec2_client, key_pair_name) - puts "Stopping program." + puts 'Stopping program.' exit 1 end - puts "-" * 10 - puts "Displaying existing key pair names after creating this key pair..." + puts '-' * 10 + puts 'Displaying existing key pair names after creating this key pair...' describe_key_pairs(ec2_client) - puts "-" * 10 - puts "Deleting key pair..." + puts '-' * 10 + puts 'Deleting key pair...' unless key_pair_deleted?(ec2_client, key_pair_name) - puts "Stopping program. You must delete the key pair yourself." + puts 'Stopping program. You must delete the key pair yourself.' exit 1 end - puts "Key pair deleted." + puts 'Key pair deleted.' - puts "-" * 10 - puts "Now that the key pair is deleted, " \ - "also deleting the related private key pair file..." - filename = File.join(Dir.home, key_pair_name + ".pem") + puts '-' * 10 + puts 'Now that the key pair is deleted, ' \ + 'also deleting the related private key pair file...' + filename = File.join(Dir.home, "#{key_pair_name}.pem") File.delete(filename) if File.exist?(filename) puts "Could not delete file at '#{filename}'. You must delete it yourself." else - puts "File deleted." + puts 'File deleted.' end - puts "-" * 10 - puts "Displaying existing key pair names after deleting this key pair..." + puts '-' * 10 + puts 'Displaying existing key pair names after deleting this key pair...' describe_key_pairs(ec2_client) end diff --git a/ruby/example_code/ec2/ec2-ruby-example-list-state-instance-i-123abc.rb b/ruby/example_code/ec2/ec2-ruby-example-list-state-instance-i-123abc.rb index 8690e5dcde5..534117d586b 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-list-state-instance-i-123abc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-list-state-instance-i-123abc.rb @@ -6,7 +6,7 @@ # list the state of an Amazon Elastic Compute Cloud (Amazon EC2) instance. # snippet-start:[ec2.Ruby.listStateInstance] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # # Prerequisites: @@ -25,7 +25,7 @@ def list_instance_state(ec2_client, instance_id) instance_ids: [instance_id] ) if response.count.zero? - puts "No matching instance found." + puts 'No matching instance found.' else instance = response.reservations[0].instances[0] puts "The instance with ID '#{instance_id}' is '#{instance.state.name}'." @@ -36,21 +36,21 @@ def list_instance_state(ec2_client, instance_id) # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-list-state-instance-i-123abc.rb " \ - "INSTANCE_ID REGION" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-list-state-instance-i-123abc.rb " \ - "i-123abc us-west-2" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-list-state-instance-i-123abc.rb ' \ + 'INSTANCE_ID REGION' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-list-state-instance-i-123abc.rb ' \ + 'i-123abc us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - instance_id = "i-123abc" - region = "us-west-2" + instance_id = 'i-123abc' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] diff --git a/ruby/example_code/ec2/ec2-ruby-example-manage-instances.rb b/ruby/example_code/ec2/ec2-ruby-example-manage-instances.rb index 51e65bb7b3f..33f3735a273 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-manage-instances.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-manage-instances.rb @@ -17,7 +17,7 @@ # 4. Enables detailed monitoring for the instance. # 5. Displays information about available instances. -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Waits for an Amazon Elastic Compute Cloud (Amazon EC2) instance # to reach the specified state. @@ -59,10 +59,10 @@ def wait_for_instance(ec2_client, instance_state, instance_id) def instance_stopped?(ec2_client, instance_id) ec2_client.stop_instances(instance_ids: [instance_id]) wait_for_instance(ec2_client, :instance_stopped, instance_id) - return true + true rescue StandardError => e puts "Error stopping instance: #{e.message}" - return false + false end # Attempts to restart an Amazon Elastic Compute Cloud (Amazon EC2) instance. @@ -82,10 +82,10 @@ def instance_stopped?(ec2_client, instance_id) def instance_restarted?(ec2_client, instance_id) ec2_client.start_instances(instance_ids: [instance_id]) wait_for_instance(ec2_client, :instance_running, instance_id) - return true + true rescue StandardError => e puts "Error restarting instance: #{e.message}" - return false + false end # Attempts to reboot an Amazon Elastic Compute Cloud (Amazon EC2) instance. @@ -105,10 +105,10 @@ def instance_restarted?(ec2_client, instance_id) def instance_rebooted?(ec2_client, instance_id) ec2_client.reboot_instances(instance_ids: [instance_id]) wait_for_instance(ec2_client, :instance_status_ok, instance_id) - return true + true rescue StandardError => e puts "Error rebooting instance: #{e.message}" - return false + false end # Attempts to enabled detailed monitoring for an @@ -129,13 +129,13 @@ def instance_rebooted?(ec2_client, instance_id) def instance_detailed_monitoring_enabled?(ec2_client, instance_id) result = ec2_client.monitor_instances(instance_ids: [instance_id]) puts "Detailed monitoring state: #{result.instance_monitorings[0].monitoring.state}" - return true + true rescue Aws::EC2::Errors::InvalidState - puts "The instance is not in a monitorable state. Skipping this step." - return false + puts 'The instance is not in a monitorable state. Skipping this step.' + false rescue StandardError => e puts "Error enabling detailed monitoring: #{e.message}" - return false + false end # Displays information about available @@ -147,28 +147,28 @@ def instance_detailed_monitoring_enabled?(ec2_client, instance_id) def list_instances_information(ec2_client) result = ec2_client.describe_instances result.reservations.each do |reservation| - if reservation.instances.count.positive? - reservation.instances.each do |instance| - puts "-" * 12 - puts "Instance ID: #{instance.instance_id}" - puts "State: #{instance.state.name}" - puts "Image ID: #{instance.image_id}" - puts "Instance type: #{instance.instance_type}" - puts "Architecture: #{instance.architecture}" - puts "IAM instance profile ARN: #{instance.iam_instance_profile.arn}" - puts "Key name: #{instance.key_name}" - puts "Launch time: #{instance.launch_time}" - puts "Detailed monitoring state: #{instance.monitoring.state}" - puts "Public IP address: #{instance.public_ip_address}" - puts "Public DNS name: #{instance.public_dns_name}" - puts "VPC ID: #{instance.vpc_id}" - puts "Subnet ID: #{instance.subnet_id}" - if instance.tags.count.positive? - puts "Tags:" - instance.tags.each do |tag| - puts " #{tag.key}/#{tag.value}" - end - end + next unless reservation.instances.count.positive? + + reservation.instances.each do |instance| + puts '-' * 12 + puts "Instance ID: #{instance.instance_id}" + puts "State: #{instance.state.name}" + puts "Image ID: #{instance.image_id}" + puts "Instance type: #{instance.instance_type}" + puts "Architecture: #{instance.architecture}" + puts "IAM instance profile ARN: #{instance.iam_instance_profile.arn}" + puts "Key name: #{instance.key_name}" + puts "Launch time: #{instance.launch_time}" + puts "Detailed monitoring state: #{instance.monitoring.state}" + puts "Public IP address: #{instance.public_ip_address}" + puts "Public DNS name: #{instance.public_dns_name}" + puts "VPC ID: #{instance.vpc_id}" + puts "Subnet ID: #{instance.subnet_id}" + next unless instance.tags.count.positive? + + puts 'Tags:' + instance.tags.each do |tag| + puts " #{tag.key}/#{tag.value}" end end end @@ -176,21 +176,21 @@ def list_instances_information(ec2_client) # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-manage-instances.rb " \ - "INSTANCE_ID REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-manage-instances.rb ' \ + 'INSTANCE_ID REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-manage-instances.rb " \ - "i-033c48ef067af3dEX us-west-2" + puts 'Example: ruby ec2-ruby-example-manage-instances.rb ' \ + 'i-033c48ef067af3dEX us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - instance_id = "i-033c48ef067af3dEX" - region = "us-west-2" + instance_id = 'i-033c48ef067af3dEX' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] @@ -199,28 +199,22 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) - puts "Attempting to stop the instance. " \ - "This might take a few minutes..." - unless instance_stopped?(ec2_client, instance_id) - puts "Cannot stop the instance. Skipping this step." - end + puts 'Attempting to stop the instance. ' \ + 'This might take a few minutes...' + puts 'Cannot stop the instance. Skipping this step.' unless instance_stopped?(ec2_client, instance_id) puts "\nAttempting to restart the instance. " \ - "This might take a few minutes..." - unless instance_restarted?(ec2_client, instance_id) - puts "Cannot restart the instance. Skipping this step." - end + 'This might take a few minutes...' + puts 'Cannot restart the instance. Skipping this step.' unless instance_restarted?(ec2_client, instance_id) puts "\nAttempting to reboot the instance. " \ - "This might take a few minutes..." - unless instance_rebooted?(ec2_client, instance_id) - puts "Cannot reboot the instance. Skipping this step." - end + 'This might take a few minutes...' + puts 'Cannot reboot the instance. Skipping this step.' unless instance_rebooted?(ec2_client, instance_id) puts "\nAttempting to enable detailed monitoring for the instance..." unless instance_detailed_monitoring_enabled?(ec2_client, instance_id) - puts "Cannot enable detailed monitoring for the instance. " \ - "Skipping this step." + puts 'Cannot enable detailed monitoring for the instance. ' \ + 'Skipping this step.' end puts "\nInformation about available instances:" diff --git a/ruby/example_code/ec2/ec2-ruby-example-reboot-instance-i-123abc.rb b/ruby/example_code/ec2/ec2-ruby-example-reboot-instance-i-123abc.rb index 3484fa5e750..b2d05e5385b 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-reboot-instance-i-123abc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-reboot-instance-i-123abc.rb @@ -7,7 +7,7 @@ # snippet-start:[ec2.Ruby.rebootInstances] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Prerequisites: # @@ -23,14 +23,14 @@ def request_instance_reboot(ec2_client, instance_id) response = ec2_client.describe_instances(instance_ids: [instance_id]) if response.count.zero? - puts "Error requesting reboot: no matching instance found." + puts 'Error requesting reboot: no matching instance found.' else instance = response.reservations[0].instances[0] - if instance.state.name == "terminated" - puts "Error requesting reboot: the instance is already terminated." + if instance.state.name == 'terminated' + puts 'Error requesting reboot: the instance is already terminated.' else ec2_client.reboot_instances(instance_ids: [instance_id]) - puts "Reboot request sent." + puts 'Reboot request sent.' end end rescue StandardError => e @@ -39,21 +39,21 @@ def request_instance_reboot(ec2_client, instance_id) # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-reboot-instance-i-123abc.rb " \ - "INSTANCE_ID REGION" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-reboot-instance-i-123abc.rb " \ - "i-123abc us-west-2" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-reboot-instance-i-123abc.rb ' \ + 'INSTANCE_ID REGION' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-reboot-instance-i-123abc.rb ' \ + 'i-123abc us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - instance_id = "i-123abc" - region = "us-west-2" + instance_id = 'i-123abc' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] diff --git a/ruby/example_code/ec2/ec2-ruby-example-regions-availability-zones.rb b/ruby/example_code/ec2/ec2-ruby-example-regions-availability-zones.rb index 5700db883ee..2ea33f48f8e 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-regions-availability-zones.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-regions-availability-zones.rb @@ -8,7 +8,7 @@ # snippet-start:[ec2.Ruby.regionsAvailabilityZones] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @example @@ -19,18 +19,18 @@ def list_regions_endpoints(ec2_client) max_region_string_length = 16 max_endpoint_string_length = 33 # Print header. - print "Region" - print " " * (max_region_string_length - "Region".length) + print 'Region' + print ' ' * (max_region_string_length - 'Region'.length) print " Endpoint\n" - print "-" * max_region_string_length - print " " - print "-" * max_endpoint_string_length + print '-' * max_region_string_length + print ' ' + print '-' * max_endpoint_string_length print "\n" # Print Regions and their endpoints. result.regions.each do |region| print region.region_name - print " " * (max_region_string_length - region.region_name.length) - print " " + print ' ' * (max_region_string_length - region.region_name.length) + print ' ' print region.endpoint print "\n" end @@ -50,30 +50,30 @@ def list_availability_zones(ec2_client) max_zone_string_length = 18 max_state_string_length = 9 # Print header. - print "Region" - print " " * (max_region_string_length - "Region".length) - print " Zone" - print " " * (max_zone_string_length - "Zone".length) + print 'Region' + print ' ' * (max_region_string_length - 'Region'.length) + print ' Zone' + print ' ' * (max_zone_string_length - 'Zone'.length) print " State\n" - print "-" * max_region_string_length - print " " - print "-" * max_zone_string_length - print " " - print "-" * max_state_string_length + print '-' * max_region_string_length + print ' ' + print '-' * max_zone_string_length + print ' ' + print '-' * max_state_string_length print "\n" # Print Regions, Availability Zones, and their states. result.availability_zones.each do |zone| print zone.region_name - print " " * (max_region_string_length - zone.region_name.length) - print " " + print ' ' * (max_region_string_length - zone.region_name.length) + print ' ' print zone.zone_name - print " " * (max_zone_string_length - zone.zone_name.length) - print " " + print ' ' * (max_zone_string_length - zone.zone_name.length) + print ' ' print zone.state # Print any messages for this Availability Zone. if zone.messages.count.positive? print "\n" - puts " Messages for this zone:" + puts ' Messages for this zone:' zone.messages.each do |message| print " #{message.message}\n" end @@ -84,17 +84,17 @@ def list_availability_zones(ec2_client) # Example usage: def run_me - region = "" + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-regions-availability-zones.rb REGION" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-regions-availability-zones.rb REGION' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-regions-availability-zones.rb us-west-2" + puts 'Example: ruby ec2-ruby-example-regions-availability-zones.rb us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - region = "us-west-2" + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else region = ARGV[0] @@ -102,7 +102,7 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) - puts "AWS Regions for Amazon EC2 that are available to you:" + puts 'AWS Regions for Amazon EC2 that are available to you:' list_regions_endpoints(ec2_client) puts "\n\nAmazon EC2 Availability Zones that are available to you for AWS Region '#{region}':" list_availability_zones(ec2_client) diff --git a/ruby/example_code/ec2/ec2-ruby-example-security-group.rb b/ruby/example_code/ec2/ec2-ruby-example-security-group.rb index abeea02da4d..de3e97adbd9 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-security-group.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-security-group.rb @@ -15,7 +15,7 @@ # 3. Displays information about available security groups. # 4. Deletes the security group. -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group. # @@ -36,12 +36,7 @@ # 'This is my security group.', # 'vpc-6713dfEX' # ) -def create_security_group( - ec2_client, - group_name, - description, - vpc_id -) +def create_security_group(ec2_client, group_name, description, vpc_id) security_group = ec2_client.create_security_group( group_name: group_name, description: description, @@ -49,10 +44,10 @@ def create_security_group( ) puts "Created security group '#{group_name}' with ID " \ "'#{security_group.group_id}' in VPC with ID '#{vpc_id}'." - return security_group.group_id + security_group.group_id rescue StandardError => e puts "Error creating security group: #{e.message}" - return "Error" + 'Error' end # Adds an inbound rule to an Amazon Elastic Compute Cloud (Amazon EC2) @@ -79,12 +74,7 @@ def create_security_group( # '0.0.0.0/0' # ) def security_group_ingress_authorized?( - ec2_client, - security_group_id, - ip_protocol, - from_port, - to_port, - cidr_ip_range + ec2_client, security_group_id, ip_protocol, from_port, to_port, cidr_ip_range ) ec2_client.authorize_security_group_ingress( group_id: security_group_id, @@ -104,237 +94,163 @@ def security_group_ingress_authorized?( puts "Added inbound rule to security group '#{security_group_id}' for protocol " \ "'#{ip_protocol}' from port '#{from_port}' to port '#{to_port}' " \ "with CIDR IP range '#{cidr_ip_range}'." - return true + true rescue StandardError => e puts "Error adding inbound rule to security group: #{e.message}" - return false + false +end + +# Refactored method to simplify complexity for describing security group permissions +def format_port_information(perm) + from_port_str = perm.from_port == '-1' || perm.from_port == -1 ? 'All' : perm.from_port.to_s + to_port_str = perm.to_port == '-1' || perm.to_port == -1 ? 'All' : perm.to_port.to_s + { from_port: from_port_str, to_port: to_port_str } end # Displays information about a security group's IP permissions set in # Amazon Elastic Compute Cloud (Amazon EC2). -# -# Prerequisites: -# -# - A security group with inbound rules, outbound rules, or both. -# -# @param p [Aws::EC2::Types::IpPermission] The IP permissions set. -# @example -# ec2_client = Aws::EC2::Client.new(region: 'us-west-2') -# response = ec2_client.describe_security_groups -# unless sg.ip_permissions.empty? -# describe_security_group_permissions( -# response.security_groups[0].ip_permissions[0] -# ) -# end def describe_security_group_permissions(perm) - print " Protocol: #{perm.ip_protocol == '-1' ? 'All' : perm.ip_protocol}" + ports = format_port_information(perm) - unless perm.from_port.nil? - if perm.from_port == "-1" || perm.from_port == -1 - print ", From: All" - else - print ", From: #{perm.from_port}" - end - end - - unless perm.to_port.nil? - if perm.to_port == "-1" || perm.to_port == -1 - print ", To: All" - else - print ", To: #{perm.to_port}" - end - end - - if perm.key?(:ipv_6_ranges) && perm.ipv_6_ranges.count.positive? - print ", CIDR IPv6: #{perm.ipv_6_ranges[0].cidr_ipv_6}" - end + print " Protocol: #{perm.ip_protocol == '-1' ? 'All' : perm.ip_protocol}" + print ", From: #{ports[:from_port]}, To: #{ports[:to_port]}" - if perm.key?(:ip_ranges) && perm.ip_ranges.count.positive? - print ", CIDR IPv4: #{perm.ip_ranges[0].cidr_ip}" - end + print ", CIDR IPv6: #{perm.ipv_6_ranges[0].cidr_ipv_6}" if perm.key?(:ipv_6_ranges) && perm.ipv_6_ranges.count.positive? + print ", CIDR IPv4: #{perm.ip_ranges[0].cidr_ip}" if perm.key?(:ip_ranges) && perm.ip_ranges.count.positive? print "\n" end # Displays information about available security groups in # Amazon Elastic Compute Cloud (Amazon EC2). -# -# @param ec2_client [Aws::EC2::Client] An initialized Amazon EC2 client. -# @example -# describe_security_groups(Aws::EC2::Client.new(region: 'us-west-2')) def describe_security_groups(ec2_client) response = ec2_client.describe_security_groups if response.security_groups.count.positive? response.security_groups.each do |sg| - puts "-" * (sg.group_name.length + 13) - puts "Name: #{sg.group_name}" - puts "Description: #{sg.description}" - puts "Group ID: #{sg.group_id}" - puts "Owner ID: #{sg.owner_id}" - puts "VPC ID: #{sg.vpc_id}" - - if sg.tags.count.positive? - puts "Tags:" - sg.tags.each do |tag| - puts " Key: #{tag.key}, Value: #{tag.value}" - end - end - - unless sg.ip_permissions.empty? - puts "Inbound rules:" if sg.ip_permissions.count.positive? - sg.ip_permissions.each do |p| - describe_security_group_permissions(p) - end - end - - unless sg.ip_permissions_egress.empty? - puts "Outbound rules:" if sg.ip_permissions.count.positive? - sg.ip_permissions_egress.each do |p| - describe_security_group_permissions(p) - end - end + display_group_details(sg) end else - puts "No security groups found." + puts 'No security groups found.' end rescue StandardError => e puts "Error getting information about security groups: #{e.message}" end +# Helper method to display the details of security groups +def display_group_details(sg) + puts '-' * (sg.group_name.length + 13) + puts "Name: #{sg.group_name}" + puts "Description: #{sg.description}" + puts "Group ID: #{sg.group_id}" + puts "Owner ID: #{sg.owner_id}" + puts "VPC ID: #{sg.vpc_id}" + + display_group_tags(sg.tags) if sg.tags.count.positive? + display_group_permissions(sg) +end + +def display_group_tags(tags) + puts 'Tags:' + tags.each do |tag| + puts " Key: #{tag.key}, Value: #{tag.value}" + end +end + +def display_group_permissions(sg) + if sg.ip_permissions.count.positive? + puts 'Inbound rules:' + sg.ip_permissions.each do |p| + describe_security_group_permissions(p) + end + end + + return if sg.ip_permissions_egress.empty? + + puts 'Outbound rules:' + sg.ip_permissions_egress.each do |p| + describe_security_group_permissions(p) + end +end + # Deletes an Amazon Elastic Compute Cloud (Amazon EC2) # security group. -# -# Prerequisites: -# -# - The security group. -# -# @param ec2_client [Aws::EC2::Client] An initialized -# Amazon EC2 client. -# @param security_group_id [String] The ID of the security group to delete. -# @return [Boolean] true if the security group was deleted; otherwise, false. -# @example -# exit 1 unless security_group_deleted?( -# Aws::EC2::Client.new(region: 'us-west-2'), -# 'sg-030a858e078f1b9EX' -# ) def security_group_deleted?(ec2_client, security_group_id) ec2_client.delete_security_group(group_id: security_group_id) puts "Deleted security group '#{security_group_id}'." - return true + true rescue StandardError => e puts "Error deleting security group: #{e.message}" - return false + false end -# Example usage: +# Example usage with refactored run_me to reduce complexity def run_me - group_name = "" - description = "" - vpc_id = "" - ip_protocol_http = "" - from_port_http = "" - to_port_http = "" - cidr_ip_range_http = "" - ip_protocol_ssh = "" - from_port_ssh = "" - to_port_ssh = "" - cidr_ip_range_ssh = "" - region = "" - # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-security-group.rb " \ - "GROUP_NAME DESCRIPTION VPC_ID IP_PROTOCOL_1 FROM_PORT_1 TO_PORT_1 " \ - "CIDR_IP_RANGE_1 IP_PROTOCOL_2 FROM_PORT_2 TO_PORT_2 " \ - "CIDR_IP_RANGE_2 REGION" - puts "Example: ruby ec2-ruby-example-security-group.rb " \ - "my-security-group 'This is my security group.' vpc-6713dfEX " \ - "tcp 80 80 '0.0.0.0/0' tcp 22 22 '0.0.0.0/0' us-west-2" + group_name, description, vpc_id, ip_protocol_http, from_port_http, to_port_http, \ + cidr_ip_range_http, ip_protocol_ssh, from_port_ssh, to_port_ssh, \ + cidr_ip_range_ssh, region = process_arguments + ec2_client = Aws::EC2::Client.new(region: region) + + security_group_id = attempt_create_security_group(ec2_client, group_name, description, vpc_id) + security_group_exists = security_group_id != 'Error' + + if security_group_exists + add_inbound_rules(ec2_client, security_group_id, ip_protocol_http, from_port_http, to_port_http, cidr_ip_range_http) + add_inbound_rules(ec2_client, security_group_id, ip_protocol_ssh, from_port_ssh, to_port_ssh, cidr_ip_range_ssh) + end + + describe_security_groups(ec2_client) + attempt_delete_security_group(ec2_client, security_group_id) if security_group_exists +end + +def process_arguments + if ARGV[0] == '--help' || ARGV[0] == '-h' + display_help exit 1 - # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? - group_name = "my-security-group" - description = "This is my security group." - vpc_id = "vpc-6713dfEX" - ip_protocol_http = "tcp" - from_port_http = "80" - to_port_http = "80" - cidr_ip_range_http = "0.0.0.0/0" - ip_protocol_ssh = "tcp" - from_port_ssh = "22" - to_port_ssh = "22" - cidr_ip_range_ssh = "0.0.0.0/0" - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - region = "us-west-2" - # Otherwise, use the values as specified at the command prompt. + default_values else - group_name = ARGV[0] - description = ARGV[1] - vpc_id = ARGV[2] - ip_protocol_http = ARGV[3] - from_port_http = ARGV[4] - to_port_http = ARGV[5] - cidr_ip_range_http = ARGV[6] - ip_protocol_ssh = ARGV[7] - from_port_ssh = ARGV[8] - to_port_ssh = ARGV[9] - cidr_ip_range_ssh = ARGV[10] - region = ARGV[11] + ARGV end +end - security_group_id = "" - security_group_exists = false - ec2_client = Aws::EC2::Client.new(region: region) +def attempt_create_security_group(ec2_client, group_name, description, vpc_id) + puts 'Attempting to create security group...' + security_group_id = create_security_group(ec2_client, group_name, description, vpc_id) + puts 'Could not create security group. Skipping this step.' if security_group_id == 'Error' + security_group_id +end - puts "Attempting to create security group..." - security_group_id = create_security_group( - ec2_client, - group_name, - description, - vpc_id - ) - if security_group_id == "Error" - puts "Could not create security group. Skipping this step." - else - security_group_exists = true - end +def add_inbound_rules(ec2_client, security_group_id, ip_protocol, from_port, to_port, cidr_ip_range) + puts 'Attempting to add inbound rules to security group...' + return if security_group_ingress_authorized?(ec2_client, security_group_id, ip_protocol, from_port, to_port, + cidr_ip_range) - if security_group_exists - puts "Attempting to add inbound rules to security group..." - unless security_group_ingress_authorized?( - ec2_client, - security_group_id, - ip_protocol_http, - from_port_http, - to_port_http, - cidr_ip_range_http - ) - puts "Could not add inbound HTTP rule to security group. " \ - "Skipping this step." - end + puts 'Could not add inbound rule to security group. Skipping this step.' +end - unless security_group_ingress_authorized?( - ec2_client, - security_group_id, - ip_protocol_ssh, - from_port_ssh, - to_port_ssh, - cidr_ip_range_ssh - ) - puts "Could not add inbound SSH rule to security group. " \ - "Skipping this step." - end - end +def attempt_delete_security_group(ec2_client, security_group_id) + puts "\nAttempting to delete security group..." + return if security_group_deleted?(ec2_client, security_group_id) - puts "\nInformation about available security groups:" - describe_security_groups(ec2_client) + puts 'Could not delete security group. You must delete it yourself.' +end - if security_group_exists - puts "\nAttempting to delete security group..." - unless security_group_deleted?(ec2_client, security_group_id) - puts "Could not delete security group. You must delete it yourself." - end - end +def display_help + puts 'Usage: ruby ec2-ruby-example-security-group.rb ' \ + 'GROUP_NAME DESCRIPTION VPC_ID IP_PROTOCOL_1 FROM_PORT_1 TO_PORT_1 ' \ + 'CIDR_IP_RANGE_1 IP_PROTOCOL_2 FROM_PORT_2 TO_PORT_2 ' \ + 'CIDR_IP_RANGE_2 REGION' + puts 'Example: ruby ec2-ruby-example-security-group.rb ' \ + "my-security-group 'This is my security group.' vpc-6713dfEX " \ + "tcp 80 80 '0.0.0.0/0' tcp 22 22 '0.0.0.0/0' us-west-2" +end + +def default_values + [ + 'my-security-group', 'This is my security group.', 'vpc-6713dfEX', 'tcp', '80', '80', + '0.0.0.0/0', 'tcp', '22', '22', '0.0.0.0/0', 'us-west-2' + ] end run_me if $PROGRAM_NAME == __FILE__ diff --git a/ruby/example_code/ec2/ec2-ruby-example-start-instance-i-123abc.rb b/ruby/example_code/ec2/ec2-ruby-example-start-instance-i-123abc.rb index 84f378b56a3..a82d3581ac5 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-start-instance-i-123abc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-start-instance-i-123abc.rb @@ -8,7 +8,7 @@ # snippet-start:[ec2.Ruby.startInstance] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Attempts to start an Amazon Elastic Compute Cloud (Amazon EC2) instance. # @@ -30,45 +30,45 @@ def instance_started?(ec2_client, instance_id) if response.instance_statuses.count.positive? state = response.instance_statuses[0].instance_state.name case state - when "pending" - puts "Error starting instance: the instance is pending. Try again later." + when 'pending' + puts 'Error starting instance: the instance is pending. Try again later.' return false - when "running" - puts "The instance is already running." + when 'running' + puts 'The instance is already running.' return true - when "terminated" - puts "Error starting instance: " \ - "the instance is terminated, so you cannot start it." + when 'terminated' + puts 'Error starting instance: ' \ + 'the instance is terminated, so you cannot start it.' return false end end ec2_client.start_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_running, instance_ids: [instance_id]) - puts "Instance started." - return true + puts 'Instance started.' + true rescue StandardError => e puts "Error starting instance: #{e.message}" - return false + false end # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-start-instance-i-123abc.rb " \ - "INSTANCE_ID REGION " - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-start-instance-i-123abc.rb " \ - "i-123abc us-west-2" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \ + 'INSTANCE_ID REGION ' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \ + 'i-123abc us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - instance_id = "i-123abc" - region = "us-west-2" + instance_id = 'i-123abc' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] @@ -78,10 +78,10 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) puts "Attempting to start instance '#{instance_id}' " \ - "(this might take a few minutes)..." - unless instance_started?(ec2_client, instance_id) - puts "Could not start instance." - end + '(this might take a few minutes)...' + return if instance_started?(ec2_client, instance_id) + + puts 'Could not start instance.' end run_me if $PROGRAM_NAME == __FILE__ diff --git a/ruby/example_code/ec2/ec2-ruby-example-stop-instance-i-123abc.rb b/ruby/example_code/ec2/ec2-ruby-example-stop-instance-i-123abc.rb index ced2887f58e..c6d97246d34 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-stop-instance-i-123abc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-stop-instance-i-123abc.rb @@ -7,7 +7,7 @@ # snippet-start:[ec2.Ruby.stopInstances] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Prerequisites: # @@ -27,45 +27,45 @@ def instance_stopped?(ec2_client, instance_id) if response.instance_statuses.count.positive? state = response.instance_statuses[0].instance_state.name case state - when "stopping" - puts "The instance is already stopping." + when 'stopping' + puts 'The instance is already stopping.' return true - when "stopped" - puts "The instance is already stopped." + when 'stopped' + puts 'The instance is already stopped.' return true - when "terminated" - puts "Error stopping instance: " \ - "the instance is terminated, so you cannot stop it." + when 'terminated' + puts 'Error stopping instance: ' \ + 'the instance is terminated, so you cannot stop it.' return false end end ec2_client.stop_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_stopped, instance_ids: [instance_id]) - puts "Instance stopped." - return true + puts 'Instance stopped.' + true rescue StandardError => e puts "Error stopping instance: #{e.message}" - return false + false end # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-stop-instance-i-123abc.rb " \ - "INSTANCE_ID REGION " + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-stop-instance-i-123abc.rb ' \ + 'INSTANCE_ID REGION ' # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-start-instance-i-123abc.rb " \ - "i-123abc us-west-2" + puts 'Example: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \ + 'i-123abc us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - instance_id = "i-123abc" - region = "us-west-2" + instance_id = 'i-123abc' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] @@ -75,10 +75,10 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) puts "Attempting to stop instance '#{instance_id}' " \ - "(this might take a few minutes)..." - unless instance_stopped?(ec2_client, instance_id) - puts "Could not stop instance." - end + '(this might take a few minutes)...' + return if instance_stopped?(ec2_client, instance_id) + + puts 'Could not stop instance.' end run_me if $PROGRAM_NAME == __FILE__ diff --git a/ruby/example_code/ec2/ec2-ruby-example-terminate-instance-i-123abc.rb b/ruby/example_code/ec2/ec2-ruby-example-terminate-instance-i-123abc.rb index a104d1c3f56..a3682309bf3 100644 --- a/ruby/example_code/ec2/ec2-ruby-example-terminate-instance-i-123abc.rb +++ b/ruby/example_code/ec2/ec2-ruby-example-terminate-instance-i-123abc.rb @@ -11,7 +11,7 @@ # snippet-start:[ec2.Ruby.terminateInstances] -require "aws-sdk-ec2" +require 'aws-sdk-ec2' # Prerequisites: # @@ -29,38 +29,38 @@ def instance_terminated?(ec2_client, instance_id) response = ec2_client.describe_instance_status(instance_ids: [instance_id]) if response.instance_statuses.count.positive? && - response.instance_statuses[0].instance_state.name == "terminated" + response.instance_statuses[0].instance_state.name == 'terminated' - puts "The instance is already terminated." + puts 'The instance is already terminated.' return true end ec2_client.terminate_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_terminated, instance_ids: [instance_id]) - puts "Instance terminated." - return true + puts 'Instance terminated.' + true rescue StandardError => e puts "Error terminating instance: #{e.message}" - return false + false end # Example usage: def run_me - instance_id = "" - region = "" + instance_id = '' + region = '' # Print usage information and then stop. - if ARGV[0] == "--help" || ARGV[0] == "-h" - puts "Usage: ruby ec2-ruby-example-terminate-instance-i-123abc.rb " \ - "INSTANCE_ID REGION " - # Replace us-west-2 with the AWS Region you're using for Amazon EC2. - puts "Example: ruby ec2-ruby-example-terminate-instance-i-123abc.rb " \ - "i-123abc us-west-2" + if ARGV[0] == '--help' || ARGV[0] == '-h' + puts 'Usage: ruby ec2-ruby-example-terminate-instance-i-123abc.rb ' \ + 'INSTANCE_ID REGION ' + # Replace us-west-2 with the AWS Region you're using for Amazon EC2. + puts 'Example: ruby ec2-ruby-example-terminate-instance-i-123abc.rb ' \ + 'i-123abc us-west-2' exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? - instance_id = "i-123abc" - region = "us-west-2" + instance_id = 'i-123abc' + region = 'us-west-2' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] @@ -70,10 +70,10 @@ def run_me ec2_client = Aws::EC2::Client.new(region: region) puts "Attempting to terminate instance '#{instance_id}' " \ - "(this might take a few minutes)..." - unless instance_terminated?(ec2_client, instance_id) - puts "Could not terminate instance." - end + '(this might take a few minutes)...' + return if instance_terminated?(ec2_client, instance_id) + + puts 'Could not terminate instance.' end run_me if $PROGRAM_NAME == __FILE__ diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-attach-igw-vpc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-attach-igw-vpc.rb index d39b0006516..7a920546c8c 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-attach-igw-vpc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-attach-igw-vpc.rb @@ -1,18 +1,18 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-attach-igw-vpc" +require_relative '../ec2-ruby-example-attach-igw-vpc' -describe "#internet_gateway_created_and_attached?" do - let(:vpc_id) { "vpc-6713dfEX" } - let(:tag_key) { "my-key" } - let(:tag_value) { "my-value" } +describe '#internet_gateway_created_and_attached?' do + let(:vpc_id) { 'vpc-6713dfEX' } + let(:tag_key) { 'my-key' } + let(:tag_value) { 'my-value' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { create_internet_gateway: { internet_gateway: { - internet_gateway_id: "igw-052bf3915781dd0EX" + internet_gateway_id: 'igw-052bf3915781dd0EX' } }, attach_internet_gateway: {}, @@ -22,7 +22,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates an internet gateway and attaches it to a VPC" do + it 'creates an internet gateway and attaches it to a VPC' do expect( internet_gateway_created_and_attached?( ec2_resource, diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-instance.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-instance.rb index f4aa730184b..1354d65e57b 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-instance.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-instance.rb @@ -1,14 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-create-instance" +require_relative '../ec2-ruby-example-create-instance' -describe "#instance_created?" do - let(:image_id) { "ami-0947d2ba12EXAMPLE" } - let(:key_pair_name) { "my-key-pair" } - let(:tag_key) { "my-key" } - let(:tag_value) { "my-value" } - let(:instance_id) { "i-01c7a43263ddbc7EX" } +describe '#instance_created?' do + let(:image_id) { 'ami-0947d2ba12EXAMPLE' } + let(:key_pair_name) { 'my-key-pair' } + let(:tag_key) { 'my-key' } + let(:tag_value) { 'my-value' } + let(:instance_id) { 'i-01c7a43263ddbc7EX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -22,7 +22,7 @@ instances: [ instance_id: instance_id, state: { - name: "running" + name: 'running' } ] ] @@ -33,7 +33,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates an instance" do + it 'creates an instance' do expect( instance_created?( ec2_resource, diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-key-pair.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-key-pair.rb index 9af6e5c707f..63726b22b50 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-key-pair.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-key-pair.rb @@ -1,18 +1,17 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-create-key-pair" +require_relative '../ec2-ruby-example-create-key-pair' -describe "#key_pair_created?" do - let(:key_pair_name) { "delete-this-key-pair--only-a-test" } +describe '#key_pair_created?' do + let(:key_pair_name) { 'delete-this-key-pair--only-a-test' } let(:ec2_client) do - Aws::EC2::Client.new( stub_responses: { create_key_pair: { key_name: key_pair_name, - key_fingerprint: "EX:AM:PL:E4:ac:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE", - key_pair_id: "key-08021f7c59EXAMPLE", + key_fingerprint: 'EX:AM:PL:E4:ac:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE', + key_pair_id: 'key-08021f7c59EXAMPLE', key_material: "-----BEGIN RSA PRIVATE KEY-----\n_omitted_for_brevity\n-----END RSA PRIVATE KEY-----" } } @@ -20,7 +19,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates a key pair" do + it 'creates a key pair' do expect(key_pair_created?(ec2_client, key_pair_name)).to be(true) end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-route-table.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-route-table.rb index 5fa296a5907..80ef2f999e4 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-route-table.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-route-table.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-create-route-table" +require_relative '../ec2-ruby-example-create-route-table' -describe "#route_table_created_and_associated?" do - let(:vpc_id) { "vpc-0b6f769731EXAMPLE" } - let(:subnet_id) { "subnet-03d9303b57EXAMPLE" } - let(:gateway_id) { "igw-06ca90c011EXAMPLE" } - let(:destination_cidr_block) { "0.0.0.0/0" } - let(:tag_key) { "my-key" } - let(:tag_value) { "my-value" } +describe '#route_table_created_and_associated?' do + let(:vpc_id) { 'vpc-0b6f769731EXAMPLE' } + let(:subnet_id) { 'subnet-03d9303b57EXAMPLE' } + let(:gateway_id) { 'igw-06ca90c011EXAMPLE' } + let(:destination_cidr_block) { '0.0.0.0/0' } + let(:tag_key) { 'my-key' } + let(:tag_value) { 'my-value' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { create_route_table: { route_table: { - route_table_id: "rtb-225746EX" + route_table_id: 'rtb-225746EX' } }, create_tags: {}, @@ -23,14 +23,14 @@ return: true }, associate_route_table: { - association_id: "rtbassoc-781d0dEX" + association_id: 'rtbassoc-781d0dEX' } } ) end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates and associates a route table" do + it 'creates and associates a route table' do expect( route_table_created_and_associated?( ec2_resource, diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-security-group.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-security-group.rb index 9e132b5881e..034bb92f90b 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-security-group.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-security-group.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-create-security-group" +require_relative '../ec2-ruby-example-create-security-group' -describe "#security_group_created_with_egress?" do - let(:group_name) { "my-security-group" } - let(:description) { "This is my security group." } - let(:vpc_id) { "vpc-6713dfEX" } - let(:ip_protocol) { "tcp" } - let(:from_port) { "22" } - let(:to_port) { "22" } - let(:cidr_ip_range) { "0.0.0.0/0" } +describe '#security_group_created_with_egress?' do + let(:group_name) { 'my-security-group' } + let(:description) { 'This is my security group.' } + let(:vpc_id) { 'vpc-6713dfEX' } + let(:ip_protocol) { 'tcp' } + let(:from_port) { '22' } + let(:to_port) { '22' } + let(:cidr_ip_range) { '0.0.0.0/0' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { create_security_group: { - group_id: "sg-903004EX" + group_id: 'sg-903004EX' }, authorize_security_group_egress: {} } @@ -23,7 +23,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates a security group and adds an egress rule" do + it 'creates a security group and adds an egress rule' do expect( security_group_created_with_egress?( ec2_resource, diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-subnet.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-subnet.rb index 504b0e55dd3..0684e8ad005 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-subnet.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-subnet.rb @@ -1,20 +1,20 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-create-subnet" +require_relative '../ec2-ruby-example-create-subnet' -describe "#subnet_created_and_tagged?" do - let(:vpc_id) { "vpc-6713dfEX" } - let(:cidr_block) { "10.0.0.0/24" } - let(:availability_zone) { "us-west-2a" } - let(:tag_key) { "my-key" } - let(:tag_value) { "my-value" } +describe '#subnet_created_and_tagged?' do + let(:vpc_id) { 'vpc-6713dfEX' } + let(:cidr_block) { '10.0.0.0/24' } + let(:availability_zone) { 'us-west-2a' } + let(:tag_key) { 'my-key' } + let(:tag_value) { 'my-value' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { create_subnet: { subnet: { - subnet_id: "subnet-03d9303b57c7187EX" + subnet_id: 'subnet-03d9303b57c7187EX' } }, create_tags: {} @@ -23,7 +23,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates and tags a subnet" do + it 'creates and tags a subnet' do expect( subnet_created_and_tagged?( ec2_resource, diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-vpc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-vpc.rb index b5f9cca5f9d..0ac28f38548 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-vpc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-create-vpc.rb @@ -1,18 +1,18 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-create-vpc" +require_relative '../ec2-ruby-example-create-vpc' -describe "#vpc_created_and_tagged?" do - let(:cidr_block) { "10.0.0.0/24" } - let(:tag_key) { "my-key" } - let(:tag_value) { "my-value" } +describe '#vpc_created_and_tagged?' do + let(:cidr_block) { '10.0.0.0/24' } + let(:tag_key) { 'my-key' } + let(:tag_value) { 'my-value' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { create_vpc: { vpc: { - vpc_id: "vpc-6713dfEX" + vpc_id: 'vpc-6713dfEX' } }, modify_vpc_attribute: {}, @@ -22,7 +22,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates and tags a VPC" do + it 'creates and tags a VPC' do expect( vpc_created_and_tagged?( ec2_resource, diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-elastic-ips.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-elastic-ips.rb index c91569367a4..cf73091ee45 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-elastic-ips.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-elastic-ips.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-elastic-ips" +require_relative '../ec2-ruby-example-elastic-ips' -describe "#instance_exists?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_exists?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -21,14 +21,14 @@ ) end - it "checks whether the instance exists" do + it 'checks whether the instance exists' do expect(instance_exists?(ec2_client, instance_id)).to be(true) end end -describe "#allocate_elastic_ip_address" do - let(:instance_id) { "i-033c48ef067af3dEX" } - let(:allocation_id) { "eipalloc-0e7e1c46c5ee5f8EX" } +describe '#allocate_elastic_ip_address' do + let(:instance_id) { 'i-033c48ef067af3dEX' } + let(:allocation_id) { 'eipalloc-0e7e1c46c5ee5f8EX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -39,15 +39,15 @@ ) end - it "checks for the Elastic IP address allocation ID" do + it 'checks for the Elastic IP address allocation ID' do expect(allocate_elastic_ip_address(ec2_client)).to eq(allocation_id) end end -describe "#associate_elastic_ip_address_with_instance" do - let(:instance_id) { "i-033c48ef067af3dEX" } - let(:allocation_id) { "eipalloc-0e7e1c46c5ee5f8EX" } - let(:association_id) { "eipassoc-010e2d189043030EX" } +describe '#associate_elastic_ip_address_with_instance' do + let(:instance_id) { 'i-033c48ef067af3dEX' } + let(:allocation_id) { 'eipalloc-0e7e1c46c5ee5f8EX' } + let(:association_id) { 'eipassoc-010e2d189043030EX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -58,7 +58,7 @@ ) end - it "checks for the Elastic IP address allocation ID" do + it 'checks for the Elastic IP address allocation ID' do expect( associate_elastic_ip_address_with_instance( ec2_client, @@ -69,16 +69,16 @@ end end -describe "#describe_addresses_for_instance" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#describe_addresses_for_instance' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { describe_addresses: { addresses: [ { - public_ip: "203.0.113.0", - private_ip_address: "10.0.1.241" + public_ip: '203.0.113.0', + private_ip_address: '10.0.1.241' } ] } @@ -86,14 +86,14 @@ ) end - it "lists information about the instance" do + it 'lists information about the instance' do expect { describe_addresses_for_instance(ec2_client, instance_id) }.not_to raise_error end end -describe "#elastic_ip_address_released?" do - let(:instance_id) { "i-033c48ef067af3dEX" } - let(:allocation_id) { "eipalloc-0e7e1c46c5ee5f8EX" } +describe '#elastic_ip_address_released?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } + let(:allocation_id) { 'eipalloc-0e7e1c46c5ee5f8EX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -102,7 +102,7 @@ ) end - it "releases the Elastic IP address" do + it 'releases the Elastic IP address' do expect(elastic_ip_address_released?(ec2_client, allocation_id)).to be(true) end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-all-instance-info.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-all-instance-info.rb index cba97fbece5..489f02f7dcb 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-all-instance-info.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-all-instance-info.rb @@ -1,18 +1,18 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-get-all-instance-info" +require_relative '../ec2-ruby-example-get-all-instance-info' -describe "#list_instance_ids_states" do +describe '#list_instance_ids_states' do let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { describe_instances: { reservations: [ instances: [ - { instance_id: "i-abc123-1", state: { name: "running" } }, - { instance_id: "i-abc123-2", state: { name: "running" } }, - { instance_id: "i-abc123-3", state: { name: "running" } } + { instance_id: 'i-abc123-1', state: { name: 'running' } }, + { instance_id: 'i-abc123-2', state: { name: 'running' } }, + { instance_id: 'i-abc123-3', state: { name: 'running' } } ] ] } @@ -21,7 +21,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "lists instance IDs and states" do + it 'lists instance IDs and states' do expect { list_instance_ids_states(ec2_resource) }.not_to raise_error end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-instance-info-by-tag.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-instance-info-by-tag.rb index 9112c4d886b..018780f4d0c 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-instance-info-by-tag.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-get-instance-info-by-tag.rb @@ -1,20 +1,20 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-get-instance-info-by-tag" +require_relative '../ec2-ruby-example-get-instance-info-by-tag' -describe "#list_instance_ids_states" do - let(:tag_key) { "my-key" } - let(:tag_value) { "my-value" } +describe '#list_instance_ids_states' do + let(:tag_key) { 'my-key' } + let(:tag_value) { 'my-value' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { describe_instances: { reservations: [ instances: [ - { instance_id: "i-abc123-1", state: { name: "running" }, tags: [key: "my-key", value: "my-value"] }, - { instance_id: "i-abc123-2", state: { name: "running" }, tags: [key: "my-key", value: "my-value"] }, - { instance_id: "i-abc123-3", state: { name: "running" }, tags: [key: "my-key", value: "my-value"] } + { instance_id: 'i-abc123-1', state: { name: 'running' }, tags: [key: 'my-key', value: 'my-value'] }, + { instance_id: 'i-abc123-2', state: { name: 'running' }, tags: [key: 'my-key', value: 'my-value'] }, + { instance_id: 'i-abc123-3', state: { name: 'running' }, tags: [key: 'my-key', value: 'my-value'] } ] ] } @@ -23,7 +23,7 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "lists instance IDs and states" do + it 'lists instance IDs and states' do expect { list_instance_ids_states_by_tag(ec2_resource, tag_key, tag_value) }.not_to raise_error end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-key-pairs.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-key-pairs.rb index bec6705c97d..18a8a5ee6e8 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-key-pairs.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-key-pairs.rb @@ -1,17 +1,17 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-key-pairs" +require_relative '../ec2-ruby-example-key-pairs' -describe "#key_pair_created?" do - let(:key_pair_name) { "delete-this-key-pair--only-a-test" } +describe '#key_pair_created?' do + let(:key_pair_name) { 'delete-this-key-pair--only-a-test' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { create_key_pair: { key_name: key_pair_name, - key_fingerprint: "EX:AM:PL:E4:ac:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE", - key_pair_id: "key-08021f7c59EXAMPLE", + key_fingerprint: 'EX:AM:PL:E4:ac:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE', + key_pair_id: 'key-08021f7c59EXAMPLE', key_material: "-----BEGIN RSA PRIVATE KEY-----\n_omitted_for_brevity\n-----END RSA PRIVATE KEY-----" } } @@ -19,24 +19,24 @@ end let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) } - it "creates a key pair" do + it 'creates a key pair' do expect(key_pair_created?(ec2_client, key_pair_name)).to be(true) end end -describe "#describe_key_pairs" do +describe '#describe_key_pairs' do let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { describe_key_pairs: { key_pairs: [ { - key_name: "my-key-pair-1", - key_fingerprint: "EX:AM:PL:E4:ac:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE" + key_name: 'my-key-pair-1', + key_fingerprint: 'EX:AM:PL:E4:ac:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE' }, { - key_name: "my-key-pair-2", - key_fingerprint: "EX:AM:PL:E4:bd:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE" + key_name: 'my-key-pair-2', + key_fingerprint: 'EX:AM:PL:E4:bd:f2:42:71:6d:26:26:8f:31:b7:67:a2:6E:XA:MP:LE' } ] } @@ -44,13 +44,13 @@ ) end - it "lists information about available key pairs" do + it 'lists information about available key pairs' do expect { describe_key_pairs(ec2_client) }.not_to raise_error end end -describe "#key_pair_deleted?" do - let(:key_pair_name) { "my-key-pair" } +describe '#key_pair_deleted?' do + let(:key_pair_name) { 'my-key-pair' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -59,7 +59,7 @@ ) end - it "deletes a key pair" do + it 'deletes a key pair' do expect(key_pair_deleted?(ec2_client, key_pair_name)).to be(true) end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-list-state-instance-i-123abc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-list-state-instance-i-123abc.rb index 93f5ee55b8f..7d9b8dd7007 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-list-state-instance-i-123abc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-list-state-instance-i-123abc.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-list-state-instance-i-123abc" +require_relative '../ec2-ruby-example-list-state-instance-i-123abc' -describe "#list_instance_state" do - let(:instance_id) { "i-123abc" } +describe '#list_instance_state' do + let(:instance_id) { 'i-123abc' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -13,7 +13,7 @@ instances: [ instance_id: instance_id, state: { - name: "running" + name: 'running' } ] ] @@ -22,7 +22,7 @@ ) end - it "displays state information for the instance" do + it 'displays state information for the instance' do expect { list_instance_state(ec2_client, instance_id) }.not_to raise_error end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-manage-instances.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-manage-instances.rb index e807d553be6..3d81ee9d482 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-manage-instances.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-manage-instances.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-manage-instances" +require_relative '../ec2-ruby-example-manage-instances' -describe "#wait_for_instance" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#wait_for_instance' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:instance_state) { :instance_stopped } let(:ec2_client) do Aws::EC2::Client.new( @@ -14,7 +14,7 @@ instances: [ instance_id: instance_id, state: { - name: "stopped" + name: 'stopped' } ] ] @@ -23,13 +23,13 @@ ) end - it "waits for the instance to be in a stopped state" do + it 'waits for the instance to be in a stopped state' do expect { wait_for_instance(ec2_client, instance_state, instance_id) }.not_to raise_error end end -describe "#instance_stopped?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_stopped?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -38,12 +38,12 @@ { current_state: { code: 64, - name: "stopping" + name: 'stopping' }, instance_id: instance_id, previous_state: { code: 16, - name: "running" + name: 'running' } } ] @@ -53,7 +53,7 @@ instances: [ instance_id: instance_id, state: { - name: "stopped" + name: 'stopped' } ] ] @@ -62,13 +62,13 @@ ) end - it "stops an instance" do + it 'stops an instance' do expect(instance_stopped?(ec2_client, instance_id)).to be(true) end end -describe "#instance_restarted?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_restarted?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -77,12 +77,12 @@ { current_state: { code: 0, - name: "pending" + name: 'pending' }, instance_id: instance_id, previous_state: { code: 80, - name: "stopped" + name: 'stopped' } } ] @@ -92,7 +92,7 @@ instances: [ instance_id: instance_id, state: { - name: "running" + name: 'running' } ] ] @@ -101,13 +101,13 @@ ) end - it "restarts an instance" do + it 'restarts an instance' do expect(instance_restarted?(ec2_client, instance_id)).to be(true) end end -describe "#instance_rebooted?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_rebooted?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -116,7 +116,7 @@ instance_statuses: [ { instance_status: { - status: "ok" + status: 'ok' } } ] @@ -125,20 +125,20 @@ ) end - it "reboots an instance" do + it 'reboots an instance' do expect(instance_rebooted?(ec2_client, instance_id)).to be(true) end end -describe "#instance_detailed_monitoring_enabled?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_detailed_monitoring_enabled?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { monitor_instances: { instance_monitorings: [ monitoring: { - state: "enabled" + state: 'enabled' } ] } @@ -146,12 +146,12 @@ ) end - it "checks whether detailed instance monitoring is enabled" do + it 'checks whether detailed instance monitoring is enabled' do expect(instance_detailed_monitoring_enabled?(ec2_client, instance_id)).to be(true) end end -describe "#list_instances_information" do +describe '#list_instances_information' do let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -159,64 +159,64 @@ reservations: [ instances: [ { - instance_id: "i-033c48ef067af3dEX", + instance_id: 'i-033c48ef067af3dEX', state: { - name: "running" + name: 'running' }, - image_id: "ami-0947d2ba12ee1ffEX", - instance_type: "t2.large", - architecture: "x86_64", + image_id: 'ami-0947d2ba12ee1ffEX', + instance_type: 't2.large', + architecture: 'x86_64', iam_instance_profile: { - arn: "arn:aws:iam::111111111111:instance-profile/my-instance-profile" + arn: 'arn:aws:iam::111111111111:instance-profile/my-instance-profile' }, - key_name: "my-key-pair", - launch_time: Time.new(2020, 3, 10, 14, 51, 17, "-08:00"), + key_name: 'my-key-pair', + launch_time: Time.new(2020, 3, 10, 14, 51, 17, '-08:00'), monitoring: { - state: "enabled" + state: 'enabled' }, - public_ip_address: "192.0.2.0", - public_dns_name: "ec2-12-345-67-8EX.compute-1.amazonaws.com", - vpc_id: "vpc-6713dfEX", - subnet_id: "subnet-ecf662EX", + public_ip_address: '192.0.2.0', + public_dns_name: 'ec2-12-345-67-8EX.compute-1.amazonaws.com', + vpc_id: 'vpc-6713dfEX', + subnet_id: 'subnet-ecf662EX', tags: [ { - key: "my-key-1", - value: "my-value-1" + key: 'my-key-1', + value: 'my-value-1' }, { - key: "my-key-2", - value: "my-value-2" + key: 'my-key-2', + value: 'my-value-2' } ] }, { - instance_id: "i-033c48ef067af4dEX", + instance_id: 'i-033c48ef067af4dEX', state: { - name: "running" + name: 'running' }, - image_id: "ami-0947d2ba12ee1ffEX", - instance_type: "m4.large", - architecture: "x86_64", + image_id: 'ami-0947d2ba12ee1ffEX', + instance_type: 'm4.large', + architecture: 'x86_64', iam_instance_profile: { - arn: "arn:aws:iam::111111111111:instance-profile/my-instance-profile" + arn: 'arn:aws:iam::111111111111:instance-profile/my-instance-profile' }, - key_name: "my-key-pair", - launch_time: Time.new(2020, 5, 18, 9, 10, 59, "-08:00"), + key_name: 'my-key-pair', + launch_time: Time.new(2020, 5, 18, 9, 10, 59, '-08:00'), monitoring: { - state: "enabled" + state: 'enabled' }, - public_ip_address: "192.0.2.0", - public_dns_name: "ec2-34-567-89-0EX.compute-1.amazonaws.com", - vpc_id: "vpc-6713dfEX", - subnet_id: "subnet-ecf662EX", + public_ip_address: '192.0.2.0', + public_dns_name: 'ec2-34-567-89-0EX.compute-1.amazonaws.com', + vpc_id: 'vpc-6713dfEX', + subnet_id: 'subnet-ecf662EX', tags: [ { - key: "my-other-key-1", - value: "my-other-value-1" + key: 'my-other-key-1', + value: 'my-other-value-1' }, { - key: "my-other-key-2", - value: "my-other-value-2" + key: 'my-other-key-2', + value: 'my-other-value-2' } ] } @@ -227,7 +227,7 @@ ) end - it "displays instance information" do + it 'displays instance information' do expect { list_instances_information(ec2_client) }.not_to raise_error end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-reboot-instance-i-123abc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-reboot-instance-i-123abc.rb index d30952e0802..21bd2aab9cd 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-reboot-instance-i-123abc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-reboot-instance-i-123abc.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-reboot-instance-i-123abc" +require_relative '../ec2-ruby-example-reboot-instance-i-123abc' -describe "#request_instance_reboot" do - let(:instance_id) { "i-123abc" } +describe '#request_instance_reboot' do + let(:instance_id) { 'i-123abc' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -13,7 +13,7 @@ instances: [ instance_id: instance_id, state: { - name: "running" + name: 'running' } ] ] @@ -23,7 +23,7 @@ ) end - it "sends an instance reboot request" do + it 'sends an instance reboot request' do expect { request_instance_reboot(ec2_client, instance_id) }.not_to raise_error end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-regions-availability-zones.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-regions-availability-zones.rb index 4f6634418ec..cde8b5b80bd 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-regions-availability-zones.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-regions-availability-zones.rb @@ -1,57 +1,57 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-regions-availability-zones" +require_relative '../ec2-ruby-example-regions-availability-zones' -describe "#list_regions_endpoints" do +describe '#list_regions_endpoints' do let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { describe_regions: { regions: [ { - endpoint: "ec2.ap-south-1.amazonaws.com", - region_name: "ap-south-1" + endpoint: 'ec2.ap-south-1.amazonaws.com', + region_name: 'ap-south-1' }, { - endpoint: "ec2.eu-west-1.amazonaws.com", - region_name: "eu-west-1" + endpoint: 'ec2.eu-west-1.amazonaws.com', + region_name: 'eu-west-1' }, { - endpoint: "ec2.ap-southeast-1.amazonaws.com", - region_name: "ap-southeast-1" + endpoint: 'ec2.ap-southeast-1.amazonaws.com', + region_name: 'ap-southeast-1' }, { - endpoint: "ec2.ap-southeast-2.amazonaws.com", - region_name: "ap-southeast-2" + endpoint: 'ec2.ap-southeast-2.amazonaws.com', + region_name: 'ap-southeast-2' }, { - endpoint: "ec2.eu-central-1.amazonaws.com", - region_name: "eu-central-1" + endpoint: 'ec2.eu-central-1.amazonaws.com', + region_name: 'eu-central-1' }, { - endpoint: "ec2.ap-northeast-2.amazonaws.com", - region_name: "ap-northeast-2" + endpoint: 'ec2.ap-northeast-2.amazonaws.com', + region_name: 'ap-northeast-2' }, { - endpoint: "ec2.ap-northeast-1.amazonaws.com", - region_name: "ap-northeast-1" + endpoint: 'ec2.ap-northeast-1.amazonaws.com', + region_name: 'ap-northeast-1' }, { - endpoint: "ec2.us-west-2.amazonaws.com", - region_name: "us-west-2" + endpoint: 'ec2.us-west-2.amazonaws.com', + region_name: 'us-west-2' }, { - endpoint: "ec2.sa-east-1.amazonaws.com", - region_name: "sa-east-1" + endpoint: 'ec2.sa-east-1.amazonaws.com', + region_name: 'sa-east-1' }, { - endpoint: "ec2.us-west-1.amazonaws.com", - region_name: "us-west-1" + endpoint: 'ec2.us-west-1.amazonaws.com', + region_name: 'us-west-1' }, { - endpoint: "ec2.us-west-2.amazonaws.com", - region_name: "us-west-2" + endpoint: 'ec2.us-west-2.amazonaws.com', + region_name: 'us-west-2' } ] } @@ -59,12 +59,12 @@ ) end - it "displays information about regions and endpoints" do + it 'displays information about regions and endpoints' do expect { list_regions_endpoints(ec2_client) }.not_to raise_error end end -describe "#list_availability_zones" do +describe '#list_availability_zones' do let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -72,33 +72,33 @@ availability_zones: [ { messages: [], - region_name: "us-west-2", - state: "available", - zone_name: "us-west-2a" + region_name: 'us-west-2', + state: 'available', + zone_name: 'us-west-2a' }, { messages: [], - region_name: "us-west-2", - state: "available", - zone_name: "us-west-2b" + region_name: 'us-west-2', + state: 'available', + zone_name: 'us-west-2b' }, { messages: [], - region_name: "us-west-2", - state: "available", - zone_name: "us-west-2c" + region_name: 'us-west-2', + state: 'available', + zone_name: 'us-west-2c' }, { messages: [], - region_name: "us-west-2", - state: "available", - zone_name: "us-west-2d", + region_name: 'us-west-2', + state: 'available', + zone_name: 'us-west-2d' }, { messages: [], - region_name: "us-west-2", - state: "available", - zone_name: "us-west-2e" + region_name: 'us-west-2', + state: 'available', + zone_name: 'us-west-2e' } ] } @@ -106,7 +106,7 @@ ) end - it "displays information about availability zones" do + it 'displays information about availability zones' do expect { list_availability_zones(ec2_client) }.not_to raise_error end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-security-group.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-security-group.rb index 73f1b049d6d..9071d84ed9a 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-security-group.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-security-group.rb @@ -1,13 +1,13 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-security-group" +require_relative '../ec2-ruby-example-security-group' -describe "#create_security_group" do - let(:group_name) { "my-security-group" } - let(:description) { "This is my security group." } - let(:vpc_id) { "vpc-6713dfEX" } - let(:group_id) { "sg-0050f059851d102EX" } +describe '#create_security_group' do + let(:group_name) { 'my-security-group' } + let(:description) { 'This is my security group.' } + let(:vpc_id) { 'vpc-6713dfEX' } + let(:group_id) { 'sg-0050f059851d102EX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -18,7 +18,7 @@ ) end - it "creates a security group" do + it 'creates a security group' do expect( create_security_group( ec2_client, @@ -30,12 +30,12 @@ end end -describe "#security_group_ingress_authorized?" do - let(:security_group_id) { "sg-0050f059851d102EX" } - let(:ip_protocol) { "tcp" } - let(:from_port) { "22" } - let(:to_port) { "22" } - let(:cidr_ip_range) { "0.0.0.0/0" } +describe '#security_group_ingress_authorized?' do + let(:security_group_id) { 'sg-0050f059851d102EX' } + let(:ip_protocol) { 'tcp' } + let(:from_port) { '22' } + let(:to_port) { '22' } + let(:cidr_ip_range) { '0.0.0.0/0' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -44,7 +44,7 @@ ) end - it "adds an inbound rule to a security group" do + it 'adds an inbound rule to a security group' do expect( security_group_ingress_authorized?( ec2_client, @@ -58,44 +58,44 @@ end end -describe "#describe_security_groups" do +describe '#describe_security_groups' do let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { describe_security_groups: { security_groups: [ { - group_name: "launch-wizard-1", - description: "launch-wizard-1 created", - group_id: "sg-03d327b2d28d827EX", - owner_id: "111111111111", - vpc_id: "vpc-6713dfEX", + group_name: 'launch-wizard-1', + description: 'launch-wizard-1 created', + group_id: 'sg-03d327b2d28d827EX', + owner_id: '111111111111', + vpc_id: 'vpc-6713dfEX', tags: [ { - key: "my-key", - value: "my-value" + key: 'my-key', + value: 'my-value' } ], ip_permissions: [ { - ip_protocol: "tcp", + ip_protocol: 'tcp', from_port: 22, to_port: 22, ip_ranges: [ { - cidr_ip: "0.0.0.0/0" + cidr_ip: '0.0.0.0/0' } ] } ], ip_permissions_egress: [ { - ip_protocol: "-1", + ip_protocol: '-1', from_port: -1, to_port: -1, ip_ranges: [ { - cidr_ip: "0.0.0.0/0" + cidr_ip: '0.0.0.0/0' } ] } @@ -107,13 +107,13 @@ ) end - it "displays information about available security groups" do + it 'displays information about available security groups' do expect { describe_security_groups(ec2_client) }.not_to raise_error end end -describe "#security_group_deleted?" do - let(:security_group_id) { "sg-0050f059851d102EX" } +describe '#security_group_deleted?' do + let(:security_group_id) { 'sg-0050f059851d102EX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -122,7 +122,7 @@ ) end - it "deletes a security group" do + it 'deletes a security group' do expect(security_group_deleted?(ec2_client, security_group_id)).to be(true) end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-start-instance-i-123abc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-start-instance-i-123abc.rb index b25c4c4672d..cb36456dde7 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-start-instance-i-123abc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-start-instance-i-123abc.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-start-instance-i-123abc" +require_relative '../ec2-ruby-example-start-instance-i-123abc' -describe "#instance_started?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_started?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -12,7 +12,7 @@ instance_statuses: [ { instance_state: { - name: "stopped" + name: 'stopped' } } ] @@ -22,12 +22,12 @@ { current_state: { code: 16, - name: "running" + name: 'running' }, instance_id: instance_id, previous_state: { code: 80, - name: "stopped" + name: 'stopped' } } ] @@ -38,7 +38,7 @@ instance_id: instance_id, state: { code: 16, - name: "running" + name: 'running' } ] ] @@ -47,7 +47,7 @@ ) end - it "starts an instance" do + it 'starts an instance' do expect(instance_started?(ec2_client, instance_id)).to be(true) end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-stop-instance-i-123abc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-stop-instance-i-123abc.rb index 0cbfa6d77e4..830fa576860 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-stop-instance-i-123abc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-stop-instance-i-123abc.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-stop-instance-i-123abc" +require_relative '../ec2-ruby-example-stop-instance-i-123abc' -describe "#instance_stopped?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_stopped?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -12,7 +12,7 @@ instance_statuses: [ { instance_state: { - name: "running" + name: 'running' } } ] @@ -22,12 +22,12 @@ { current_state: { code: 80, - name: "stopped" + name: 'stopped' }, instance_id: instance_id, previous_state: { code: 16, - name: "running" + name: 'running' } } ] @@ -38,7 +38,7 @@ instance_id: instance_id, state: { code: 80, - name: "stopped" + name: 'stopped' } ] ] @@ -47,7 +47,7 @@ ) end - it "stops an instance" do + it 'stops an instance' do expect(instance_stopped?(ec2_client, instance_id)).to be(true) end end diff --git a/ruby/example_code/ec2/tests/test_ec2-ruby-example-terminate-instance-i-123abc.rb b/ruby/example_code/ec2/tests/test_ec2-ruby-example-terminate-instance-i-123abc.rb index 0fc14932324..cf7d031f40b 100644 --- a/ruby/example_code/ec2/tests/test_ec2-ruby-example-terminate-instance-i-123abc.rb +++ b/ruby/example_code/ec2/tests/test_ec2-ruby-example-terminate-instance-i-123abc.rb @@ -1,10 +1,10 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../ec2-ruby-example-terminate-instance-i-123abc" +require_relative '../ec2-ruby-example-terminate-instance-i-123abc' -describe "#instance_terminated?" do - let(:instance_id) { "i-033c48ef067af3dEX" } +describe '#instance_terminated?' do + let(:instance_id) { 'i-033c48ef067af3dEX' } let(:ec2_client) do Aws::EC2::Client.new( stub_responses: { @@ -12,7 +12,7 @@ instance_statuses: [ { instance_state: { - name: "running" + name: 'running' } } ] @@ -22,12 +22,12 @@ { current_state: { code: 48, - name: "terminated" + name: 'terminated' }, instance_id: instance_id, previous_state: { code: 16, - name: "running" + name: 'running' } } ] @@ -38,7 +38,7 @@ instance_id: instance_id, state: { code: 48, - name: "terminated" + name: 'terminated' } ] ] @@ -47,7 +47,7 @@ ) end - it "terminates an instance" do + it 'terminates an instance' do expect(instance_terminated?(ec2_client, instance_id)).to be(true) end end diff --git a/ruby/example_code/elasticbeanstalk/list_apps.rb b/ruby/example_code/elasticbeanstalk/list_apps.rb index 77f8b4c97f8..746b7dab806 100644 --- a/ruby/example_code/elasticbeanstalk/list_apps.rb +++ b/ruby/example_code/elasticbeanstalk/list_apps.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-elasticbeanstalk" -require "logger" +require 'aws-sdk-elasticbeanstalk' +require 'logger' # snippet-start:[eb.Ruby.listApps] # Class to manage Elastic Beanstalk applications diff --git a/ruby/example_code/elasticbeanstalk/list_stacks.rb b/ruby/example_code/elasticbeanstalk/list_stacks.rb index 76ffb7c787a..1dddf4093ad 100644 --- a/ruby/example_code/elasticbeanstalk/list_stacks.rb +++ b/ruby/example_code/elasticbeanstalk/list_stacks.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-elasticbeanstalk" -require "logger" +require 'aws-sdk-elasticbeanstalk' +require 'logger' # snippet-start:[eb.Ruby.listStacks] # Manages listing of AWS Elastic Beanstalk solution stacks @@ -50,6 +50,6 @@ def log_summary(filtered_length, orig_length) # Example usage: if $PROGRAM_NAME == __FILE__ eb_client = Aws::ElasticBeanstalk::Client.new - stack_lister = StackLister.new(eb_client, "java") + stack_lister = StackLister.new(eb_client, 'java') stack_lister.list_stacks end diff --git a/ruby/example_code/elasticbeanstalk/spec/list_apps_spec.rb b/ruby/example_code/elasticbeanstalk/spec/list_apps_spec.rb index 0ba8c628b04..4748056d31a 100644 --- a/ruby/example_code/elasticbeanstalk/spec/list_apps_spec.rb +++ b/ruby/example_code/elasticbeanstalk/spec/list_apps_spec.rb @@ -1,14 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../list_apps" +require 'rspec' +require_relative '../list_apps' describe ElasticBeanstalkManager do let(:eb_client) { Aws::ElasticBeanstalk::Client.new } let(:eb_manager) { ElasticBeanstalkManager.new(eb_client) } - describe "#list_applications" do - it "logs application and environment details without error" do + describe '#list_applications' do + it 'logs application and environment details without error' do expect { eb_manager.list_applications }.not_to raise_error end end diff --git a/ruby/example_code/elasticbeanstalk/spec/list_stacks_spec.rb b/ruby/example_code/elasticbeanstalk/spec/list_stacks_spec.rb index 26dd7ab2ab3..5cce495ae9d 100644 --- a/ruby/example_code/elasticbeanstalk/spec/list_stacks_spec.rb +++ b/ruby/example_code/elasticbeanstalk/spec/list_stacks_spec.rb @@ -1,18 +1,18 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../list_stacks" +require 'rspec' +require_relative '../list_stacks' describe StackLister do let(:eb_client) { Aws::ElasticBeanstalk::Client.new } - let(:stack_lister) { StackLister.new(eb_client, "java") } + let(:stack_lister) { StackLister.new(eb_client, 'java') } - describe "#list_stacks" do - it "successfully lists available solution stacks" do + describe '#list_stacks' do + it 'successfully lists available solution stacks' do expect { stack_lister.list_stacks }.not_to raise_error end - it "logs at least one stack" do + it 'logs at least one stack' do expect_any_instance_of(Logger).to receive(:info).at_least(:once) stack_lister.list_stacks end diff --git a/ruby/example_code/elasticbeanstalk/spec/update_app_spec.rb b/ruby/example_code/elasticbeanstalk/spec/update_app_spec.rb index cab1409e332..7ed9108f762 100644 --- a/ruby/example_code/elasticbeanstalk/spec/update_app_spec.rb +++ b/ruby/example_code/elasticbeanstalk/spec/update_app_spec.rb @@ -1,15 +1,15 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../update_app" -require "rspec" +require_relative '../update_app' +require 'rspec' describe RailsAppDeployer do let(:eb_client) { Aws::ElasticBeanstalk::Client.new } let(:s3_client) { Aws::S3::Client.new } - let(:app_deployer) { RailsAppDeployer.new(eb_client, s3_client, "MyRailsApp") } + let(:app_deployer) { RailsAppDeployer.new(eb_client, s3_client, 'MyRailsApp') } - describe "#deploy" do - it "successfully deploys the application" do + describe '#deploy' do + it 'successfully deploys the application' do expect { app_deployer.deploy }.not_to raise_error end end diff --git a/ruby/example_code/elasticbeanstalk/update_app.rb b/ruby/example_code/elasticbeanstalk/update_app.rb index 7a3e3a471a4..5823f48116a 100644 --- a/ruby/example_code/elasticbeanstalk/update_app.rb +++ b/ruby/example_code/elasticbeanstalk/update_app.rb @@ -1,9 +1,9 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-elasticbeanstalk" -require "aws-sdk-s3" -require "securerandom" -require "logger" +require 'aws-sdk-elasticbeanstalk' +require 'aws-sdk-s3' +require 'securerandom' +require 'logger' # snippet-start:[eb.Ruby.updateMyRailsApp] # Manages deployment of Rails applications to AWS Elastic Beanstalk @@ -62,7 +62,7 @@ def fetch_bucket_name # Creates a new application version and deploys it def create_and_deploy_new_application_version(zip_file_name) - version_label = File.basename(zip_file_name, ".zip") + version_label = File.basename(zip_file_name, '.zip') @eb_client.create_application_version( process: false, application_name: @app_name, @@ -104,6 +104,6 @@ def fetch_environment_name if $PROGRAM_NAME == __FILE__ eb_client = Aws::ElasticBeanstalk::Client.new s3_client = Aws::S3::Client.new - app_deployer = RailsAppDeployer.new(eb_client, s3_client, "MyRailsApp") + app_deployer = RailsAppDeployer.new(eb_client, s3_client, 'MyRailsApp') app_deployer.deploy end diff --git a/ruby/example_code/elastictranscoder/create_job.rb b/ruby/example_code/elastictranscoder/create_job.rb index e415a6732cb..4ebec971af1 100644 --- a/ruby/example_code/elastictranscoder/create_job.rb +++ b/ruby/example_code/elastictranscoder/create_job.rb @@ -5,8 +5,8 @@ # Demonstrates how to create an HLS job using the AWS SDK for Ruby. # snippet-start:[elastictranscoder.ruby.create_hls_job.import] -require "aws-sdk-elastictranscoder" -require "aws-sdk-s3" +require 'aws-sdk-elastictranscoder' +require 'aws-sdk-s3' def create_elastictranscoder_job(transcoder_client, s3_resource, pipeline_name) bucket_name = "transcoder-bucket-#{rand(10**4)}" @@ -16,86 +16,85 @@ def create_elastictranscoder_job(transcoder_client, s3_resource, pipeline_name) name: pipeline_name, # required input_bucket: bucket_name, # required output_bucket: bucket_name, - role: "arn:aws:iam::260778392212:role/Elastic_Transcoder_Default_Role" # required + role: 'arn:aws:iam::260778392212:role/Elastic_Transcoder_Default_Role' # required }) - pipeline_id = resp["pipeline"]["id"] + pipeline_id = resp['pipeline']['id'] # This is the name of the input key that you would like to transcode. - input_key = ".Jabberwocky.mp3" + input_key = '.Jabberwocky.mp3' # HLS Presets that will be used to create an adaptive bitrate playlist. - hls_64k_audio_preset_id = "1351620000001-200071" - hls_0400k_preset_id = "1351620000001-200050" - hls_0600k_preset_id = "1351620000001-200040" - hls_1000k_preset_id = "1351620000001-200030" - hls_1500k_preset_id = "1351620000001-200020" - hls_2000k_preset_id = "1351620000001-200010" + hls_64k_audio_preset_id = '1351620000001-200071' + hls_0400k_preset_id = '1351620000001-200050' + hls_0600k_preset_id = '1351620000001-200040' + hls_1000k_preset_id = '1351620000001-200030' + hls_1500k_preset_id = '1351620000001-200020' + hls_2000k_preset_id = '1351620000001-200010' # Additional variables - segment_duration = "2" - output_key_prefix = "elastic-transcoder-samples/output/hls/" + segment_duration = '2' + output_key_prefix = 'elastic-transcoder-samples/output/hls/' input = { key: input_key } - output_key = OpenSSL::Digest::SHA256.new(input_key.encode("UTF-8")).to_s - + output_key = OpenSSL::Digest::SHA256.new(input_key.encode('UTF-8')).to_s hls_audio = { - key: "hlsAudio/" + output_key, + key: "hlsAudio/#{output_key}", preset_id: hls_64k_audio_preset_id, segment_duration: segment_duration } hls_400k = { - key: "hls0400k/" + output_key, + key: "hls0400k/#{output_key}", preset_id: hls_0400k_preset_id, segment_duration: segment_duration } hls_600k = { - key: "hls0600k/" + output_key, + key: "hls0600k/#{output_key}", preset_id: hls_0600k_preset_id, segment_duration: segment_duration } hls_1000k = { - key: "hls1000k/" + output_key, + key: "hls1000k/#{output_key}", preset_id: hls_1000k_preset_id, segment_duration: segment_duration } hls_1500k = { - key: "hls1500k/" + output_key, + key: "hls1500k/#{output_key}", preset_id: hls_1500k_preset_id, segment_duration: segment_duration } hls_2000k = { - key: "hls2000k/" + output_key, + key: "hls2000k/#{output_key}", preset_id: hls_2000k_preset_id, segment_duration: segment_duration } outputs = [hls_audio, hls_400k, hls_600k, hls_1000k, hls_1500k, hls_2000k] playlist = { - name: "hls_" + output_key, - format: "HLSv3", + name: "hls_#{output_key}", + format: 'HLSv3', output_keys: outputs.map { |output| output[:key] } } job = transcoder_client.create_job( pipeline_id: pipeline_id, input: input, - output_key_prefix: output_key_prefix + output_key + "/", + output_key_prefix: "#{output_key_prefix}#{output_key}/", outputs: outputs, playlists: [playlist] )[:job] - puts "HLS job has been created: " + JSON.pretty_generate(job) + puts "HLS job has been created: #{JSON.pretty_generate(job)}" end # snippet-end:[elastictranscoder.ruby.create_hls_job.import] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME transcoder_client = Aws::ElasticTranscoder::Client.new s3_resource = Aws::S3::Resource.new pipeline_name = "transcoder-pipeline-#{rand(10**4)}" diff --git a/ruby/example_code/elastictranscoder/create_job_status_notification.rb b/ruby/example_code/elastictranscoder/create_job_status_notification.rb index 7b82cf7688e..df7ffabe054 100644 --- a/ruby/example_code/elastictranscoder/create_job_status_notification.rb +++ b/ruby/example_code/elastictranscoder/create_job_status_notification.rb @@ -5,13 +5,12 @@ # create_job_status_notification.rb demonstrates how to create a notification handler for an # Amazon Elastic Transcoder job using the AWS SDK for Ruby. - # snippet-start:[elastictranscoder.ruby.create_job_status_notification.import] -require "aws-sdk-elastictranscoder" -require "openssl" -require_relative "sqs_queue_notification_worker" -require "aws-sdk-s3" -require "aws-sdk-sqs" +require 'aws-sdk-elastictranscoder' +require 'openssl' +require_relative 'sqs_queue_notification_worker' +require 'aws-sdk-s3' +require 'aws-sdk-sqs' # set clients required transcoder_client = Aws::ElasticTranscoder::Client.new @@ -23,27 +22,26 @@ bucket_name = "transcoder-bucket-#{rand(10**4)}" sqs_queue_name = "transcoder-sqs-#{rand(10**4)}" - s3_resource.create_bucket(bucket: bucket_name) -resp = sqs_client.create_queue({queue_name: sqs_queue_name}) +resp = sqs_client.create_queue({ queue_name: sqs_queue_name }) sqs_queue_url = resp.queue_url resp = transcoder_client.create_pipeline({ name: transcoder_pipeline, # required input_bucket: bucket_name, # required output_bucket: bucket_name, - role: "arn:aws:iam::260778392212:role/Elastic_Transcoder_Default_Role" # required + role: 'arn:aws:iam::260778392212:role/Elastic_Transcoder_Default_Role' # required }) -pipeline_id = resp["pipeline"]["id"] +pipeline_id = resp['pipeline']['id'] -input_key = ".Jabberwocky.mp3" +input_key = '.Jabberwocky.mp3' # This will generate a 480p 16:9 mp4 output. -preset_id = "1351620000001-000020" +preset_id = '1351620000001-000020' # All outputs will have this prefix prepended to their output key. -output_key_prefix = "elastic-transcoder-samples/output/" +output_key_prefix = 'elastic-transcoder-samples/output/' def create_elastic_transcoder_job(pipeline_id, input_key, preset_id, output_key_prefix) # Create the client for Elastic Transcoder. @@ -54,7 +52,7 @@ def create_elastic_transcoder_job(pipeline_id, input_key, preset_id, output_key_ # Setup the job input using the provided input key. output = { - key: OpenSSL::Digest::SHA256.new(input_key.encode("UTF-8")).to_s, + key: OpenSSL::Digest::SHA256.new(input_key.encode('UTF-8')).to_s, preset_id: preset_id } @@ -68,12 +66,14 @@ def create_elastic_transcoder_job(pipeline_id, input_key, preset_id, output_key_ end job_id = create_elastic_transcoder_job(pipeline_id, input_key, preset_id, output_key_prefix) -puts "Waiting for job to complete: " + job_id +puts "Waiting for job to complete: #{job_id}" # Create SQS notification worker which polls for notifications. Register a # handler which will stop the worker when the job we just created completes. notification_worker = SqsQueueNotificationWorker.new(sqs_queue_url) -completion_handler = lambda { |notification| notification_worker.stop if (notification["jobId"] == job_id && ["COMPLETED", "ERROR"].include?(notification["state"])) } +completion_handler = lambda { |notification| + notification_worker.stop if notification['jobId'] == job_id && %w[COMPLETED ERROR].include?(notification['state']) +} notification_worker.add_handler(completion_handler) notification_worker.start # snippet-end:[elastictranscoder.ruby.create_job_status_notification.import] diff --git a/ruby/example_code/elastictranscoder/specs/elastictranscoder_spec.rb b/ruby/example_code/elastictranscoder/specs/elastictranscoder_spec.rb index ca9936cb779..8fd49878dba 100644 --- a/ruby/example_code/elastictranscoder/specs/elastictranscoder_spec.rb +++ b/ruby/example_code/elastictranscoder/specs/elastictranscoder_spec.rb @@ -3,16 +3,15 @@ # frozen_string_literal: true -require_relative "../create_job" -require "rspec" +require_relative '../create_job' +require 'rspec' -describe "TestElastictranscoder" do +describe 'TestElastictranscoder' do let(:transcoder_client) { Aws::ElasticTranscoder::Client.new } let(:s3_resource) { Aws::S3::Resource.new } let(:pipeline_name) { "transcoder-pipeline-#{rand(10**4)}" } - it "create" do + it 'create' do create_elastictranscoder_job(transcoder_client, s3_resource, pipeline_name) end - end diff --git a/ruby/example_code/elastictranscoder/sqs_queue_notification_worker.rb b/ruby/example_code/elastictranscoder/sqs_queue_notification_worker.rb index 114ebb6bda5..94ab13b96c5 100644 --- a/ruby/example_code/elastictranscoder/sqs_queue_notification_worker.rb +++ b/ruby/example_code/elastictranscoder/sqs_queue_notification_worker.rb @@ -6,8 +6,8 @@ # for an Amazon Elastic Transcoder job using the AWS SDK for Ruby. # snippet-start:[elastictranscoder.ruby.create_sqs_notification_queue.import] -require "aws-sdk-elastictranscoder" -require "aws-sdk-sqs" +require 'aws-sdk-elastictranscoder' +require 'aws-sdk-sqs' # Class which will poll SQS for job state notifications in a separate thread. # This class is intended for batch-processing. If you are using a ruby-on-rails @@ -52,7 +52,7 @@ def poll_and_handle_messages next if sqs_messages.nil? sqs_messages.each do |sqs_message| - notification = JSON.parse(JSON.parse(sqs_message[:body])["Message"]) + notification = JSON.parse(JSON.parse(sqs_message[:body])['Message']) @handlers.each do |handler| handler.call(notification) sqs_client.delete_message(queue_url: @queue_url, receipt_handle: sqs_message[:receipt_handle]) diff --git a/ruby/example_code/eventbridge/cw-ruby-example-send-events-ec2.rb b/ruby/example_code/eventbridge/cw-ruby-example-send-events-ec2.rb index e98977ea193..bd2788356c5 100644 --- a/ruby/example_code/eventbridge/cw-ruby-example-send-events-ec2.rb +++ b/ruby/example_code/eventbridge/cw-ruby-example-send-events-ec2.rb @@ -29,15 +29,17 @@ # The run_me function toward the end of this code example calls the # functions in the correct order. + # snippet-start:[cloudwatch.cross-service.Ruby.require] -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" +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' # snippet-end:[cloudwatch.cross-service.Ruby.require] + # snippet-start:[cloudwatch.cross-service.Ruby.sns] # Checks whether the specified Amazon SNS # topic exists among those provided to this function. @@ -55,14 +57,14 @@ # ) # puts 'Topic found.' # end - def topic_found?(topics, topic_arn) topics.each do |topic| return true if topic.topic_arn == topic_arn end - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.sns] + # snippet-start:[cloudwatch.cross-service.Ruby.snstopic] # Checks whether the specified topic exists among those available to the # caller in Amazon SNS. @@ -80,26 +82,27 @@ def topic_exists?(sns_client, topic_arn) response = sns_client.list_topics if response.topics.count.positive? if topic_found?(response.topics, topic_arn) - puts "Topic found." + puts 'Topic found.' return true end - while response.next_page? do + while response.next_page? response = response.next_page - if response.topics.count.positive? - if topic_found?(response.topics, topic_arn) - puts "Topic found." - return true - end + 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." - return false + puts 'Topic not found.' + false rescue StandardError => e puts "Topic not found: #{e.message}" - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.snstopic] + # snippet-start:[cloudwatch.cross-service.Ruby.createSnsTopic] # Creates a topic in Amazon SNS # and then subscribes an email address to receive notifications to that topic. @@ -120,20 +123,21 @@ def create_topic(sns_client, topic_name, email_address) puts "Topic created with ARN '#{topic_response.topic_arn}'." subscription_response = sns_client.subscribe( topic_arn: topic_response.topic_arn, - protocol: "email", + protocol: 'email', endpoint: email_address, return_subscription_arn: true ) - puts "Subscription created with ARN " \ + 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." - return topic_response.topic_arn + '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}" - return "Error" + 'Error' end # snippet-end:[cloudwatch.cross-service.Ruby.createSnsTopic] + # snippet-start:[cloudwatch.cross-service.Ruby.IamRole] # Checks whether the specified AWS Identity and Access Management (IAM) # role exists among those provided to this function. @@ -155,9 +159,10 @@ def role_found?(roles, role_arn) roles.each do |role| return true if role.arn == role_arn end - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.IamRole] + # snippet-start:[cloudwatch.cross-service.Ruby.checkIamRole] # Checks whether the specified role exists among those available to the # caller in AWS Identity and Access Management (IAM). @@ -175,26 +180,27 @@ def role_exists?(iam_client, role_arn) response = iam_client.list_roles if response.roles.count.positive? if role_found?(response.roles, role_arn) - puts "Role found." + puts 'Role found.' return true end - while response.next_page? do + while response.next_page? response = response.next_page - if response.roles.count.positive? - if role_found?(response.roles, role_arn) - puts "Role found." - return true - end + 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." - return false + puts 'Role not found.' + false rescue StandardError => e puts "Role not found: #{e.message}" - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.checkIamRole] + # snippet-start:[cloudwatch.cross-service.Ruby.createIamRole] # Creates a role in AWS Identity and Access Management (IAM). # This role is used by a rule in Amazon EventBridge to allow @@ -213,53 +219,54 @@ 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", + 'Version': '2012-10-17', 'Statement': [ { - 'Sid': "", - 'Effect': "Allow", + 'Sid': '', + 'Effect': 'Allow', 'Principal': { - 'Service': "events.amazonaws.com" + 'Service': 'events.amazonaws.com' }, - 'Action': "sts:AssumeRole" + 'Action': 'sts:AssumeRole' } ] }.to_json, - path: "/", + path: '/', role_name: role_name ) puts "Role created with ARN '#{response.role.arn}'." - puts "Adding access policy to role..." + puts 'Adding access policy to role...' iam_client.put_role_policy( policy_document: { - 'Version': "2012-10-17", + 'Version': '2012-10-17', 'Statement': [ { - 'Sid': "CloudWatchEventsFullAccess", - 'Effect': "Allow", - 'Resource': "*", - 'Action': "events:*" + 'Sid': 'CloudWatchEventsFullAccess', + 'Effect': 'Allow', + 'Resource': '*', + 'Action': 'events:*' }, { - 'Sid': "IAMPassRoleForCloudWatchEvents", - 'Effect': "Allow", - 'Resource': "arn:aws:iam::*:role/AWS_Events_Invoke_Targets", - 'Action': "iam:PassRole" + 'Sid': 'IAMPassRoleForCloudWatchEvents', + 'Effect': 'Allow', + 'Resource': 'arn:aws:iam::*:role/AWS_Events_Invoke_Targets', + 'Action': 'iam:PassRole' } ] }.to_json, - policy_name: "CloudWatchEventsPolicy", + policy_name: 'CloudWatchEventsPolicy', role_name: role_name ) - puts "Access policy added to role." - return response.role.arn + 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." - return "Error" + 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 # snippet-end:[cloudwatch.cross-service.Ruby.createIamRole] + # snippet-start:[cloudwatch.cross-service.Ruby.checkRuleExists] # Checks whether the specified Amazon EventBridge rule exists among # those provided to this function. @@ -278,9 +285,10 @@ def rule_found?(rules, rule_name) rules.each do |rule| return true if rule.name == rule_name end - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.checkRuleExists] + # snippet-start:[cloudwatch.cross-service.Ruby.checkRuleAvailable] # Checks whether the specified rule exists among those available to the # caller in Amazon EventBridge. @@ -299,26 +307,27 @@ def rule_exists?(cloudwatchevents_client, rule_name) response = cloudwatchevents_client.list_rules if response.rules.count.positive? if rule_found?(response.rules, rule_name) - puts "Rule found." + puts 'Rule found.' return true end - while response.next_page? do + while response.next_page? response = response.next_page - if response.rules.count.positive? - if rule_found?(response.rules, rule_name) - puts "Rule found." - return true - end + 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." - return false + puts 'Rule not found.' + false rescue StandardError => e puts "Rule not found: #{e.message}" - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.checkRuleAvailable] + # snippet-start:[cloudwatch.cross-service.Ruby.createRule] # Creates a rule in Amazon EventBridge. # This rule is triggered whenever an available instance in @@ -367,10 +376,10 @@ def rule_created?( description: rule_description, event_pattern: { 'source': [ - "aws.ec2" + 'aws.ec2' ], 'detail-type': [ - "EC2 Instance State-change Notification" + 'EC2 Instance State-change Notification' ], 'detail': { 'state': [ @@ -378,7 +387,7 @@ def rule_created?( ] } }.to_json, - state: "ENABLED", + state: 'ENABLED', role_arn: role_arn ) puts "Rule created with ARN '#{put_rule_response.rule_arn}'." @@ -393,22 +402,23 @@ def rule_created?( ] ) if put_targets_response.key?(:failed_entry_count) && - put_targets_response.failed_entry_count > 0 - puts "Error(s) adding target to rule:" + 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 - return false + false else - return true + 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." - return false + 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 # snippet-end:[cloudwatch.cross-service.Ruby.createRule] + # snippet-start:[cloudwatch.cross-service.Ruby.checkLogGroup] # Checks to see whether the specified log group exists among those available # to the caller in Amazon CloudWatch Logs. @@ -430,18 +440,19 @@ def log_group_exists?(cloudwatchlogs_client, 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." + puts 'Log group found.' return true end end end - puts "Log group not found." - return false + puts 'Log group not found.' + false rescue StandardError => e puts "Log group not found: #{e.message}" - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.checkLogGroup] + # snippet-start:[cloudwatch.cross-service.Ruby.createLogGroup] # Creates a log group in Amazon CloudWatch Logs. # @@ -457,13 +468,14 @@ def log_group_exists?(cloudwatchlogs_client, log_group_name) 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." - return true + puts 'Log group created.' + true rescue StandardError => e puts "Error creating log group: #{e.message}" - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.createLogGroup] + # snippet-start:[cloudwatch.cross-service.Ruby.writeEvent] # Writes an event to a log stream in Amazon CloudWatch Logs. # @@ -511,19 +523,17 @@ def log_event( } ] } - unless sequence_token.empty? - event[:sequence_token] = sequence_token - end + event[:sequence_token] = sequence_token unless sequence_token.empty? response = cloudwatchlogs_client.put_log_events(event) - puts "Message logged." - return response.next_sequence_token + puts 'Message logged.' + response.next_sequence_token rescue StandardError => e puts "Message not logged: #{e.message}" end # snippet-end:[cloudwatch.cross-service.Ruby.writeEvent] -# snippet-start:[cloudwatch.cross-service.Ruby.restartInstance] +# snippet-start:[cloudwatch.cross-service.Ruby.restartInstance] # Restarts an Amazon EC2 instance # and adds information about the related activity to a log stream # in Amazon CloudWatch Logs. @@ -560,13 +570,13 @@ def instance_restarted?( log_group_name: log_group_name, log_stream_name: log_stream_name ) - sequence_token = "" + sequence_token = '' puts "Attempting to stop the instance with the ID '#{instance_id}'. " \ - "This might take a few minutes..." + '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." + puts 'Instance stopped.' sequence_token = log_event( cloudwatchlogs_client, log_group_name, @@ -575,10 +585,10 @@ def instance_restarted?( sequence_token ) - puts "Attempting to restart the instance. This might take a few minutes..." + 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." + puts 'Instance restarted.' sequence_token = log_event( cloudwatchlogs_client, log_group_name, @@ -587,9 +597,9 @@ def instance_restarted?( sequence_token ) - return true + true rescue StandardError => e - puts "Error creating log stream or stopping or restarting the instance: " \ + puts 'Error creating log stream or stopping or restarting the instance: ' \ "#{e.message}" log_event( cloudwatchlogs_client, @@ -598,9 +608,10 @@ def instance_restarted?( "Error stopping or starting instance '#{instance_id}': #{e.message}", sequence_token ) - return false + false end # snippet-end:[cloudwatch.cross-service.Ruby.restartInstance] + # snippet-start:[cloudwatch.cross-service.Ruby.displayInfo] # Displays information about activity for a rule in Amazon EventBridge. # @@ -631,21 +642,21 @@ def display_rule_activity( end_time, period ) - puts "Attempting to display rule activity..." + puts 'Attempting to display rule activity...' response = cloudwatch_client.get_metric_statistics( - namespace: "AWS/Events", - metric_name: "Invocations", + namespace: 'AWS/Events', + metric_name: 'Invocations', dimensions: [ { - name: "RuleName", + name: 'RuleName', value: rule_name } ], start_time: start_time, end_time: end_time, period: period, - statistics: ["Sum"], - unit: "Count" + statistics: ['Sum'], + unit: 'Count' ) if response.key?(:datapoints) && response.datapoints.count.positive? @@ -655,12 +666,13 @@ def display_rule_activity( end else puts "The event rule '#{rule_name}' was not triggered during the " \ - "specified time period." + 'specified time period.' end rescue StandardError => e puts "Error getting information about event rule activity: #{e.message}" end # snippet-end:[cloudwatch.cross-service.Ruby.displayInfo] + # snippet-start:[cloudwatch.cross-service.Ruby.displayLogInfo] # Displays log information for all of the log streams in a log group in # Amazon CloudWatch Logs. @@ -678,39 +690,39 @@ def display_rule_activity( # '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 " \ + 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", + 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.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) + 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.count.positive? get_log_events_response.events.each do |event| puts event.message end else - puts "No log messages for this log stream." + 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: " \ + puts 'Error getting information about the log streams or their messages: ' \ "#{e.message}" end # snippet-end:[cloudwatch.cross-service.Ruby.displayLogInfo] -# snippet-start:[cloudwatch.cross-service.Ruby.displayReminder] +# snippet-start:[cloudwatch.cross-service.Ruby.displayReminder] # Displays a reminder to the caller to manually clean up any associated # AWS resources that they no longer need. # @@ -730,41 +742,42 @@ def display_log_data(cloudwatchlogs_client, log_group_name) 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 '-' * 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 +# snippet-end:[cloudwatch.cross-service.Ruby.displayReminder] # Example usage: def run_me # Properties for the Amazon SNS topic. - topic_name = "aws-doc-sdk-examples-topic" - email_address = "mary@example.com" + topic_name = 'aws-doc-sdk-examples-topic' + email_address = 'mary@example.com' # Properties for the IAM role. - role_name = "aws-doc-sdk-examples-cloudwatch-events-rule-role" + role_name = 'aws-doc-sdk-examples-cloudwatch-events-rule-role' # Properties for the Amazon EventBridge rule. - rule_name = "aws-doc-sdk-examples-ec2-state-change" - rule_description = "Triggers when any available EC2 instance starts." - instance_state = "running" - target_id = "sns-topic" + rule_name = 'aws-doc-sdk-examples-ec2-state-change' + rule_description = 'Triggers when any available EC2 instance starts.' + instance_state = 'running' + target_id = 'sns-topic' # Properties for the Amazon EC2 instance. - instance_id = "i-033c48ef067af3dEX" + instance_id = 'i-033c48ef067af3dEX' # Properties for displaying the event rule's activity. start_time = Time.now - 600 # Go back over the past 10 minutes - # (10 minutes * 60 seconds = 600 seconds). + # (10 minutes * 60 seconds = 600 seconds). end_time = Time.now period = 60 # Look back every 60 seconds over the past 10 minutes. # Properties for the Amazon CloudWatch Logs log group. - log_group_name = "aws-doc-sdk-examples-cloudwatch-log" + log_group_name = 'aws-doc-sdk-examples-cloudwatch-log' # AWS service clients for this code example. - region = "us-east-1" + region = 'us-east-1' sts_client = Aws::STS::Client.new(region: region) sns_client = Aws::SNS::Client.new(region: region) iam_client = Aws::IAM::Client.new(region: region) @@ -781,8 +794,8 @@ def run_me topic_arn = "arn:aws:sns:#{region}:#{account_id}:#{topic_name}" unless topic_exists?(sns_client, topic_arn) topic_arn = create_topic(sns_client, topic_name, email_address) - if topic_arn == "Error" - puts "Could not create the Amazon SNS topic correctly. Program stopped." + if topic_arn == 'Error' + puts 'Could not create the Amazon SNS topic correctly. Program stopped.' manual_cleanup_notice( topic_name, role_name, rule_name, log_group_name, instance_id ) @@ -794,8 +807,8 @@ def run_me role_arn = "arn:aws:iam::#{account_id}:role/#{role_name}" unless role_exists?(iam_client, role_arn) role_arn = create_role(iam_client, role_name) - if role_arn == "Error" - puts "Could not create the IAM role correctly. Program stopped." + if role_arn == 'Error' + puts 'Could not create the IAM role correctly. Program stopped.' manual_cleanup_notice( topic_name, role_name, rule_name, log_group_name, instance_id ) @@ -803,33 +816,30 @@ def run_me end # If the Amazon EventBridge rule doesn't exist, create it. - unless rule_exists?(cloudwatchevents_client, rule_name) - unless rule_created?( - cloudwatchevents_client, - rule_name, - rule_description, - instance_state, - role_arn, - target_id, - topic_arn + if !rule_exists?(cloudwatchevents_client, rule_name) && !rule_created?( + cloudwatchevents_client, + rule_name, + rule_description, + instance_state, + role_arn, + target_id, + topic_arn + ) + puts 'Could not create the Amazon EventBridge rule correctly. ' \ + 'Program stopped.' + manual_cleanup_notice( + topic_name, role_name, rule_name, log_group_name, instance_id ) - puts "Could not create the Amazon EventBridge rule correctly. " \ - "Program stopped." - manual_cleanup_notice( - topic_name, role_name, rule_name, log_group_name, instance_id - ) - end end # If the Amazon CloudWatch Logs log group doesn't exist, create it. - unless log_group_exists?(cloudwatchlogs_client, log_group_name) - unless log_group_created?(cloudwatchlogs_client, log_group_name) - puts "Could not create the Amazon CloudWatch Logs log group " \ - "correctly. Program stopped." - manual_cleanup_notice( - topic_name, role_name, rule_name, log_group_name, instance_id - ) - end + if !log_group_exists?(cloudwatchlogs_client, + log_group_name) && !log_group_created?(cloudwatchlogs_client, log_group_name) + puts 'Could not create the Amazon CloudWatch Logs log group ' \ + 'correctly. Program stopped.' + manual_cleanup_notice( + topic_name, role_name, rule_name, log_group_name, instance_id + ) end # Restart the Amazon EC2 instance, which triggers the rule. @@ -839,8 +849,8 @@ def run_me instance_id, log_group_name ) - puts "Could not restart the instance to trigger the rule. " \ - "Continuing anyway to show information about the rule and logs..." + puts 'Could not restart the instance to trigger the rule. ' \ + 'Continuing anyway to show information about the rule and logs...' end # Display how many times the rule was triggered over the past 10 minutes. @@ -863,4 +873,3 @@ def run_me end run_me if $PROGRAM_NAME == __FILE__ -# snippet-end:[cloudwatch.cross-service.Ruby.displayReminder] diff --git a/ruby/example_code/glue/getting_started.rb b/ruby/example_code/glue/getting_started.rb index b0ae0c83721..e03e51ec08e 100644 --- a/ruby/example_code/glue/getting_started.rb +++ b/ruby/example_code/glue/getting_started.rb @@ -3,24 +3,13 @@ # frozen_string_literal: true -# To run this demo, you will need Ruby 2.6 or later, plus dependencies. -# For more information, see: -# https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/README.md - -require "aws-sdk-glue" -require "aws-sdk-iam" -require "aws-sdk-s3" -require "io/console" -require "pp" -require "logger" -require "optparse" -require "cli/ui" -require "yaml" -# require "pry" -require_relative("../../helpers/disclaimers") -require_relative("../../helpers/decorators") -require_relative("../../helpers/waiters") -require_relative("glue_wrapper") +require 'aws-sdk-glue' +require 'aws-sdk-iam' +require 'aws-sdk-s3' +require 'logger' +require 'yaml' +require_relative('../../helpers/decorators') +require_relative('glue_wrapper') @logger = Logger.new($stdout) @@ -35,182 +24,82 @@ def initialize(glue_client, glue_service_role, glue_bucket, logger) def run(crawler_name, db_name, db_prefix, data_source, job_script, job_name) wrapper = GlueWrapper.new(@glue_client, @logger) + setup_crawler(wrapper, crawler_name, db_name, db_prefix, data_source) + query_database(wrapper, crawler_name, db_name) + create_and_run_job(wrapper, job_script, job_name, db_name) + end + + private - new_step(1, "Create a crawler") - puts "Checking for crawler #{crawler_name}." + def setup_crawler(wrapper, crawler_name, db_name, db_prefix, data_source) + new_step(1, 'Create a crawler') crawler = wrapper.get_crawler(crawler_name) - if crawler == false + unless crawler puts "Creating crawler #{crawler_name}." wrapper.create_crawler(crawler_name, @glue_service_role.arn, db_name, db_prefix, data_source) - puts "Successfully created #{crawler_name}:" - crawler = wrapper.get_crawler(crawler_name) - puts JSON.pretty_generate(crawler).yellow + puts "Successfully created #{crawler_name}." end - print "\nDone!\n".green - - new_step(2, "Run a crawler to output a database.") - puts "Location of input data analyzed by crawler: #{data_source}" - puts "Outputs: a Data Catalog database in CSV format containing metadata on input." wrapper.start_crawler(crawler_name) - puts "Starting crawler... (this typically takes a few minutes)" + monitor_crawler(wrapper, crawler_name) + end + + def monitor_crawler(wrapper, crawler_name) + new_step(2, 'Monitor Crawler') crawler_state = nil - while crawler_state != "READY" + until crawler_state == 'READY' custom_wait(15) crawler = wrapper.get_crawler(crawler_name) - crawler_state = crawler[0]["state"] - print "Status check: #{crawler_state}.".yellow + crawler_state = crawler[0]['state'] + print "Crawler status: #{crawler_state}".yellow end - print "\nDone!\n".green + end - new_step(3, "Query the database.") - database = wrapper.get_database(db_name) + def query_database(wrapper, _crawler_name, db_name) + new_step(3, 'Query the database.') + wrapper.get_database(db_name) puts "The crawler created database #{db_name}:" - print "#{database}".yellow - puts "\nThe database contains these tables:" - tables = wrapper.get_tables(db_name) - tables.each_with_index do |table, index| - print "\t#{index + 1}. #{table['name']}".yellow - end - print "\nDone!\n".green + puts "Database contains tables: #{wrapper.get_tables(db_name).map { |t| t['name'] }}" + end - new_step(4, "Create a job definition that runs an ETL script.") - puts "Uploading Python ETL script to S3..." + def create_and_run_job(wrapper, job_script, job_name, db_name) + new_step(4, 'Create and run job.') wrapper.upload_job_script(job_script, @glue_bucket) - puts "Creating job definition #{job_name}:\n" - response = wrapper.create_job(job_name, "Getting started example job.", @glue_service_role.arn, "s3://#{@glue_bucket.name}/#{job_script}") - puts JSON.pretty_generate(response).yellow - print "\nDone!\n".green + wrapper.create_job(job_name, 'ETL Job', @glue_service_role.arn, "s3://#{@glue_bucket.name}/#{job_script}") + run_job(wrapper, job_name, db_name) + end - new_step(5, "Start a new job") + def run_job(wrapper, job_name, db_name) + new_step(5, 'Run the job.') + wrapper.start_job_run(job_name, db_name, wrapper.get_tables(db_name)[0]['name'], @glue_bucket.name) job_run_status = nil - job_run_id = wrapper.start_job_run( - job_name, - db_name, - tables[0]["name"], - @glue_bucket.name - ) - puts "Job #{job_name} started. Let's wait for it to run." - until ["SUCCEEDED", "STOPPED", "FAILED", "TIMEOUT"].include?(job_run_status) + until %w[SUCCEEDED FAILED STOPPED].include?(job_run_status) custom_wait(10) job_run = wrapper.get_job_runs(job_name) - job_run_status = job_run[0]["job_run_state"] - print "Status check: #{job_name}/#{job_run_id} - #{job_run_status}.".yellow - end - print "\nDone!\n".green - - new_step(6, "View results from a successful job run.") - if job_run_status == "SUCCEEDED" - puts "Data from your job run is stored in your S3 bucket '#{@glue_bucket.name}'. Files include:" - begin - - # Print the key name of each object in the bucket. - @glue_bucket.objects.each do |object_summary| - if object_summary.key.include?("run-") - print "#{object_summary.key}".yellow - end - end - - # Print the first 256 bytes of a run file - desired_sample_objects = 1 - @glue_bucket.objects.each do |object_summary| - if object_summary.key.include?("run-") - if desired_sample_objects > 0 - sample_object = @glue_bucket.object(object_summary.key) - sample = sample_object.get(range: "bytes=0-255").body.read - puts "\nSample run file contents:" - print "#{sample}".yellow - desired_sample_objects -= 1 - end - end - end - rescue Aws::S3::Errors::ServiceError => e - logger.error( - "Couldn't get job run data. Here's why: %s: %s", - e.response.error.code, e.response.error.message - ) - raise - end + job_run_status = job_run[0]['job_run_state'] + print "Job #{job_name} status: #{job_run_status}".yellow end - print "\nDone!\n".green - - new_step(7, "Delete job definition and crawler.") - wrapper.delete_job(job_name) - puts "Job deleted: #{job_name}." - wrapper.delete_crawler(crawler_name) - puts "Crawler deleted: #{crawler_name}." - wrapper.delete_table(db_name, tables[0]["name"]) - puts "Table deleted: #{tables[0]["name"]} in #{db_name}." - wrapper.delete_database(db_name) - puts "Database deleted: #{db_name}." - print "\nDone!\n".green end end def main + banner('../../helpers/banner.txt') + puts 'Starting AWS Glue demo...' - banner("../../helpers/banner.txt") - puts "######################################################################################################".yellow - puts "# #".yellow - puts "# EXAMPLE CODE DEMO: #".yellow - puts "# AWS Glue #".yellow - puts "# #".yellow - puts "######################################################################################################".yellow - puts "" - puts "You have launched a demo of AWS Glue using the AWS for Ruby v3 SDK. Over the next 60 seconds, it will" - puts "do the following:" - puts " 1. Create a crawler." - puts " 2. Run a crawler to output a database." - puts " 3. Query the database." - puts " 4. Create a job definition that runs an ETL script." - puts " 5. Start a new job." - puts " 6. View results from a successful job run." - puts " 7. Delete job definition and crawler." - puts "" - - confirm_begin - billing - security - puts "\e[H\e[2J" - - # Set input file names - job_script_filepath = "job_script.py" - resource_names = YAML.load_file("resource_names.yaml") - - # Instantiate existing IAM role. - iam = Aws::IAM::Resource.new(region: "us-east-1") - iam_role_name = resource_names["glue_service_role"] - iam_role = iam.role(iam_role_name) - - # Instantiate existing S3 bucket. - s3 = Aws::S3::Resource.new(region: "us-east-1") - s3_bucket_name = resource_names["glue_bucket"] - s3_bucket = s3.bucket(s3_bucket_name) - - scenario = GlueCrawlerJobScenario.new( - Aws::Glue::Client.new(region: "us-east-1"), - iam_role, - s3_bucket, - @logger - ) - - random_int = rand(10 ** 4) - scenario.run( - "doc-example-crawler-#{random_int}", - "doc-example-database-#{random_int}", - "doc-example-#{random_int}-", - "s3://crawler-public-us-east-1/flight/2016/csv", - job_script_filepath, - "doc-example-job-#{random_int}" - ) - - puts "-" * 88 - puts "You have reached the end of this tour of AWS Glue." - puts "To destroy CDK-created resources, run:\n cdk destroy" - puts "-" * 88 + # Load resource names from YAML. + resource_names = YAML.load_file('resource_names.yaml') + # Setup services and resources. + iam_role = Aws::IAM::Resource.new(region: 'us-east-1').role(resource_names['glue_service_role']) + s3_bucket = Aws::S3::Resource.new(region: 'us-east-1').bucket(resource_names['glue_bucket']) + + # Instantiate scenario and run. + scenario = GlueCrawlerJobScenario.new(Aws::Glue::Client.new(region: 'us-east-1'), iam_role, s3_bucket, @logger) + random_suffix = rand(10**4) + scenario.run("crawler-#{random_suffix}", "db-#{random_suffix}", "prefix-#{random_suffix}-", 's3://data_source', + 'job_script.py', "job-#{random_suffix}") + + puts 'Demo complete.' end # snippet-end:[ruby.example_code.glue.Scenario_GetStartedCrawlersJobs] -if __FILE__ == $0 - main -end +main if __FILE__ == $PROGRAM_NAME diff --git a/ruby/example_code/glue/glue_wrapper.rb b/ruby/example_code/glue/glue_wrapper.rb index d6eeb895d23..83127130783 100644 --- a/ruby/example_code/glue/glue_wrapper.rb +++ b/ruby/example_code/glue/glue_wrapper.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-glue" -require "aws-sdk-s3" -require "logger" +require 'aws-sdk-glue' +require 'aws-sdk-s3' +require 'logger' # snippet-start:[ruby.example_code.glue.GlueWrapper.full] # snippet-start:[ruby.example_code.glue.GlueWrapper.decl] @@ -42,7 +42,7 @@ def get_crawler(name) # @param db_prefix [String] The prefix to be added to the names of tables that the crawler creates. # @param s3_target [String] The S3 path that the crawler will crawl. # @return [void] - def create_crawler(name, role_arn, db_name, db_prefix, s3_target) + def create_crawler(name, role_arn, db_name, _db_prefix, s3_target) @glue_client.create_crawler( name: name, role: role_arn, @@ -95,9 +95,9 @@ def delete_crawler(name) def get_database(name) response = @glue_client.get_database(name: name) response.database -rescue Aws::Glue::Errors::GlueException => e - @logger.error("Glue could not get database #{name}: \n#{e.message}") - raise + rescue Aws::Glue::Errors::GlueException => e + @logger.error("Glue could not get database #{name}: \n#{e.message}") + raise end # snippet-end:[ruby.example_code.glue.GetDatabase] @@ -129,11 +129,11 @@ def create_job(name, description, role_arn, script_location) description: description, role: role_arn, command: { - name: "glueetl", + name: 'glueetl', script_location: script_location, - python_version: "3" + python_version: '3' }, - glue_version: "3.0" + glue_version: '3.0' ) rescue Aws::Glue::Errors::GlueException => e @logger.error("Glue could not create job #{name}: \n#{e.message}") @@ -247,15 +247,14 @@ def delete_database(database_name) def upload_job_script(file_path, bucket_resource) File.open(file_path) do |file| bucket_resource.client.put_object({ - body: file, - bucket: bucket_resource.name, - key: file_path - }) + body: file, + bucket: bucket_resource.name, + key: file_path + }) end rescue Aws::S3::Errors::S3UploadFailedError => e @logger.error("S3 could not upload job script: \n#{e.message}") raise end - end # snippet-end:[ruby.example_code.glue.GlueWrapper.full] diff --git a/ruby/example_code/glue/spec/getting_started_scenario_spec.rb b/ruby/example_code/glue/spec/getting_started_scenario_spec.rb index 86fabf823a6..a09232fe82b 100644 --- a/ruby/example_code/glue/spec/getting_started_scenario_spec.rb +++ b/ruby/example_code/glue/spec/getting_started_scenario_spec.rb @@ -7,46 +7,45 @@ # For more information, see: # https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/README.md -require "aws-sdk-glue" -require "aws-sdk-iam" -require "aws-sdk-s3" -require "io/console" -require "pp" -require "logger" -require "optparse" -require "cli/ui" -require "yaml" -require_relative("../../../helpers/disclaimers") -require_relative("../../../helpers/decorators") -require_relative("../../../helpers/waiters") -require_relative("../glue_wrapper") -require_relative("../getting_started") +require 'aws-sdk-glue' +require 'aws-sdk-iam' +require 'aws-sdk-s3' +require 'io/console' +require 'logger' +require 'optparse' +require 'cli/ui' +require 'yaml' +require_relative('../../../helpers/disclaimers') +require_relative('../../../helpers/decorators') +require_relative('../../../helpers/waiters') +require_relative('../glue_wrapper') +require_relative('../getting_started') describe GlueWrapper, integ: true do - context "GlueWrapper" do - resource_names = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), "./..", "resource_names.yaml"))) + context 'GlueWrapper' do + resource_names = YAML.safe_load(File.open(File.join(File.dirname(__FILE__), './..', 'resource_names.yaml'))) # Instantiate existing IAM role created with the CDK - iam = Aws::IAM::Resource.new(region: "us-east-1") - iam_role_name = resource_names["glue_service_role"] + iam = Aws::IAM::Resource.new(region: 'us-east-1') + iam_role_name = resource_names['glue_service_role'] glue_service_role = iam.role(iam_role_name) # Instantiate existing S3 bucket created with the CDK. - s3 = Aws::S3::Resource.new(region: "us-east-1") - s3_bucket_name = resource_names["glue_bucket"] + s3 = Aws::S3::Resource.new(region: 'us-east-1') + s3_bucket_name = resource_names['glue_bucket'] glue_bucket = s3.bucket(s3_bucket_name) - random_int = rand(10 ** 4) + random_int = rand(10**4) crawler_name = "doc-example-crawler-#{random_int}" db_name = "doc-example-database-#{random_int}" db_prefix = "doc-example-#{random_int}-" - data_source = "s3://crawler-public-us-east-1/flight/2016/csv" - job_script = "test_job_script.py" + data_source = 's3://crawler-public-us-east-1/flight/2016/csv' + job_script = 'test_job_script.py' job_name = "doc-example-job-#{random_int}" - wrapper = GlueWrapper.new(Aws::Glue::Client.new(region: "us-east-1"), Logger.new($stdout)) + wrapper = GlueWrapper.new(Aws::Glue::Client.new(region: 'us-east-1'), Logger.new($stdout)) - it "Checking for crawler", integ: true do + it 'Checking for crawler', integ: true do crawler = wrapper.get_crawler(crawler_name) if crawler == false puts "Creating crawler #{crawler_name}." @@ -58,89 +57,86 @@ print "\nDone!\n".green end - it "Starts crawler", integ: true do + it 'Starts crawler', integ: true do wrapper.start_crawler(crawler_name) puts "Let's wait for the crawler to run. This typically takes a few minutes." crawler_state = nil - while crawler_state != "READY" + while crawler_state != 'READY' custom_wait(10) crawler = wrapper.get_crawler(crawler_name) - crawler_state = crawler[0]["state"] + crawler_state = crawler[0]['state'] print "Status check: #{crawler_state}.".yellow end print "\nDone!\n".green end - it "Checks database created by crawler", integ: true do + it 'Checks database created by crawler', integ: true do database = wrapper.get_database(db_name) puts "The crawler created database #{db_name}:" - print "#{database}".yellow + print database.to_s.yellow puts "\nThe database contains these tables:" tables = wrapper.get_tables(db_name) tables.each_with_index do |table, index| print "\t#{index + 1}. #{table['name']}".yellow end print "\nDone!\n".green - puts "-" * 88 + puts '-' * 88 end - - it "Creates a job definition that runs an ETL script", integ: true do - puts "Uploading Python ETL script to S3..." + it 'Creates a job definition that runs an ETL script', integ: true do + puts 'Uploading Python ETL script to S3...' script_directory = File.dirname(__FILE__) file_path = File.join(script_directory, job_script) wrapper.upload_job_script(file_path, glue_bucket) puts "Creating job definition #{job_name}:\n" - response = wrapper.create_job(job_name, "Getting started example job.", glue_service_role.arn, "s3://#{glue_bucket.name}/#{job_script}") + response = wrapper.create_job(job_name, 'Getting started example job.', glue_service_role.arn, + "s3://#{glue_bucket.name}/#{job_script}") puts JSON.pretty_generate(response).yellow print "\nDone!\n".green end - it "Starts a new job", integ: true do + it 'Starts a new job', integ: true do tables = wrapper.get_tables(db_name) job_run_status = nil job_run_id = wrapper.start_job_run( job_name, db_name, - tables[0]["name"], + tables[0]['name'], glue_bucket.name ) puts "Job #{job_name} started. Let's wait for it to run." - until ["SUCCEEDED", "STOPPED", "FAILED", "TIMEOUT"].include?(job_run_status) + until %w[SUCCEEDED STOPPED FAILED TIMEOUT].include?(job_run_status) custom_wait(10) job_run = wrapper.get_job_runs(job_name) - job_run_status = job_run[0]["job_run_state"] + job_run_status = job_run[0]['job_run_state'] print "Status check: #{job_name}/#{job_run_id} - #{job_run_status}.".yellow end - puts "-" * 88 + puts '-' * 88 end - it "Views results from a successful job run", integ: true do + it 'Views results from a successful job run', integ: true do job_run = wrapper.get_job_runs(job_name) - job_run_status = job_run[0]["job_run_state"] - if job_run_status == "SUCCEEDED" + job_run_status = job_run[0]['job_run_state'] + if job_run_status == 'SUCCEEDED' puts "Data from your job run is stored in your S3 bucket '#{glue_bucket.name}'. Files include:" begin - # Print the key name of each object in the bucket. glue_bucket.objects.each do |object_summary| - if object_summary.key.include?("run-") - print "#{object_summary.key}".yellow - end + print object_summary.key.to_s.yellow if object_summary.key.include?('run-') end # Print the first 256 bytes of a run file desired_sample_objects = 1 glue_bucket.objects.each do |object_summary| - if object_summary.key.include?("run-") - if desired_sample_objects > 0 - sample_object = glue_bucket.object(object_summary.key) - sample = sample_object.get(range: "bytes=0-255").body.read - puts "\nSample run file contents:" - print "#{sample}".yellow - desired_sample_objects -= 1 - end - end + next unless object_summary.key.include?('run-') + + next unless desired_sample_objects.positive? + + sample_object = glue_bucket.object(object_summary.key) + sample = sample_object.get(range: 'bytes=0-255').body.read + puts "\nSample run file contents:" + print sample.to_s.yellow + desired_sample_objects -= 1 end rescue Aws::S3::Errors::ServiceError => e logger.error( @@ -152,7 +148,7 @@ end end - it "Deletes job definition and crawler.", integ: true do + it 'Deletes job definition and crawler.', integ: true do wrapper.delete_job(job_name) wrapper.delete_crawler(crawler_name) end diff --git a/ruby/example_code/iam/README.md b/ruby/example_code/iam/README.md index 410a730578f..8271a32a307 100644 --- a/ruby/example_code/iam/README.md +++ b/ruby/example_code/iam/README.md @@ -39,25 +39,25 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `ruby` Code excerpts that show you how to call individual service functions. - [AttachRolePolicy](attach_role_policy.rb#L6) -- [AttachUserPolicy](attach_user_policy.rb#L39) +- [AttachUserPolicy](attach_user_policy.rb#L38) - [CreateAccessKey](manage_access_keys.rb#L6) - [CreateAccountAlias](manage_account_aliases.rb#L6) - [CreatePolicy](attach_role_policy.rb#L6) -- [CreateRole](manage_roles.rb#L63) -- [CreateServiceLinkedRole](manage_roles.rb#L91) +- [CreateRole](manage_roles.rb#L64) +- [CreateServiceLinkedRole](manage_roles.rb#L92) - [CreateUser](manage_users.rb#L18) - [DeleteAccessKey](manage_access_keys.rb#L6) - [DeleteAccountAlias](manage_account_aliases.rb#L6) -- [DeleteRole](manage_roles.rb#L111) +- [DeleteRole](manage_roles.rb#L113) - [DeleteServerCertificate](manage_server_certificates.rb#L6) - [DeleteServiceLinkedRole](manage_roles.rb#L143) - [DeleteUser](manage_users.rb#L134) - [DeleteUserPolicy](manage_users.rb#L134) - [DetachRolePolicy](attach_role_policy.rb#L6) -- [DetachUserPolicy](attach_user_policy.rb#L57) +- [DetachUserPolicy](attach_user_policy.rb#L56) - [GetAccountPasswordPolicy](get_account_password_policy.rb#L6) - [GetPolicy](attach_role_policy.rb#L34) -- [GetRole](manage_roles.rb#L44) +- [GetRole](manage_roles.rb#L45) - [GetUser](manage_users.rb#L43) - [ListAccessKeys](manage_access_keys.rb#L6) - [ListAccountAliases](manage_account_aliases.rb#L6) diff --git a/ruby/example_code/iam/attach_role_policy.rb b/ruby/example_code/iam/attach_role_policy.rb index c29b131a786..7bd07719888 100644 --- a/ruby/example_code/iam/attach_role_policy.rb +++ b/ruby/example_code/iam/attach_role_policy.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.iam.AttachRolePolicy] # Manages policies in AWS Identity and Access Management (IAM) @@ -12,7 +12,7 @@ class RolePolicyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "PolicyManager" + @logger.progname = 'PolicyManager' end # Creates a policy @@ -101,27 +101,27 @@ def detach_policy_from_role(role_name, policy_arn) if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new manager = RolePolicyManager.new(iam_client) - role_name = "my-role" - policy_name = "my-policy" + role_name = 'my-role' + policy_name = 'my-policy' policy_document = { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Effect" => "Allow", - "Action" => "s3:ListAllMyBuckets", - "Resource" => "arn:aws:s3:::*" + 'Effect' => 'Allow', + 'Action' => 's3:ListAllMyBuckets', + 'Resource' => 'arn:aws:s3:::*' } ] } iam_client.create_role( role_name: role_name, assume_role_policy_document: { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Effect" => "Allow", - "Principal" => { "Service" => "ec2.amazonaws.com" }, - "Action" => "sts:AssumeRole" + 'Effect' => 'Allow', + 'Principal' => { 'Service' => 'ec2.amazonaws.com' }, + 'Action' => 'sts:AssumeRole' } ] }.to_json @@ -133,6 +133,6 @@ def detach_policy_from_role(role_name, policy_arn) puts "Policy ARNs attached to role '#{role_name}': #{attached_policies}" manager.detach_policy_from_role(role_name, policy_arn) else - puts "Failed to create policy." + puts 'Failed to create policy.' end end diff --git a/ruby/example_code/iam/attach_user_policy.rb b/ruby/example_code/iam/attach_user_policy.rb index 183c379597c..b33ff85f8c5 100644 --- a/ruby/example_code/iam/attach_user_policy.rb +++ b/ruby/example_code/iam/attach_user_policy.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # Manages IAM user policies class UserPolicyManager @@ -11,7 +11,7 @@ class UserPolicyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "UserManager" + @logger.progname = 'UserManager' end # snippet-start:[ruby.iam.PutUserPolicy] @@ -22,10 +22,10 @@ def initialize(iam_client, logger: Logger.new($stdout)) # @return [Boolean] def create_user_policy(username, policy_name, policy_document) @iam_client.put_user_policy({ - user_name: username, - policy_name: policy_name, - policy_document: policy_document - }) + user_name: username, + policy_name: policy_name, + policy_document: policy_document + }) @logger.info("Policy #{policy_name} created for user #{username}.") true rescue Aws::IAM::Errors::ServiceError => e @@ -35,7 +35,6 @@ def create_user_policy(username, policy_name, policy_document) end # snippet-end:[ruby.iam.PutUserPolicy] - # snippet-start:[ruby.iam.AttachUserPolicy] # Attaches a policy to a user # @@ -68,22 +67,21 @@ def detach_user_policy(user_name, policy_arn) @logger.info("Policy '#{policy_arn}' detached from user '#{user_name}' successfully.") true rescue Aws::IAM::Errors::NoSuchEntity - @logger.error("Error detaching policy: Policy or user does not exist.") + @logger.error('Error detaching policy: Policy or user does not exist.') false rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from user '#{user_name}': #{e.message}") false end # snippet-end:[ruby.iam.DetachUserPolicy] - end # Example usage: if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new user_manager = UserPolicyManager.new(iam_client) - user_name = "my-user" - policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess" + user_name = 'my-user' + policy_arn = 'arn:aws:iam::aws:policy/AmazonS3FullAccess' if user_manager.attach_policy_to_user(user_name, policy_arn) puts "Policy attached to user '#{user_name}'." @@ -100,12 +98,12 @@ def detach_user_policy(user_name, policy_arn) policy_name = "test-policy-#{Time.now.to_i}" policy_document = { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Effect" => "Allow", - "Action" => "s3:ListAllMyBuckets", - "Resource" => "arn:aws:s3:::*" + 'Effect' => 'Allow', + 'Action' => 's3:ListAllMyBuckets', + 'Resource' => 'arn:aws:s3:::*' } ] } diff --git a/ruby/example_code/iam/get_account_password_policy.rb b/ruby/example_code/iam/get_account_password_policy.rb index 715c5084d28..4d8679598ce 100644 --- a/ruby/example_code/iam/get_account_password_policy.rb +++ b/ruby/example_code/iam/get_account_password_policy.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.example_code.iam.GetAccountPasswordPolicy] # Class to manage IAM account password policies @@ -11,20 +11,18 @@ class PasswordPolicyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "IAMPolicyManager" + @logger.progname = 'IAMPolicyManager' end # Retrieves and logs the account password policy def print_account_password_policy - begin - response = @iam_client.get_account_password_policy - @logger.info("The account password policy is: #{response.password_policy.to_h}") - rescue Aws::IAM::Errors::NoSuchEntity - @logger.info("The account does not have a password policy.") - rescue Aws::Errors::ServiceError => e - @logger.error("Couldn't print the account password policy. Error: #{e.code} - #{e.message}") - raise - end + response = @iam_client.get_account_password_policy + @logger.info("The account password policy is: #{response.password_policy.to_h}") + rescue Aws::IAM::Errors::NoSuchEntity + @logger.info('The account does not have a password policy.') + rescue Aws::Errors::ServiceError => e + @logger.error("Couldn't print the account password policy. Error: #{e.code} - #{e.message}") + raise end end # snippet-end:[ruby.example_code.iam.GetAccountPasswordPolicy] diff --git a/ruby/example_code/iam/list_admins.rb b/ruby/example_code/iam/list_admins.rb index e25d22ed4f2..5e1a5572824 100644 --- a/ruby/example_code/iam/list_admins.rb +++ b/ruby/example_code/iam/list_admins.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[iam.ruby.ListAdmins] # Manages IAM user's administrative privileges class AdminPrivilegeManager - ADMIN_ACCESS_POLICY_NAME = "AdministratorAccess".freeze + ADMIN_ACCESS_POLICY_NAME = 'AdministratorAccess'.freeze def initialize(iam_client, logger: Logger.new($stdout)) @iam = iam_client @logger = logger - @logger.progname = "AdminPrivilegeManager" + @logger.progname = 'AdminPrivilegeManager' end # Checks if the specified IAM entity (user or group) has admin privileges - def has_admin_privileges?(entity) + def admin_privileges?(entity) entity_policies = @iam.list_attached_user_policies(user_name: entity.user_name) if entity.respond_to?(:user_name) entity_policies ||= @iam.list_attached_group_policies(group_name: entity.group_name) if entity.respond_to?(:group_name) @@ -39,7 +39,8 @@ def user_is_admin?(user) # Counts and lists users with admin privileges def count_and_list_admins - num_users, num_admins = 0, 0 + num_users = 0 + num_admins = 0 @iam.list_users.users.each do |user| num_users += 1 if user_is_admin?(user) diff --git a/ruby/example_code/iam/list_groups.rb b/ruby/example_code/iam/list_groups.rb index aaf0c9d7562..5454d5f5b76 100644 --- a/ruby/example_code/iam/list_groups.rb +++ b/ruby/example_code/iam/list_groups.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.iam.ListGroups] # A class to manage IAM operations via the AWS SDK client @@ -34,6 +34,6 @@ def list_groups(count) if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new iam_group_manager = IamGroupManager.new(iam_client) - puts "Attempting to list groups..." + puts 'Attempting to list groups...' iam_group_manager.list_groups(10) end diff --git a/ruby/example_code/iam/list_saml_providers.rb b/ruby/example_code/iam/list_saml_providers.rb index 07c3be53972..a6e1a38c240 100644 --- a/ruby/example_code/iam/list_saml_providers.rb +++ b/ruby/example_code/iam/list_saml_providers.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.example_code.iam.ListSamlProviders] class SamlProviderLister @@ -35,6 +35,6 @@ def list_saml_providers(count) if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new user_manager = SamlProviderLister.new(iam_client) - puts "Attempting to get details for available SAML providers..." + puts 'Attempting to get details for available SAML providers...' user_manager.list_saml_providers(10) end diff --git a/ruby/example_code/iam/list_users.rb b/ruby/example_code/iam/list_users.rb index 27bc7a3d0b0..99b10cb01aa 100644 --- a/ruby/example_code/iam/list_users.rb +++ b/ruby/example_code/iam/list_users.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.iam.ScenarioListUsers] class UserManager @@ -16,13 +16,13 @@ def initialize(iam_client, logger: Logger.new($stdout)) # Displays information about available users in AWS Identity and Access Management (IAM). # This includes user names, associated group names, inline embedded user policy names, # and access key IDs. Logging is added for monitoring purposes. - def get_user_details - @logger.info("Requesting list of users") + def user_details + @logger.info('Requesting list of users') users_response = @iam_client.list_users if users_response.users.empty? - @logger.warn("No users found.") - puts "No users found." + @logger.warn('No users found.') + puts 'No users found.' return end @@ -46,7 +46,7 @@ def get_user_details def display_user_details(user) @logger.info("Displaying details for user: #{user.user_name}") - puts "-" * 30 + puts '-' * 30 puts "User name: #{user.user_name}" display_groups(user.user_name) @@ -56,10 +56,10 @@ def display_user_details(user) def display_groups(user_name) @logger.info("Listing groups for user: #{user_name}") - puts "Groups:" + puts 'Groups:' groups_response = @iam_client.list_groups_for_user(user_name: user_name) if groups_response.groups.empty? - puts " None" + puts ' None' else groups_response.groups.each { |group| puts " #{group.group_name}" } end @@ -67,10 +67,10 @@ def display_groups(user_name) def display_policies(user_name) @logger.info("Listing policies for user: #{user_name}") - puts "Inline embedded user policies:" + puts 'Inline embedded user policies:' policies_response = @iam_client.list_user_policies(user_name: user_name) if policies_response.policy_names.empty? - puts " None" + puts ' None' else policies_response.policy_names.each { |policy_name| puts " #{policy_name}" } end @@ -78,10 +78,10 @@ def display_policies(user_name) def display_access_keys(user_name) @logger.info("Listing access keys for user: #{user_name}") - puts "Access keys:" + puts 'Access keys:' access_keys_response = @iam_client.list_access_keys(user_name: user_name) if access_keys_response.access_key_metadata.empty? - puts " None" + puts ' None' else access_keys_response.access_key_metadata.each { |access_key| puts " #{access_key.access_key_id}" } end @@ -93,6 +93,6 @@ def display_access_keys(user_name) if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new user_manager = UserManager.new(iam_client) - puts "Attempting to get details for available users..." + puts 'Attempting to get details for available users...' user_manager.get_user_details end diff --git a/ruby/example_code/iam/manage_access_keys.rb b/ruby/example_code/iam/manage_access_keys.rb index 8a22dd4597b..9ddf0438d0d 100644 --- a/ruby/example_code/iam/manage_access_keys.rb +++ b/ruby/example_code/iam/manage_access_keys.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[iam.ruby.exampleAccessKeys] # Manages access keys for IAM users @@ -9,7 +9,7 @@ class AccessKeyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "AccessKeyManager" + @logger.progname = 'AccessKeyManager' end # Lists access keys for a user @@ -22,7 +22,7 @@ def list_access_keys(user_name) else response.access_key_metadata.map(&:access_key_id) end - rescue Aws::IAM::Errors::NoSuchEntity => e + rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Error listing access keys: cannot find user '#{user_name}'.") [] rescue StandardError => e @@ -39,8 +39,8 @@ def create_access_key(user_name) access_key = response.access_key @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}") access_key - rescue Aws::IAM::Errors::LimitExceeded => e - @logger.error("Error creating access key: limit exceeded. Cannot create more.") + rescue Aws::IAM::Errors::LimitExceeded + @logger.error('Error creating access key: limit exceeded. Cannot create more.') nil rescue StandardError => e @logger.error("Error creating access key: #{e.message}") @@ -56,7 +56,7 @@ def deactivate_access_key(user_name, access_key_id) @iam_client.update_access_key( user_name: user_name, access_key_id: access_key_id, - status: "Inactive" + status: 'Inactive' ) true rescue StandardError => e @@ -92,25 +92,21 @@ def delete_access_key(user_name, access_key_id) puts "Access keys for '#{user_name}':" keys_before = manager.list_access_keys(user_name) - puts keys_before.any? ? keys_before.join("\n") : "No keys" + puts keys_before.any? ? keys_before.join("\n") : 'No keys' new_key = manager.create_access_key(user_name) puts "New key created: #{new_key.access_key_id}" if new_key keys_after = manager.list_access_keys(user_name) - puts "Access keys after creation:" - puts keys_after.any? ? keys_after.join("\n") : "No keys" + puts 'Access keys after creation:' + puts keys_after.any? ? keys_after.join("\n") : 'No keys' # Optionally deactivate and delete the new access key - if new_key && manager.deactivate_access_key(user_name, new_key.access_key_id) - puts "Key #{new_key.access_key_id} deactivated." - end + puts "Key #{new_key.access_key_id} deactivated." if new_key && manager.deactivate_access_key(user_name, new_key.access_key_id) - if new_key && manager.delete_access_key(user_name, new_key.access_key_id) - puts "Key #{new_key.access_key_id} deleted." - end + puts "Key #{new_key.access_key_id} deleted." if new_key && manager.delete_access_key(user_name, new_key.access_key_id) final_keys = manager.list_access_keys(user_name) puts "Final access keys for '#{user_name}':" - puts final_keys.any? ? final_keys.join("\n") : "No keys" + puts final_keys.any? ? final_keys.join("\n") : 'No keys' end diff --git a/ruby/example_code/iam/manage_account_aliases.rb b/ruby/example_code/iam/manage_account_aliases.rb index 1188a8e1d14..111ddaaa5f7 100644 --- a/ruby/example_code/iam/manage_account_aliases.rb +++ b/ruby/example_code/iam/manage_account_aliases.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[iam.ruby.ManageAccountAliases] class IAMAliasManager @@ -18,10 +18,10 @@ def list_aliases response = @iam_client.list_account_aliases if response.account_aliases.count.positive? - @logger.info("Account aliases are:") + @logger.info('Account aliases are:') response.account_aliases.each { |account_alias| @logger.info(" #{account_alias}") } else - @logger.info("No account aliases found.") + @logger.info('No account aliases found.') end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing account aliases: #{e.message}") @@ -57,7 +57,7 @@ def delete_account_alias(account_alias) if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new manager = IAMAliasManager.new(iam_client) - account_alias = "my-account-alias" + account_alias = 'my-account-alias' manager.list_aliases diff --git a/ruby/example_code/iam/manage_roles.rb b/ruby/example_code/iam/manage_roles.rb index aeb73c36730..e7d21c66412 100644 --- a/ruby/example_code/iam/manage_roles.rb +++ b/ruby/example_code/iam/manage_roles.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.iam.ManageRoles] # Manages IAM roles @@ -12,7 +12,7 @@ class RoleManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "RoleManager" + @logger.progname = 'RoleManager' end # snippet-start:[ruby.iam.ListRoles] @@ -26,6 +26,7 @@ def list_roles(count) @iam_client.list_roles.each_page do |page| page.roles.each do |role| break if roles_counted >= count + @logger.info("\t#{roles_counted + 1}: #{role.role_name}") role_names << role.role_name roles_counted += 1 @@ -48,7 +49,7 @@ def list_roles(count) # @return [Aws::IAM::Role] The retrieved role. def get_role(name) role = @iam_client.get_role({ - role_name: name, + role_name: name }).role puts("Got data for role '#{role.role_name}'. Its ARN is '#{role.arn}'.") rescue Aws::Errors::ServiceError => e @@ -97,7 +98,8 @@ def create_role(role_name, assume_role_policy_document, policy_arns) # @return [String] The name of the created role def create_service_linked_role(service_name, description, suffix) response = @iam_client.create_service_linked_role( - aws_service_name: service_name, description: description, custom_suffix: suffix,) + aws_service_name: service_name, description: description, custom_suffix: suffix + ) role_name = response.role.role_name @logger.info("Created service-linked role #{role_name}.") role_name @@ -113,30 +115,28 @@ def create_service_linked_role(service_name, description, suffix) # # @param role_name [String] The name of the role to delete. def delete_role(role_name) - begin - # Detach and delete attached policies - @iam_client.list_attached_role_policies(role_name: role_name).each do |response| - response.attached_policies.each do |policy| - @iam_client.detach_role_policy({ - role_name: role_name, - policy_arn: policy.policy_arn - }) - # Check if the policy is a customer managed policy (not AWS managed) - unless policy.policy_arn.include?("aws:policy/") - @iam_client.delete_policy({ policy_arn: policy.policy_arn }) - @logger.info("Deleted customer managed policy #{policy.policy_name}.") - end + # Detach and delete attached policies + @iam_client.list_attached_role_policies(role_name: role_name).each do |response| + response.attached_policies.each do |policy| + @iam_client.detach_role_policy({ + role_name: role_name, + policy_arn: policy.policy_arn + }) + # Check if the policy is a customer managed policy (not AWS managed) + unless policy.policy_arn.include?('aws:policy/') + @iam_client.delete_policy({ policy_arn: policy.policy_arn }) + @logger.info("Deleted customer managed policy #{policy.policy_name}.") end end - - # Delete the role - @iam_client.delete_role({ role_name: role_name }) - @logger.info("Deleted role #{role_name}.") - rescue Aws::IAM::Errors::ServiceError => e - @logger.error("Couldn't detach policies and delete role #{role_name}. Here's why:") - @logger.error("\t#{e.code}: #{e.message}") - raise end + + # Delete the role + @iam_client.delete_role({ role_name: role_name }) + @logger.info("Deleted role #{role_name}.") + rescue Aws::IAM::Errors::ServiceError => e + @logger.error("Couldn't detach policies and delete role #{role_name}. Here's why:") + @logger.error("\t#{e.code}: #{e.message}") + raise end # snippet-end:[ruby.iam.DeleteRole] @@ -161,10 +161,12 @@ def delete_service_linked_role(role_name) def check_deletion_status(role_name, task_id) loop do response = @iam_client.get_service_linked_role_deletion_status( - deletion_task_id: task_id) + deletion_task_id: task_id + ) status = response.status @logger.info("Deletion of #{role_name} #{status}.") break if %w[SUCCEEDED FAILED].include?(status) + sleep(3) end end @@ -174,11 +176,11 @@ def check_deletion_status(role_name, task_id) # @param e [Aws::Errors::ServiceError] The error encountered during deletion # @param role_name [String] The name of the role attempted to delete def handle_deletion_error(e, role_name) - unless e.code == "NoSuchEntity" - @logger.error("Couldn't delete #{role_name}. Here's why:") - @logger.error("\t#{e.code}: #{e.message}") - raise - end + return if e.code == 'NoSuchEntity' + + @logger.error("Couldn't delete #{role_name}. Here's why:") + @logger.error("\t#{e.code}: #{e.message}") + raise end # snippet-end:[ruby.iam.DeleteServiceLinkedRole] end @@ -188,14 +190,14 @@ def handle_deletion_error(e, role_name) if __FILE__ == $PROGRAM_NAME iam_client = Aws::IAM::Client.new role_manager = RoleManager.new(iam_client) - role_name = "my-ec2-s3-dynamodb-full-access-role" + role_name = 'my-ec2-s3-dynamodb-full-access-role' assume_role_policy_document = { - Version: "2012-10-17", + Version: '2012-10-17', Statement: [ { - Effect: "Allow", - Principal: { Service: "ec2.amazonaws.com" }, - Action: "sts:AssumeRole" + Effect: 'Allow', + Principal: { Service: 'ec2.amazonaws.com' }, + Action: 'sts:AssumeRole' } ] } @@ -204,7 +206,7 @@ def handle_deletion_error(e, role_name) if (role_arn = role_manager.create_role(role_name, assume_role_policy_document, policy_arns)) puts "Role created with ARN '#{role_arn}'." else - puts "Could not create role." + puts 'Could not create role.' end puts "Attempting to delete role #{role_name}..." diff --git a/ruby/example_code/iam/manage_server_certificates.rb b/ruby/example_code/iam/manage_server_certificates.rb index e491b2426ed..49b5396f946 100644 --- a/ruby/example_code/iam/manage_server_certificates.rb +++ b/ruby/example_code/iam/manage_server_certificates.rb @@ -1,14 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[iam.ruby.ManageServerCertificates] class ServerCertificateManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "ServerCertificateManager" + @logger.progname = 'ServerCertificateManager' end # Creates a new server certificate. @@ -20,7 +20,7 @@ def create_server_certificate(name, certificate_body, private_key) @iam_client.upload_server_certificate({ server_certificate_name: name, certificate_body: certificate_body, - private_key: private_key, + private_key: private_key }) true rescue Aws::IAM::Errors::ServiceError => e @@ -33,7 +33,7 @@ def list_server_certificate_names response = @iam_client.list_server_certificates if response.server_certificate_metadata_list.empty? - @logger.info("No server certificates found.") + @logger.info('No server certificates found.') return end diff --git a/ruby/example_code/iam/manage_users.rb b/ruby/example_code/iam/manage_users.rb index 900d8a692fb..b66da4c7663 100644 --- a/ruby/example_code/iam/manage_users.rb +++ b/ruby/example_code/iam/manage_users.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "logger" +require 'aws-sdk-iam' +require 'logger' # snippet-start:[ruby.iam.ManageUsers] # Manages IAM users @@ -12,7 +12,7 @@ class UserManager def initialize(iam_client, logger = Logger.new($stdout)) @iam_client = iam_client @logger = logger - @logger.progname = "UserManager" + @logger.progname = 'UserManager' end # snippet-start:[ruby.iam.CreateUser] @@ -94,10 +94,10 @@ def update_user_name(current_name, new_name) # @param user_name [String] The name of the user def display_groups(user_name) @logger.info("Listing groups for user: #{user_name}") - puts "Groups:" + puts 'Groups:' groups_response = @iam_client.list_groups_for_user(user_name: user_name) if groups_response.groups.empty? - puts " None" + puts ' None' else groups_response.groups.each { |group| puts " #{group.group_name}" } end @@ -108,10 +108,10 @@ def display_groups(user_name) # @param user_name [String] The name of the user def display_policies(user_name) @logger.info("Listing policies for user: #{user_name}") - puts "Inline embedded user policies:" + puts 'Inline embedded user policies:' policies_response = @iam_client.list_user_policies(user_name: user_name) if policies_response.policy_names.empty? - puts " None" + puts ' None' else policies_response.policy_names.each { |policy_name| puts " #{policy_name}" } end @@ -122,10 +122,10 @@ def display_policies(user_name) # @param user_name [String] The name of the user def display_access_keys(user_name) @logger.info("Listing access keys for user: #{user_name}") - puts "Access keys:" + puts 'Access keys:' access_keys_response = @iam_client.list_access_keys(user_name: user_name) if access_keys_response.access_key_metadata.empty? - puts " None" + puts ' None' else access_keys_response.access_key_metadata.each { |access_key| puts " #{access_key.access_key_id}" } end @@ -149,17 +149,16 @@ def delete_user(user_name) end # snippet-end:[ruby.iam.DeleteUser] - # This is a example module that displays information about available users in # AWS Identity and Access Management (IAM). This includes user names, associated # group names, inline embedded user policy names, and access key IDs. Logging is # added for monitoring purposes. - def get_user_details - @logger.info("Requesting list of users") + def user_details + @logger.info('Requesting list of users') users_response = list_users if users_response.users.empty? - @logger.warn("No users found.") - puts "No users found." + @logger.warn('No users found.') + puts 'No users found.' return end @@ -173,7 +172,7 @@ def get_user_details users_response.users.each do |user| @logger.info("Displaying details for user: #{user.user_name}") - puts "-" * 30 + puts '-' * 30 puts "User name: #{user.user_name}" display_groups(user.user_name) display_policies(user.user_name) @@ -191,21 +190,21 @@ def get_user_details iam_client = Aws::IAM::Client.new logger = Logger.new($stdout) user_manager = UserManager.new(iam_client, logger) - user_name = "example-user" - initial_password = "InitialP@ssw0rd!" + user_name = 'example-user' + initial_password = 'InitialP@ssw0rd!' # Create a new IAM user if (user_id = user_manager.create_user(user_name, initial_password)) logger.info("User '#{user_name}' created with ID '#{user_id}' and initial password '#{initial_password}'.") else - logger.error("User not created.") + logger.error('User not created.') end # Retrieve details of the created user if (user = user_manager.get_user(user_name)) logger.info("Retrieved user '#{user_name}' with creation date #{user.create_date}.") else - logger.error("Could not retrieve user details.") + logger.error('Could not retrieve user details.') end # List all IAM users diff --git a/ruby/example_code/iam/scenario_users.rb b/ruby/example_code/iam/scenario_users.rb index 28b4f645b32..fae7546d010 100644 --- a/ruby/example_code/iam/scenario_users.rb +++ b/ruby/example_code/iam/scenario_users.rb @@ -1,9 +1,9 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "aws-sdk-s3" -require "logger" +require 'aws-sdk-iam' +require 'aws-sdk-s3' +require 'logger' # snippet-start:[ruby.iam.Scenario_CreateUserAssumeRole] # Wraps the scenario actions. @@ -20,7 +20,7 @@ def initialize(iam_client, logger: Logger.new($stdout)) # # @param duration [Integer] The number of seconds to wait. def wait(duration) - puts("Give AWS time to propagate resources...") + puts('Give AWS time to propagate resources...') sleep(duration) end @@ -33,7 +33,7 @@ def create_user(user_name) user = @iam_client.create_user(user_name: user_name).user @logger.info("Created demo user named #{user.user_name}.") rescue Aws::Errors::ServiceError => e - @logger.info("Tried and failed to create demo user.") + @logger.info('Tried and failed to create demo user.') @logger.info("\t#{e.code}: #{e.message}") @logger.info("\nCan't continue the demo without a user!") raise @@ -67,12 +67,12 @@ def create_access_key_pair(user) # @return [Aws::IAM::Role] The newly created role. def create_role(role_name, user) trust_policy = { - Version: "2012-10-17", + Version: '2012-10-17', Statement: [{ - Effect: "Allow", - Principal: {'AWS': user.arn}, - Action: "sts:AssumeRole" - }] + Effect: 'Allow', + Principal: { 'AWS': user.arn }, + Action: 'sts:AssumeRole' + }] }.to_json role = @iam_client.create_role( role_name: role_name, @@ -96,12 +96,12 @@ def create_role(role_name, user) # @return [Aws::IAM::Policy] The newly created policy. def create_and_attach_role_policy(policy_name, role) policy_document = { - Version: "2012-10-17", + Version: '2012-10-17', Statement: [{ - Effect: "Allow", - Action: "s3:ListAllMyBuckets", - Resource: "arn:aws:s3:::*" - }] + Effect: 'Allow', + Action: 's3:ListAllMyBuckets', + Resource: 'arn:aws:s3:::*' + }] }.to_json policy = @iam_client.create_policy( policy_name: policy_name, @@ -126,12 +126,12 @@ def create_and_attach_role_policy(policy_name, role) # @return [Aws::IAM::UserPolicy] The newly created policy. def create_user_policy(policy_name, user, role) policy_document = { - Version: "2012-10-17", + Version: '2012-10-17', Statement: [{ - Effect: "Allow", - Action: "sts:AssumeRole", - Resource: role.arn - }] + Effect: 'Allow', + Action: 'sts:AssumeRole', + Resource: role.arn + }] }.to_json @iam_client.put_user_policy( user_name: user.user_name, @@ -166,8 +166,8 @@ def list_buckets(s3_resource) break if count.zero? end rescue Aws::Errors::ServiceError => e - if e.code == "AccessDenied" - puts("Attempt to list buckets with no permissions: AccessDenied.") + if e.code == 'AccessDenied' + puts('Attempt to list buckets with no permissions: AccessDenied.') else @logger.info("Couldn't list buckets for the account. Here's why: ") @logger.info("\t#{e.code}: #{e.message}") @@ -195,7 +195,7 @@ def assume_role(role_arn, sts_client) credentials = Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: role_arn, - role_session_name: "create-use-assume-role-scenario" + role_session_name: 'create-use-assume-role-scenario' ) @logger.info("Assumed role '#{role_arn}', got temporary credentials.") credentials @@ -242,9 +242,9 @@ def delete_user(user_name) # Runs the IAM create a user and assume a role scenario. def run_scenario(scenario) - puts("-" * 88) - puts("Welcome to the IAM create a user and assume a role demo!") - puts("-" * 88) + puts('-' * 88) + puts('Welcome to the IAM create a user and assume a role demo!') + puts('-' * 88) user = scenario.create_user("doc-example-user-#{Random.uuid}") user_key = scenario.create_access_key_pair(user) scenario.wait(10) @@ -252,23 +252,25 @@ def run_scenario(scenario) scenario.create_and_attach_role_policy("doc-example-role-policy-#{Random.uuid}", role) scenario.create_user_policy("doc-example-user-policy-#{Random.uuid}", user, role) scenario.wait(10) - puts("Try to list buckets with credentials for a user who has no permissions.") - puts("Expect AccessDenied from this call.") + puts('Try to list buckets with credentials for a user who has no permissions.') + puts('Expect AccessDenied from this call.') scenario.list_buckets( - scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key))) - puts("Now, assume the role that grants permission.") + scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key)) + ) + puts('Now, assume the role that grants permission.') temp_credentials = scenario.assume_role( - role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key)) - puts("Here are your buckets:") + role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key) + ) + puts('Here are your buckets:') scenario.list_buckets(scenario.create_s3_resource(temp_credentials)) puts("Deleting role '#{role.role_name}' and attached policies.") scenario.delete_role(role.role_name) puts("Deleting user '#{user.user_name}', policies, and keys.") scenario.delete_user(user.user_name) - puts("Thanks for watching!") - puts("-" * 88) + puts('Thanks for watching!') + puts('-' * 88) rescue Aws::Errors::ServiceError => e - puts("Something went wrong with the demo.") + puts('Something went wrong with the demo.') puts("\t#{e.code}: #{e.message}") end diff --git a/ruby/example_code/iam/spec/attach_role_policy_spec.rb b/ruby/example_code/iam/spec/attach_role_policy_spec.rb index 9069a857c00..ae45ec275b1 100644 --- a/ruby/example_code/iam/spec/attach_role_policy_spec.rb +++ b/ruby/example_code/iam/spec/attach_role_policy_spec.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require_relative("../attach_role_policy") -require "rspec" +require 'aws-sdk-iam' +require_relative('../attach_role_policy') +require 'rspec' describe RolePolicyManager do before(:all) do @@ -11,24 +11,24 @@ @role_name = "test-role-#{Time.now.to_i}" @policy_name = "test-policy-#{Time.now.to_i}" @policy_document = { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Effect" => "Allow", - "Action" => "s3:ListAllMyBuckets", - "Resource" => "arn:aws:s3:::*" + 'Effect' => 'Allow', + 'Action' => 's3:ListAllMyBuckets', + 'Resource' => 'arn:aws:s3:::*' } ] } @iam_client.create_role( role_name: @role_name, assume_role_policy_document: { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Effect" => "Allow", - "Principal" => { "Service" => "ec2.amazonaws.com" }, - "Action" => "sts:AssumeRole" + 'Effect' => 'Allow', + 'Principal' => { 'Service' => 'ec2.amazonaws.com' }, + 'Action' => 'sts:AssumeRole' } ] }.to_json @@ -39,7 +39,7 @@ @iam_client.delete_role(role_name: @role_name) end - it "creates, attaches, lists, and detaches a policy to a role" do + it 'creates, attaches, lists, and detaches a policy to a role' do policy_arn = @manager.create_policy(@policy_name, @policy_document) expect(policy_arn).not_to be_nil diff --git a/ruby/example_code/iam/spec/attach_user_policy_spec.rb b/ruby/example_code/iam/spec/attach_user_policy_spec.rb index 9e2e85df7f6..871bbbd3aaa 100644 --- a/ruby/example_code/iam/spec/attach_user_policy_spec.rb +++ b/ruby/example_code/iam/spec/attach_user_policy_spec.rb @@ -1,20 +1,20 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require_relative("../attach_user_policy") -require "rspec" +require 'aws-sdk-iam' +require_relative('../attach_user_policy') +require 'rspec' describe UserPolicyManager do let(:iam_client) { Aws::IAM::Client.new } let(:user_manager) { UserPolicyManager.new(iam_client) } let(:user_name) { "test-user-#{Time.now.to_i}" } - let(:policy_arn) { "arn:aws:iam::aws:policy/AmazonS3FullAccess" } + let(:policy_arn) { 'arn:aws:iam::aws:policy/AmazonS3FullAccess' } before(:all) do @iam_client = Aws::IAM::Client.new @user_name = "test-user-#{Time.now.to_i}" @iam_client.create_user(user_name: @user_name) - @policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess" + @policy_arn = 'arn:aws:iam::aws:policy/AmazonS3FullAccess' @manager = UserPolicyManager.new(@iam_client) end @@ -22,12 +22,11 @@ @iam_client.delete_user(user_name: @user_name) end - it "attaches a policy to a user" do + it 'attaches a policy to a user' do expect(@manager.attach_policy_to_user(@user_name, @policy_arn)).to be true end - it "detaches a policy from a user" do + it 'detaches a policy from a user' do expect(@manager.detach_user_policy(@user_name, @policy_arn)).to be true end - end diff --git a/ruby/example_code/iam/spec/get_account_password_policy_spec.rb b/ruby/example_code/iam/spec/get_account_password_policy_spec.rb index 4031395e3bb..973ed4436da 100644 --- a/ruby/example_code/iam/spec/get_account_password_policy_spec.rb +++ b/ruby/example_code/iam/spec/get_account_password_policy_spec.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../get_account_password_policy" -require "aws-sdk-iam" +require 'rspec' +require_relative '../get_account_password_policy' +require 'aws-sdk-iam' describe PasswordPolicyManager do before(:each) do @@ -10,15 +10,15 @@ @iam_policy_manager = PasswordPolicyManager.new(@iam_client) end - describe "#print_account_password_policy" do - context "when the account has a password policy" do - it "logs the password policy details" do + describe '#print_account_password_policy' do + context 'when the account has a password policy' do + it 'logs the password policy details' do expect { @iam_policy_manager.print_account_password_policy }.not_to raise_error end end - context "when the account does not have a password policy" do - it "logs a specific message" do + context 'when the account does not have a password policy' do + it 'logs a specific message' do expect { @iam_policy_manager.print_account_password_policy }.not_to raise_error end end diff --git a/ruby/example_code/iam/spec/list_admins_spec.rb b/ruby/example_code/iam/spec/list_admins_spec.rb index d21db7f9b4b..7e26282a122 100644 --- a/ruby/example_code/iam/spec/list_admins_spec.rb +++ b/ruby/example_code/iam/spec/list_admins_spec.rb @@ -1,38 +1,39 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require_relative("../list_admins") -require "rspec" +require 'aws-sdk-iam' +require_relative('../list_admins') +require 'rspec' describe AdminPrivilegeManager do let(:iam_client) { Aws::IAM::Client.new } let(:admin_privilege_manager) { AdminPrivilegeManager.new(iam_client) } - describe "#has_admin_privileges?" do - context "when the entity is a user with admin privileges" do - it "returns true" do - user = iam_client.create_user(user_name: "test_admin_user").user + describe '#has_admin_privileges?' do + context 'when the entity is a user with admin privileges' do + it 'returns true' do + user = iam_client.create_user(user_name: 'test_admin_user').user iam_client.attach_user_policy({ - policy_arn: "arn:aws:iam::aws:policy/AdministratorAccess", # Use the correct ARN for the admin policy - user_name: user.user_name, + policy_arn: 'arn:aws:iam::aws:policy/AdministratorAccess', + # Use the correct ARN for the admin policy + user_name: user.user_name }) expect(admin_privilege_manager.has_admin_privileges?(user)).to eq(true) # Detach the policy and delete the user after the test iam_client.detach_user_policy({ - policy_arn: "arn:aws:iam::aws:policy/AdministratorAccess", - user_name: user.user_name, + policy_arn: 'arn:aws:iam::aws:policy/AdministratorAccess', + user_name: user.user_name }) - iam_client.delete_user({user_name: user.user_name}) + iam_client.delete_user({ user_name: user.user_name }) end end - context "when the entity is a user without admin privileges" do - it "returns false" do - user = iam_client.create_user(user_name: "test_non_admin_user").user + context 'when the entity is a user without admin privileges' do + it 'returns false' do + user = iam_client.create_user(user_name: 'test_non_admin_user').user expect(admin_privilege_manager.has_admin_privileges?(user)).to eq(false) - iam_client.delete_user({user_name: user.user_name}) # Cleanup after test + iam_client.delete_user({ user_name: user.user_name }) # Cleanup after test end end end diff --git a/ruby/example_code/iam/spec/list_groups_spec.rb b/ruby/example_code/iam/spec/list_groups_spec.rb index b3c66762ce3..d7de9a78d27 100644 --- a/ruby/example_code/iam/spec/list_groups_spec.rb +++ b/ruby/example_code/iam/spec/list_groups_spec.rb @@ -1,14 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../list_groups" +require 'rspec' +require_relative '../list_groups' describe IamGroupManager do let(:iam_client) { Aws::IAM::Client.new } let(:iam_group_manager) { IamGroupManager.new(iam_client) } - describe "#list_groups" do - it "lists up to a specified number of groups without raising an error" do + describe '#list_groups' do + it 'lists up to a specified number of groups without raising an error' do expect { iam_group_manager.list_groups(10) }.not_to raise_error end end diff --git a/ruby/example_code/iam/spec/list_saml_providers_spec.rb b/ruby/example_code/iam/spec/list_saml_providers_spec.rb index 9595b3bd1c9..cd26d4c3253 100644 --- a/ruby/example_code/iam/spec/list_saml_providers_spec.rb +++ b/ruby/example_code/iam/spec/list_saml_providers_spec.rb @@ -1,14 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative("../list_saml_providers") +require 'rspec' +require_relative('../list_saml_providers') describe SamlProviderLister do let(:iam_client) { Aws::IAM::Client.new } let(:manager) { SamlProviderLister.new(iam_client) } - describe "#list_saml_providers" do - it "logs the ARNs of up to the specified number of SAML providers" do + describe '#list_saml_providers' do + it 'logs the ARNs of up to the specified number of SAML providers' do expect { manager.list_saml_providers(10) }.not_to raise_error end end diff --git a/ruby/example_code/iam/spec/manage_access_keys_spec.rb b/ruby/example_code/iam/spec/manage_access_keys_spec.rb index 4d4ff57e896..605b6c463dc 100644 --- a/ruby/example_code/iam/spec/manage_access_keys_spec.rb +++ b/ruby/example_code/iam/spec/manage_access_keys_spec.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require_relative("../manage_access_keys") -require "rspec" +require 'aws-sdk-iam' +require_relative('../manage_access_keys') +require 'rspec' describe AccessKeyManager do before(:all) do @@ -16,7 +16,7 @@ @iam_client.delete_user(user_name: @user_name) end - it "creates and deletes an access key for a user" do + it 'creates and deletes an access key for a user' do access_key = @manager.create_access_key(@user_name) expect(access_key).not_to be_nil diff --git a/ruby/example_code/iam/spec/manage_account_aliases_spec.rb b/ruby/example_code/iam/spec/manage_account_aliases_spec.rb index 9a9d867eb14..955981e8e26 100644 --- a/ruby/example_code/iam/spec/manage_account_aliases_spec.rb +++ b/ruby/example_code/iam/spec/manage_account_aliases_spec.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require_relative "../manage_account_aliases" -require "rspec" +require 'aws-sdk-iam' +require_relative '../manage_account_aliases' +require 'rspec' describe IAMAliasManager do before(:each) do @@ -19,15 +19,15 @@ @iam_client.delete_account_alias(account_alias: @account_alias) if existing_aliases.include?(@account_alias) end - describe "#create_account_alias", :integ do - it "creates an account alias successfully" do + describe '#create_account_alias', :integ do + it 'creates an account alias successfully' do expect(@manager.create_account_alias(@account_alias)).to be true expect(@iam_client.list_account_aliases.account_aliases).to include(@account_alias) end end - describe "#delete_account_alias", :integ do - it "deletes an account alias successfully" do + describe '#delete_account_alias', :integ do + it 'deletes an account alias successfully' do @manager.create_account_alias(@account_alias) expect(@manager.delete_account_alias(@account_alias)).to be true expect(@iam_client.list_account_aliases.account_aliases).not_to include(@account_alias) diff --git a/ruby/example_code/iam/spec/manage_roles_spec.rb b/ruby/example_code/iam/spec/manage_roles_spec.rb index ef329151f20..ad7bd078905 100644 --- a/ruby/example_code/iam/spec/manage_roles_spec.rb +++ b/ruby/example_code/iam/spec/manage_roles_spec.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require "rspec" -require_relative "../manage_roles" +require 'aws-sdk-iam' +require 'rspec' +require_relative '../manage_roles' describe RoleManager do before(:all) do @@ -10,50 +10,51 @@ @role_manager = RoleManager.new(@iam_client) @role_name = "rspec-test-role-#{Time.now.to_i}" @assume_role_policy_document = { - "Version" => "2012-10-17", - "Statement" => [ + 'Version' => '2012-10-17', + 'Statement' => [ { - "Effect" => "Allow", - "Principal" => { "Service" => "ec2.amazonaws.com" }, - "Action" => "sts:AssumeRole" + 'Effect' => 'Allow', + 'Principal' => { 'Service' => 'ec2.amazonaws.com' }, + 'Action' => 'sts:AssumeRole' } ] } - @policy_arns = ["arn:aws:iam::aws:policy/ReadOnlyAccess"] + @policy_arns = ['arn:aws:iam::aws:policy/ReadOnlyAccess'] end - describe "#create_role" do - it "creates a role and returns its ARN" do + describe '#create_role' do + it 'creates a role and returns its ARN' do role_arn = @role_manager.create_role(@role_name, @assume_role_policy_document, @policy_arns) expect(role_arn).to be_a(String) - expect(role_arn).to include("arn:aws:iam::") + expect(role_arn).to include('arn:aws:iam::') end end - describe "#list_roles" do - it "lists available roles" do + describe '#list_roles' do + it 'lists available roles' do roles = @role_manager.list_roles(1000) # Adjust count as necessary expect(roles).to include(@role_name) end end - describe "#get_role" do - it "retrieves data about a specific role" do + describe '#get_role' do + it 'retrieves data about a specific role' do role = @role_manager.get_role(@role_name) expect(role).to be_a(Aws::IAM::Types::Role) expect(role.role_name).to eq(@role_name) end end - describe "#delete_role" do - it "deletes a specified role" do + describe '#delete_role' do + it 'deletes a specified role' do expect { @role_manager.delete_role(@role_name) }.not_to raise_error end end - describe "#create_service_linked_role" do - it "creates a service-linked role and returns its name" do - role_name = @role_manager.create_service_linked_role("autoscaling.amazonaws.com", "Role for AutoScaling services", "test-#{Time.now.to_i}") + describe '#create_service_linked_role' do + it 'creates a service-linked role and returns its name' do + role_name = @role_manager.create_service_linked_role('autoscaling.amazonaws.com', + 'Role for AutoScaling services', "test-#{Time.now.to_i}") expect(role_name).not_to be_nil @role_manager.delete_service_linked_role(role_name) end diff --git a/ruby/example_code/iam/spec/manage_server_certificates_spec.rb b/ruby/example_code/iam/spec/manage_server_certificates_spec.rb index 3e6f288daf6..dd5489086ac 100644 --- a/ruby/example_code/iam/spec/manage_server_certificates_spec.rb +++ b/ruby/example_code/iam/spec/manage_server_certificates_spec.rb @@ -1,8 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-iam" -require_relative "../manage_server_certificates" -require "rspec" +require 'aws-sdk-iam' +require_relative '../manage_server_certificates' +require 'rspec' describe ServerCertificateManager do before(:each) do @@ -10,8 +10,8 @@ @manager = ServerCertificateManager.new(@iam_client) end - describe "#list_server_certificate_names", :integ do - it "logs server certificate names" do + describe '#list_server_certificate_names', :integ do + it 'logs server certificate names' do expect { @manager.list_server_certificate_names }.not_to raise_error end end diff --git a/ruby/example_code/iam/spec/manage_users_spec.rb b/ruby/example_code/iam/spec/manage_users_spec.rb index 37bc1a131cd..58d5e243515 100644 --- a/ruby/example_code/iam/spec/manage_users_spec.rb +++ b/ruby/example_code/iam/spec/manage_users_spec.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative("../manage_users") +require 'rspec' +require_relative('../manage_users') describe UserManager do before(:each) do @@ -9,26 +9,24 @@ @logger = Logger.new($stdout) @user_manager = UserManager.new(@iam_client, @logger) @user_name = "test-user-#{SecureRandom.hex(4)}" - @initial_password = "TestPa$$w0rd!" + @initial_password = 'TestPa$$w0rd!' end after(:each) do - begin - @user_manager.delete_user(@user_name) - rescue => e - @logger.error("Cleanup failed: #{e.message}") - end + @user_manager.delete_user(@user_name) + rescue StandardError => e + @logger.error("Cleanup failed: #{e.message}") end - describe "#create_user" do - it "creates a new IAM user" do + describe '#create_user' do + it 'creates a new IAM user' do user_id = @user_manager.create_user(@user_name, @initial_password) expect(user_id).not_to be_nil end end - describe "#get_user" do - it "retrieves details of an existing user" do + describe '#get_user' do + it 'retrieves details of an existing user' do @user_manager.create_user(@user_name, @initial_password) user = @user_manager.get_user(@user_name) expect(user).not_to be_nil @@ -36,8 +34,8 @@ end end - describe "#list_users" do - it "lists all IAM users" do + describe '#list_users' do + it 'lists all IAM users' do @user_manager.create_user(@user_name, @initial_password) users = @user_manager.list_users expect(users.any? { |u| u.user_name == @user_name }).to be true diff --git a/ruby/example_code/iam/spec/scenario_users_spec.rb b/ruby/example_code/iam/spec/scenario_users_spec.rb index bcaafe4eaae..63e6c05afb9 100644 --- a/ruby/example_code/iam/spec/scenario_users_spec.rb +++ b/ruby/example_code/iam/spec/scenario_users_spec.rb @@ -1,17 +1,16 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../scenario_users" +require 'rspec' +require_relative '../scenario_users' -describe "create user assume role scenario" do - context "runs against AWS (integration tests)", integ: true do - - it "runs without errors", quarantine: true do +describe 'create user assume role scenario' do + context 'runs against AWS (integration tests)', integ: true do + it 'runs without errors', quarantine: true do iam_client = Aws::IAM::Client.new scenario = ScenarioCreateUserAssumeRole.new(iam_client) - expect { run_scenario(scenario) }.not_to output("/Something went wrong with the demo/").to_stdout + expect { run_scenario(scenario) }.not_to output('/Something went wrong with the demo/').to_stdout end end end diff --git a/ruby/example_code/kms/create_key.rb b/ruby/example_code/kms/create_key.rb index b6c9c8ba938..51c7da2ea2f 100644 --- a/ruby/example_code/kms/create_key.rb +++ b/ruby/example_code/kms/create_key.rb @@ -9,7 +9,7 @@ # snippet-start:[kms.ruby.createKey] -require "aws-sdk-kms" # v2: require 'aws-sdk' +require 'aws-sdk-kms' # v2: require 'aws-sdk' # Create a AWS KMS key. # As long we are only encrypting small amounts of data (4 KiB or less) directly, @@ -22,8 +22,8 @@ resp = client.create_key({ tags: [ { - tag_key: "CreatedBy", - tag_value: "ExampleUser" + tag_key: 'CreatedBy', + tag_value: 'ExampleUser' } ] }) diff --git a/ruby/example_code/kms/decrypt_data.rb b/ruby/example_code/kms/decrypt_data.rb index 836f7b53bcc..f0cdbfbeea7 100644 --- a/ruby/example_code/kms/decrypt_data.rb +++ b/ruby/example_code/kms/decrypt_data.rb @@ -9,19 +9,19 @@ # snippet-start:[kms.ruby.decryptBlob] -require "aws-sdk-kms" # v2: require 'aws-sdk' +require 'aws-sdk-kms' # v2: require 'aws-sdk' # Decrypted blob -blob = "01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1" -blob_packed = [blob].pack("H*") +blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1' +blob_packed = [blob].pack('H*') -client = Aws::KMS::Client.new(region: "us-west-2") +client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.decrypt({ ciphertext_blob: blob_packed }) -puts "Raw text: " +puts 'Raw text: ' puts resp.plaintext # snippet-end:[kms.ruby.decryptBlob] diff --git a/ruby/example_code/kms/encrypt_data.rb b/ruby/example_code/kms/encrypt_data.rb index 4fae36b9cdf..63109630c35 100644 --- a/ruby/example_code/kms/encrypt_data.rb +++ b/ruby/example_code/kms/encrypt_data.rb @@ -6,24 +6,24 @@ # using Amazon Key Management Services (AWS KMS) using the AWS SDK for Ruby. # snippet-start:[kms.ruby.encryptBlob] -require "aws-sdk-kms" # v2: require 'aws-sdk' +require 'aws-sdk-kms' # v2: require 'aws-sdk' # ARN of the AWS KMS key. # # Replace the fictitious key ARN with a valid key ID -keyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" +keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab' -text = "1234567890" +text = '1234567890' -client = Aws::KMS::Client.new(region: "us-west-2") +client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.encrypt({ - key_id: keyId, - plaintext: text, -}) + key_id: keyId, + plaintext: text + }) # Display a readable version of the resulting encrypted blob. -puts "Blob:" -puts resp.ciphertext_blob.unpack("H*") +puts 'Blob:' +puts resp.ciphertext_blob.unpack('H*') # snippet-end:[kms.ruby.encryptBlob] diff --git a/ruby/example_code/kms/re_encrypt_data.rb b/ruby/example_code/kms/re_encrypt_data.rb index fc21e1edcfe..351cbaef5fd 100644 --- a/ruby/example_code/kms/re_encrypt_data.rb +++ b/ruby/example_code/kms/re_encrypt_data.rb @@ -8,25 +8,25 @@ # snippet-start:[kms.ruby.reEncryptData] -require "aws-sdk-kms" # v2: require 'aws-sdk' +require 'aws-sdk-kms' # v2: require 'aws-sdk' # Human-readable version of the ciphertext of the data to reencrypt. -blob = "01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1" -sourceCiphertextBlob = [blob].pack("H*") +blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1' +sourceCiphertextBlob = [blob].pack('H*') # Replace the fictitious key ARN with a valid key ID -destinationKeyId = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321" +destinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321' -client = Aws::KMS::Client.new(region: "us-west-2") +client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.re_encrypt({ - ciphertext_blob: sourceCiphertextBlob, - destination_key_id: destinationKeyId -}) + ciphertext_blob: sourceCiphertextBlob, + destination_key_id: destinationKeyId + }) # Display a readable version of the resulting re-encrypted blob. -puts "Blob:" -puts resp.ciphertext_blob.unpack("H*") +puts 'Blob:' +puts resp.ciphertext_blob.unpack('H*') # snippet-end:[kms.ruby.reEncryptData] diff --git a/ruby/example_code/lambda/README.md b/ruby/example_code/lambda/README.md index ca247c9783e..3234386e8ae 100644 --- a/ruby/example_code/lambda/README.md +++ b/ruby/example_code/lambda/README.md @@ -38,13 +38,13 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `ruby` Code excerpts that show you how to call individual service functions. -- [CreateFunction](lambda_basics.rb#L127) -- [DeleteFunction](lambda_basics.rb#L277) -- [GetFunction](lambda_basics.rb#L110) -- [Invoke](lambda_basics.rb#L164) -- [ListFunctions](lambda_basics.rb#L262) -- [UpdateFunctionCode](lambda_basics.rb#L237) -- [UpdateFunctionConfiguration](lambda_basics.rb#L212) +- [CreateFunction](lambda_basics.rb#L131) +- [DeleteFunction](lambda_basics.rb#L281) +- [GetFunction](lambda_basics.rb#L114) +- [Invoke](lambda_basics.rb#L166) +- [ListFunctions](lambda_basics.rb#L266) +- [UpdateFunctionCode](lambda_basics.rb#L241) +- [UpdateFunctionConfiguration](lambda_basics.rb#L216) ### Scenarios diff --git a/ruby/example_code/lambda/lambda_basics.rb b/ruby/example_code/lambda/lambda_basics.rb index 1205ff00830..5d6b663a1ea 100644 --- a/ruby/example_code/lambda/lambda_basics.rb +++ b/ruby/example_code/lambda/lambda_basics.rb @@ -3,24 +3,23 @@ # frozen_string_literal: true -require "aws-sdk-lambda" -require "aws-sdk-s3" -require "aws-sdk-iam" -require "aws-sdk-cloudwatchlogs" -require "logger" -require "json" -require "zip" - -$cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: "us-east-1") -$iam_client = Aws::IAM::Client.new(region: "us-east-1") +require 'aws-sdk-lambda' +require 'aws-sdk-s3' +require 'aws-sdk-iam' +require 'aws-sdk-cloudwatchlogs' +require 'logger' +require 'json' +require 'zip' # snippet-start:[ruby.example_code.ruby.LambdaWrapper.full] # snippet-start:[ruby.example_code.ruby.LambdaWrapper.decl] class LambdaWrapper - attr_accessor :lambda_client + attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new + @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') + @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end @@ -33,75 +32,80 @@ def initialize # @param action: Whether to create or destroy the IAM apparatus. # @return: The IAM role. def manage_iam(iam_role_name, action) + case action + when 'create' + create_iam_role(iam_role_name) + when 'destroy' + destroy_iam_role(iam_role_name) + else + raise "Incorrect action provided. Must provide 'create' or 'destroy'" + end + end + + private + + def create_iam_role(iam_role_name) role_policy = { - 'Version': "2012-10-17", + 'Version': '2012-10-17', 'Statement': [ { - 'Effect': "Allow", - 'Principal': { - 'Service': "lambda.amazonaws.com" - }, - 'Action': "sts:AssumeRole" + 'Effect': 'Allow', + 'Principal': { 'Service': 'lambda.amazonaws.com' }, + 'Action': 'sts:AssumeRole' } ] } - case action - when "create" - role = $iam_client.create_role( - role_name: iam_role_name, - assume_role_policy_document: role_policy.to_json - ) - $iam_client.attach_role_policy( - { - policy_arn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", - role_name: iam_role_name - } - ) - $iam_client.wait_until(:role_exists, { role_name: iam_role_name }) do |w| - w.max_attempts = 5 - w.delay = 5 - end - @logger.debug("Successfully created IAM role: #{role['role']['arn']}") - @logger.debug("Enforcing a 10-second sleep to allow IAM role to activate fully.") - sleep(10) - return role, role_policy.to_json - when "destroy" - $iam_client.detach_role_policy( - { - policy_arn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", - role_name: iam_role_name - } - ) - $iam_client.delete_role( + role = @iam_client.create_role( + role_name: iam_role_name, + assume_role_policy_document: role_policy.to_json + ) + @iam_client.attach_role_policy( + { + policy_arn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole', role_name: iam_role_name - ) - @logger.debug("Detached policy & deleted IAM role: #{iam_role_name}") - else - raise "Incorrect action provided. Must provide 'create' or 'destroy'" + } + ) + wait_for_role_to_exist(iam_role_name) + @logger.debug("Successfully created IAM role: #{role['role']['arn']}") + sleep(10) + [role, role_policy.to_json] + end + + def destroy_iam_role(iam_role_name) + @iam_client.detach_role_policy( + { + policy_arn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole', + role_name: iam_role_name + } + ) + @iam_client.delete_role(role_name: iam_role_name) + @logger.debug("Detached policy & deleted IAM role: #{iam_role_name}") + end + + def wait_for_role_to_exist(iam_role_name) + @iam_client.wait_until(:role_exists, { role_name: iam_role_name }) do |w| + w.max_attempts = 5 + w.delay = 5 end - rescue Aws::Lambda::Errors::ServiceException => e - @logger.error("There was an error creating role or attaching policy:\n #{e.message}") end # snippet-end:[ruby.example_code.lambda.setup_iam] # snippet-start:[ruby.example_code.lambda.create_deployment_package] # Creates a Lambda deployment package in .zip format. - # This zip can be passed directly as a string to Lambda when creating the function. # # @param source_file: The name of the object, without suffix, for the Lambda file and zip. # @return: The deployment package. def create_deployment_package(source_file) Dir.chdir(File.dirname(__FILE__)) - if File.exist?("lambda_function.zip") - File.delete("lambda_function.zip") - @logger.debug("Deleting old zip: lambda_function.zip") + if File.exist?('lambda_function.zip') + File.delete('lambda_function.zip') + @logger.debug('Deleting old zip: lambda_function.zip') + end + Zip::File.open('lambda_function.zip', create: true) do |zipfile| + zipfile.add('lambda_function.rb', "#{source_file}.rb") end - Zip::File.open("lambda_function.zip", create: true) { - |zipfile| - zipfile.add("lambda_function.rb", "#{source_file}.rb") - } @logger.debug("Zipping #{source_file}.rb into: lambda_function.zip.") - File.read("lambda_function.zip").to_s + File.read('lambda_function.zip').to_s rescue StandardError => e @logger.error("There was an error creating deployment package:\n #{e.message}") end @@ -128,28 +132,26 @@ def get_function(function_name) # Deploys a Lambda function. # # @param function_name: The name of the Lambda function. - # @param handler_name: The fully qualified name of the handler function. This - # must include the file name and the function name. + # @param handler_name: The fully qualified name of the handler function. # @param role_arn: The IAM role to use for the function. - # @param deployment_package: The deployment package that contains the function - # code in .zip format. + # @param deployment_package: The deployment package that contains the function code in .zip format. # @return: The Amazon Resource Name (ARN) of the newly created function. def create_function(function_name, handler_name, role_arn, deployment_package) response = @lambda_client.create_function({ role: role_arn.to_s, function_name: function_name, handler: handler_name, - runtime: "ruby2.7", + runtime: 'ruby2.7', code: { zip_file: deployment_package }, environment: { variables: { - "LOG_LEVEL" => "info" + 'LOG_LEVEL' => 'info' } } }) - @lambda_client.wait_until(:function_active_v2, { function_name: function_name}) do |w| + @lambda_client.wait_until(:function_active_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end @@ -167,7 +169,7 @@ def create_function(function_name, handler_name, role_arn, deployment_package) # @param payload [nil] Payload containing runtime parameters. # @return [Object] The response from the function invocation. def invoke_function(function_name, payload = nil) - params = { function_name: function_name} + params = { function_name: function_name } params[:payload] = payload unless payload.nil? @lambda_client.invoke(params) rescue Aws::Lambda::Errors::ServiceException => e @@ -175,30 +177,32 @@ def invoke_function(function_name, payload = nil) end # snippet-end:[ruby.example_code.lambda.Invoke] + # snippet-start:[ruby.example_code.lambda.GetLogs] # Get function logs from the latest Amazon CloudWatch log stream. # @param function_name [String] The name of the function. # @param string_match [String] A string to look for in the logs. # @return all_logs [Array] An array of all the log messages found for that stream. def get_cloudwatch_logs(function_name, string_match) - @logger.debug("Enforcing a 10 second sleep to allow CloudWatch logs to appear.") + @logger.debug('Enforcing a 10 second sleep to allow CloudWatch logs to appear.') sleep(10) - streams = $cloudwatch_client.describe_log_streams({ log_group_name: "/aws/lambda/#{function_name}" }) - streams["log_streams"].each do |x| - resp = $cloudwatch_client.get_log_events({ + streams = @cloudwatch_client.describe_log_streams({ log_group_name: "/aws/lambda/#{function_name}" }) + streams['log_streams'].each do |log_stream| + resp = @cloudwatch_client.get_log_events({ log_group_name: "/aws/lambda/#{function_name}", - log_stream_name: x["log_stream_name"] + log_stream_name: log_stream['log_stream_name'] }) - resp.events.each do |x| - if "/#{x.message}/".match(string_match) - msg = x.message.split(" -- : ")[1].green - puts "CloudWatch log stream: #{msg}" - return msg - end + resp.events.each do |event| + next unless "/#{event.message}/".match(string_match) + + msg = event.message.split(' -- : ')[1].green + puts "CloudWatch log stream: #{msg}" + return msg end end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error fetching CloudWatch logs:\n #{e.message}") end + # snippet-end:[ruby.example_code.lambda.GetLogs] def invoke_and_verify(function_name, log_statement, payload = nil) response = invoke_function(function_name, payload) @@ -219,11 +223,11 @@ def update_function_configuration(function_name, log_level) function_name: function_name, environment: { variables: { - "LOG_LEVEL" => log_level + 'LOG_LEVEL' => log_level } } }) - @lambda_client.wait_until(:function_updated_v2, { function_name: function_name}) do |w| + @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end @@ -237,7 +241,7 @@ def update_function_configuration(function_name, log_level) # snippet-start:[ruby.example_code.lambda.UpdateFunctionCode] # Updates the code for a Lambda function by submitting a .zip archive that contains # the code for the function. - + # # @param function_name: The name of the function to update. # @param deployment_package: The function code to update, packaged as bytes in # .zip format. @@ -247,7 +251,7 @@ def update_function_code(function_name, deployment_package) function_name: function_name, zip_file: deployment_package ) - @lambda_client.wait_until(:function_updated_v2, { function_name: function_name}) do |w| + @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end @@ -264,13 +268,13 @@ def update_function_code(function_name, deployment_package) def list_functions functions = [] @lambda_client.list_functions.each do |response| - response["functions"].each do |function| - functions.append(function["function_name"]) + response['functions'].each do |function| + functions.append(function['function_name']) end end functions rescue Aws::Lambda::Errors::ServiceException => e - @logger.error("There was an error executing #{function_name}:\n #{e.message}") + @logger.error("There was an error listing functions:\n #{e.message}") end # snippet-end:[ruby.example_code.lambda.ListFunctions] @@ -282,10 +286,10 @@ def delete_function(function_name) @lambda_client.delete_function( function_name: function_name ) - print "Done!".green + print 'Done!'.green rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error deleting #{function_name}:\n #{e.message}") end # snippet-end:[ruby.example_code.lambda.DeleteFunction] - # snippet-end:[ruby.example_code.ruby.LambdaWrapper.full] end +# snippet-end:[ruby.example_code.ruby.LambdaWrapper.full] diff --git a/ruby/example_code/lambda/lambda_function.rb b/ruby/example_code/lambda/lambda_function.rb index 0f51a2512d0..b7cd913ed40 100644 --- a/ruby/example_code/lambda/lambda_function.rb +++ b/ruby/example_code/lambda/lambda_function.rb @@ -4,7 +4,7 @@ # frozen_string_literal: true # snippet-start:[ruby.example_code.lambda.handler.increment] -require "logger" +require 'logger' # A function that increments a whole number by one (1) and logs the result. # Requires a manually-provided runtime parameter, 'number', which must be Int @@ -15,18 +15,18 @@ # @return incremented_number [String] The incremented number. def lambda_handler(event:, context:) logger = Logger.new($stdout) - log_level = ENV["LOG_LEVEL"] + log_level = ENV['LOG_LEVEL'] logger.level = case log_level - when "debug" + when 'debug' Logger::DEBUG - when "info" + when 'info' Logger::INFO else Logger::ERROR end - logger.debug("This is a debug log message.") - logger.info("This is an info log message. Code executed successfully!") - number = event["number"].to_i + logger.debug('This is a debug log message.') + logger.info('This is an info log message. Code executed successfully!') + number = event['number'].to_i incremented_number = number + 1 logger.info("You provided #{number.round} and it was incremented to #{incremented_number.round}") incremented_number.round.to_s diff --git a/ruby/example_code/lambda/lambda_function_updated.rb b/ruby/example_code/lambda/lambda_function_updated.rb index b1e9f798016..9aa26de89e6 100644 --- a/ruby/example_code/lambda/lambda_function_updated.rb +++ b/ruby/example_code/lambda/lambda_function_updated.rb @@ -4,7 +4,7 @@ # frozen_string_literal: true # snippet-start:[ruby.example_code.lambda.handler.multiply] -require "logger" +require 'logger' # A function that multiplies two whole numbers and logs the result. # Requires two whole numbers provided at runtime: 'first_number' and 'second_number'. @@ -15,18 +15,18 @@ # @ return product [String] The product of the two numbers. def lambda_handler(event:, context:) logger = Logger.new($stdout) - log_level = ENV["LOG_LEVEL"] + log_level = ENV['LOG_LEVEL'] logger.level = case log_level - when "debug" + when 'debug' Logger::DEBUG - when "info" + when 'info' Logger::INFO else Logger::ERROR end - first_number = event["first_number"].to_f - second_number = event["second_number"].to_f + first_number = event['first_number'].to_f + second_number = event['second_number'].to_f product = first_number.round * second_number.round logger.info("The product of #{first_number.round} and #{second_number.round} is #{product} ") product.to_s diff --git a/ruby/example_code/lambda/scenario_getting_started_functions.rb b/ruby/example_code/lambda/scenario_getting_started_functions.rb index a949ffa1ab7..34487259d48 100644 --- a/ruby/example_code/lambda/scenario_getting_started_functions.rb +++ b/ruby/example_code/lambda/scenario_getting_started_functions.rb @@ -7,17 +7,17 @@ # For more information, see: # https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/ruby/README.md -require "aws-sdk-lambda" -require "aws-sdk-cloudwatchlogs" -require "aws-sdk-iam" -require "logger" -require "json" -require "zip" -require "cli/ui" -require_relative("../../helpers/disclaimers") -require_relative("../../helpers/decorators") -require_relative("lambda_basics") -require_relative("lambda_function") +require 'aws-sdk-lambda' +require 'aws-sdk-cloudwatchlogs' +require 'aws-sdk-iam' +require 'logger' +require 'json' +require 'zip' +require 'cli/ui' +require_relative('../../helpers/disclaimers') +require_relative('../../helpers/decorators') +require_relative('lambda_basics') +require_relative('lambda_function') @logger = Logger.new($stdout) @logger.level = Logger::WARN @@ -28,92 +28,92 @@ # @return [nil] def run_scenario banner - puts "######################################################################################################".yellow - puts "# #".yellow - puts "# EXAMPLE CODE DEMO: #".yellow - puts "# AWS Lambda #".yellow - puts "# #".yellow - puts "######################################################################################################".yellow - puts "" - puts "You have launched a demo of AWS Lambda using the AWS for Ruby v3 SDK. Over the next 60 seconds, it will" - puts "do the following:" - puts " 1. Create a basic IAM role and policy for Lambda invocation." - puts " 2. Create a new Lambda function." - puts " 3. Invoke the Lambda function." - puts " 4. Update the Lambda function code." - puts " 5. Update the Lambda function configuration." - puts " 6. Destroy the Lambda function and associated IAM role." - puts "" + puts '######################################################################################################'.yellow + puts '# #'.yellow + puts '# EXAMPLE CODE DEMO: #'.yellow + puts '# AWS Lambda #'.yellow + puts '# #'.yellow + puts '######################################################################################################'.yellow + puts '' + puts 'You have launched a demo of AWS Lambda using the AWS for Ruby v3 SDK. Over the next 60 seconds, it will' + puts 'do the following:' + puts ' 1. Create a basic IAM role and policy for Lambda invocation.' + puts ' 2. Create a new Lambda function.' + puts ' 3. Invoke the Lambda function.' + puts ' 4. Update the Lambda function code.' + puts ' 5. Update the Lambda function configuration.' + puts ' 6. Destroy the Lambda function and associated IAM role.' + puts '' confirm_begin billing security puts "\e[H\e[2J" - source_file = "lambda_function" + source_file = 'lambda_function' custom_name = "lambda-function-#{rand(10**4)}" wrapper = LambdaWrapper.new - new_step(1, "Create IAM role and policy for Lambda") - print "Creating..." - role, policy = wrapper.manage_iam("#{custom_name}-role", "create") - role_arn = role["role"]["arn"] + new_step(1, 'Create IAM role and policy for Lambda') + print 'Creating...' + role, policy = wrapper.manage_iam("#{custom_name}-role", 'create') + role_arn = role['role']['arn'] print "Done!\n".green puts JSON.pretty_generate(role).green puts JSON.pretty_generate(policy).green - puts "-" * 88 + puts '-' * 88 - new_step(2, "Create new Lambda function") + new_step(2, 'Create new Lambda function') print "Let's create a function code to increment a number by 1..." if wrapper.get_function(custom_name).nil? print "No function exists called #{custom_name}! \nLet's create a deployment package..." deployment_package = wrapper.create_deployment_package(source_file) print "Done!\n".green if deployment_package - print "Uploading our deployment package to create the function..." + print 'Uploading our deployment package to create the function...' response = wrapper.create_function(custom_name, "#{source_file}.lambda_handler", role_arn, deployment_package) print "Done!\n".green puts JSON.pretty_generate(response).green end - new_step(3, "List all functions") + new_step(3, 'List all functions') print "Let's do a quick list of all functions in our account..." response = wrapper.list_functions print "Done!\n".green puts "Discovered #{response.count} functions: #{response}" - new_step(4, "Invoke the function") - response = CLI::UI::Prompt.ask("Please provide a whole number to increment by 1:") + new_step(4, 'Invoke the function') + response = CLI::UI::Prompt.ask('Please provide a whole number to increment by 1:') print "Attempting to invoke #{custom_name}..." payload = { number: response } - wrapper.invoke_and_verify(custom_name, "incremented", JSON.generate(payload)) + wrapper.invoke_and_verify(custom_name, 'incremented', JSON.generate(payload)) - new_step(5, "Update function configuration") + new_step(5, 'Update function configuration') print "Let's enable debugging within our function configuration..." - response = wrapper.update_function_configuration(custom_name, "debug") + response = wrapper.update_function_configuration(custom_name, 'debug') print "Done!\n".green if response puts JSON.pretty_generate(response).green print "Now let's invoke #{custom_name} again to see the impact of our changes..." - wrapper.invoke_and_verify(custom_name, "This is a debug log message") + wrapper.invoke_and_verify(custom_name, 'This is a debug log message') - new_step(6, "Update function code") + new_step(6, 'Update function code') print "Let's update our function code to multiply two whole numbers provided as invocation parameters..." new_deployment_package = wrapper.create_deployment_package("#{source_file}_updated") response = wrapper.update_function_code(custom_name, new_deployment_package) print "Done!\n".green if response puts JSON.pretty_generate(response).green print "Now let's invoke #{custom_name} again to see the impact of our changes...\n" - first_number = CLI::UI::Prompt.ask("Please provide a first whole number:") - second_number = CLI::UI::Prompt.ask("Please provide a second whole number:") + first_number = CLI::UI::Prompt.ask('Please provide a first whole number:') + second_number = CLI::UI::Prompt.ask('Please provide a second whole number:') payload = { first_number: first_number.to_i, second_number: second_number.to_i } - wrapper.invoke_and_verify(custom_name, "product", JSON.generate(payload)) + wrapper.invoke_and_verify(custom_name, 'product', JSON.generate(payload)) - new_step(7, "Delete function code") + new_step(7, 'Delete function code') print "That's a wrap! Destroying IAM role and function..." - wrapper.manage_iam("#{custom_name}-role", "destroy") + wrapper.manage_iam("#{custom_name}-role", 'destroy') print "Done!\n".green wrapper.delete_function(custom_name) print "Done!\n".green - puts "==========================================================================".yellow + puts '=========================================================================='.yellow end # snippet-end:[ruby.example_code.lambda.Scenario_GettingStartedFunctions] diff --git a/ruby/example_code/lambda/spec/scenario_getting_started_functions_spec.rb b/ruby/example_code/lambda/spec/scenario_getting_started_functions_spec.rb index cae5843c42a..cb7e3d980c0 100644 --- a/ruby/example_code/lambda/spec/scenario_getting_started_functions_spec.rb +++ b/ruby/example_code/lambda/spec/scenario_getting_started_functions_spec.rb @@ -3,72 +3,72 @@ # frozen_string_literal: true -require "json" -require "rspec" -require_relative "../../../helpers/disclaimers" -require_relative "../../../helpers/decorators" -require_relative "../lambda_basics" -require_relative "../lambda_function" +require 'json' +require 'rspec' +require_relative '../../../helpers/disclaimers' +require_relative '../../../helpers/decorators' +require_relative '../lambda_basics' +require_relative '../lambda_function' describe LambdaWrapper do - context "LambdaWrapper" do + context 'LambdaWrapper' do custom_name = "lambda-function-#{rand(10**4)}" - source_file = "lambda_function" + source_file = 'lambda_function' wrapper = LambdaWrapper.new # role, policy = wrapper.manage_iam("#{custom_name}-role", "create") - it "creates IAM role and attaches policy", integ: false do - expect(role["role"]["role_name"]).to eq("#{custom_name}-role") - expect(role["role"]["assume_role_policy_document"].to_s).to be_instance_of(String) + it 'creates IAM role and attaches policy', integ: false do + expect(role['role']['role_name']).to eq("#{custom_name}-role") + expect(role['role']['assume_role_policy_document'].to_s).to be_instance_of(String) end - it "creates a new deployment package", integ: false do + it 'creates a new deployment package', integ: false do deployment_package = wrapper.create_deployment_package(source_file) expect(deployment_package).to be_instance_of(String) end - it "creates new Lambda function", integ: false do + it 'creates new Lambda function', integ: false do deployment_package = wrapper.create_deployment_package(source_file) - response = wrapper.create_function(custom_name, "#{source_file}.lambda_handler", role["role"]["arn"], + response = wrapper.create_function(custom_name, "#{source_file}.lambda_handler", role['role']['arn'], deployment_package) - expect(response["function_name"]).to start_with(custom_name) + expect(response['function_name']).to start_with(custom_name) end - it "lists all Lambda functions", integ: false do + it 'lists all Lambda functions', integ: false do response = wrapper.list_functions expect(response.find { |item| item == custom_name }).to_not be_nil end - it "invokes the Lambda function", integ: false do - payload = { number: "2" } - log_statement = wrapper.invoke_and_verify(custom_name, "incremented", JSON.generate(payload)) - expect(log_statement).to include("You provided 2 and it was incremented to 3") + it 'invokes the Lambda function', integ: false do + payload = { number: '2' } + log_statement = wrapper.invoke_and_verify(custom_name, 'incremented', JSON.generate(payload)) + expect(log_statement).to include('You provided 2 and it was incremented to 3') end - it "updates the Lambda function configuration", integ: false do - response = wrapper.update_function_configuration(custom_name, "debug") - payload = { number: "2" } - log_statement = wrapper.invoke_and_verify(custom_name, "debug", JSON.generate(payload)) + it 'updates the Lambda function configuration', integ: false do + response = wrapper.update_function_configuration(custom_name, 'debug') + payload = { number: '2' } + log_statement = wrapper.invoke_and_verify(custom_name, 'debug', JSON.generate(payload)) puts log_statement expect(response).to be_truthy - expect(log_statement.to_s).to include("This is a debug log message") + expect(log_statement.to_s).to include('This is a debug log message') end - it "updates Lambda function code", integ: false do + it 'updates Lambda function code', integ: false do new_deployment_package = wrapper.create_deployment_package("#{source_file}_updated") response = wrapper.update_function_code(custom_name, new_deployment_package) payload = { first_number: 4, second_number: 4 } - log_statement = wrapper.invoke_and_verify(custom_name, "product", JSON.generate(payload)) + log_statement = wrapper.invoke_and_verify(custom_name, 'product', JSON.generate(payload)) expect(response).to be_truthy - expect(log_statement).to include("The product of 4 and 4 is 16") + expect(log_statement).to include('The product of 4 and 4 is 16') end - it "deletes Lambda function", integ: false do + it 'deletes Lambda function', integ: false do wrapper.delete_function(custom_name) end - it "deletes IAM role", integ: false do - wrapper.manage_iam("#{custom_name}-role", "destroy") + it 'deletes IAM role', integ: false do + wrapper.manage_iam("#{custom_name}-role", 'destroy') end end end diff --git a/ruby/example_code/polly/polly_describe_voices.rb b/ruby/example_code/polly/polly_describe_voices.rb index aea19eb436b..81573399282 100644 --- a/ruby/example_code/polly/polly_describe_voices.rb +++ b/ruby/example_code/polly/polly_describe_voices.rb @@ -7,7 +7,7 @@ # snippet-start:[polly.ruby.describeVoices] -require "aws-sdk-polly" # In v2: require 'aws-sdk' +require 'aws-sdk-polly' # In v2: require 'aws-sdk' begin # Create an Amazon Polly client using @@ -16,16 +16,16 @@ polly = Aws::Polly::Client.new # Get US English voices - resp = polly.describe_voices(language_code: "en-US") + resp = polly.describe_voices(language_code: 'en-US') resp.voices.each do |v| puts v.name - puts " " + v.gender + puts " #{v.gender}" puts end -rescue StandardError => ex - puts "Could not get voices" - puts "Error message:" - puts ex.message +rescue StandardError => e + puts 'Could not get voices' + puts 'Error message:' + puts e.message end # snippet-end:[polly.ruby.describeVoices] diff --git a/ruby/example_code/polly/polly_list_lexicons.rb b/ruby/example_code/polly/polly_list_lexicons.rb index 24c934e9e6f..584c52102b0 100644 --- a/ruby/example_code/polly/polly_list_lexicons.rb +++ b/ruby/example_code/polly/polly_list_lexicons.rb @@ -7,7 +7,7 @@ # snippet-start:[polly.ruby.listLexicons] -require "aws-sdk-polly" # In v2: require 'aws-sdk' +require 'aws-sdk-polly' # In v2: require 'aws-sdk' begin # Create an Amazon Polly client using @@ -19,13 +19,13 @@ resp.lexicons.each do |l| puts l.name - puts " Alphabet:" + l.attributes.alphabet - puts " Language:" + l.attributes.language + puts " Alphabet:#{l.attributes.alphabet}" + puts " Language:#{l.attributes.language}" puts end -rescue StandardError => ex - puts "Could not get lexicons" - puts "Error message:" - puts ex.message +rescue StandardError => e + puts 'Could not get lexicons' + puts 'Error message:' + puts e.message end # snippet-end:[polly.ruby.listLexicons] diff --git a/ruby/example_code/polly/polly_synthesize_speech.rb b/ruby/example_code/polly/polly_synthesize_speech.rb index 488e6b6675d..f47af9aead4 100644 --- a/ruby/example_code/polly/polly_synthesize_speech.rb +++ b/ruby/example_code/polly/polly_synthesize_speech.rb @@ -7,12 +7,12 @@ # snippet-start:[polly.ruby.synthesizeSpeech] -require "aws-sdk-polly" # In v2: require 'aws-sdk' +require 'aws-sdk-polly' # In v2: require 'aws-sdk' begin # Get the filename from the command line if ARGV.empty? - puts "You must supply a filename" + puts 'You must supply a filename' exit 1 end @@ -22,7 +22,7 @@ if File.exist?(filename) contents = IO.read(filename) else - puts "No such file: " + filename + puts "No such file: #{filename}" exit 1 end @@ -32,10 +32,10 @@ polly = Aws::Polly::Client.new resp = polly.synthesize_speech({ - output_format: "mp3", - text: contents, - voice_id: "Joanna", - }) + output_format: 'mp3', + text: contents, + voice_id: 'Joanna' + }) # Save output # Get just the file name @@ -43,16 +43,16 @@ name = File.basename(filename) # Split up name so we get just the xyz part - parts = name.split(".") + parts = name.split('.') first_part = parts[0] - mp3_file = first_part + ".mp3" + mp3_file = "#{first_part}.mp3" IO.copy_stream(resp.audio_stream, mp3_file) - puts "Wrote MP3 content to: " + mp3_file -rescue StandardError => ex - puts "Got error:" - puts "Error message:" - puts ex.message + puts "Wrote MP3 content to: #{mp3_file}" +rescue StandardError => e + puts 'Got error:' + puts 'Error message:' + puts e.message end # snippet-end:[polly.ruby.synthesizeSpeech] diff --git a/ruby/example_code/rds/create_cluster_snapshot.rb b/ruby/example_code/rds/create_cluster_snapshot.rb index 2e3bfbe2995..080179584c8 100644 --- a/ruby/example_code/rds/create_cluster_snapshot.rb +++ b/ruby/example_code/rds/create_cluster_snapshot.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.createClusterSnapshot] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # Create a snapshot of an Amazon Relational Database Service (Amazon RDS) # Multi-AZ DB cluster. @@ -21,7 +21,7 @@ def create_cluster_snapshot(rds_resource, multi_az_db_cluster) end # snippet-end:[rds.ruby.createClusterSnapshot] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Resource.new multi_az_db_cluster_name = "rds-#{rand(10**4)}-cluster" create_cluster_snapshot(rds_resource, multi_az_db_cluster_name) diff --git a/ruby/example_code/rds/create_snapshot.rb b/ruby/example_code/rds/create_snapshot.rb index 80c46907994..1f7030c1a6c 100644 --- a/ruby/example_code/rds/create_snapshot.rb +++ b/ruby/example_code/rds/create_snapshot.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.createDatabaseSnapshot] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # Create a snapshot for an Amazon Relational Database Service (Amazon RDS) # DB instance. @@ -20,7 +20,7 @@ def create_snapshot(rds_resource, db_instance_name) puts "Couldn't create DB instance snapshot #{id}:\n #{e.message}" end # snippet-end:[rds.ruby.createDatabaseSnapshot] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Resource.new db_instance_name = "rds-#{rand(10**4)}-instance" create_snapshot(rds_resource, db_instance_name) diff --git a/ruby/example_code/rds/list_cluster_snapshots.rb b/ruby/example_code/rds/list_cluster_snapshots.rb index 135e247feb0..8a17d867391 100644 --- a/ruby/example_code/rds/list_cluster_snapshots.rb +++ b/ruby/example_code/rds/list_cluster_snapshots.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.listClusterSnapshots] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # List snapshots for all Amazon Relational Database Service (Amazon RDS) # RDS clusters. @@ -26,7 +26,7 @@ def list_cluster_snapshots(rds_resource) end # snippet-end:[rds.ruby.listClusterSnapshots] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Resource.new test = list_cluster_snapshots(rds_resource) puts test diff --git a/ruby/example_code/rds/list_instance_snapshots.rb b/ruby/example_code/rds/list_instance_snapshots.rb index 7ce4f9b24e1..af63165659b 100644 --- a/ruby/example_code/rds/list_instance_snapshots.rb +++ b/ruby/example_code/rds/list_instance_snapshots.rb @@ -4,7 +4,7 @@ # frozen_string_literal: true # snippet-start:[rds.ruby.listInstanceSnapshots] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) DB instance # snapshots. diff --git a/ruby/example_code/rds/list_instances.rb b/ruby/example_code/rds/list_instances.rb index 6a94a2d4fe0..3c014d12496 100644 --- a/ruby/example_code/rds/list_instances.rb +++ b/ruby/example_code/rds/list_instances.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.listAllInstances] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) DB instances. # @@ -22,7 +22,7 @@ def list_instances(rds_resource) end # snippet-end:[rds.ruby.listAllInstances] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Client.new list_instances(rds_resource) end diff --git a/ruby/example_code/rds/list_parameter_groups.rb b/ruby/example_code/rds/list_parameter_groups.rb index 6e719d46c01..e83f4dd8edb 100644 --- a/ruby/example_code/rds/list_parameter_groups.rb +++ b/ruby/example_code/rds/list_parameter_groups.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.listParameterGroups] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) parameter groups. # @@ -22,7 +22,7 @@ def list_parameter_groups(rds_resource) end # snippet-end:[rds.ruby.listParameterGroups] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Resource.new list_parameter_groups(rds_resource) end diff --git a/ruby/example_code/rds/list_security_groups.rb b/ruby/example_code/rds/list_security_groups.rb index 3eed0dcc3fe..56fb7eecc58 100644 --- a/ruby/example_code/rds/list_security_groups.rb +++ b/ruby/example_code/rds/list_security_groups.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.listSecurityGroups] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) security groups. # @@ -16,7 +16,7 @@ def list_security_groups(rds_resource) security_groups.append({ "name": sg.db_security_group_name, "description": db_security_group_description, - "type": "db" + "type": 'db' }) end @@ -24,7 +24,7 @@ def list_security_groups(rds_resource) security_groups.append({ "name": vsg.vpc_security_group_id, "description": vsg.status, - "type": "vpc" + "type": 'vpc' }) end end @@ -34,7 +34,7 @@ def list_security_groups(rds_resource) end # snippet-end:[rds.ruby.listSecurityGroups] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Resource.new list_security_groups(rds_resource) end diff --git a/ruby/example_code/rds/list_subnet_groups.rb b/ruby/example_code/rds/list_subnet_groups.rb index 76159dbbef1..eae4884acb2 100644 --- a/ruby/example_code/rds/list_subnet_groups.rb +++ b/ruby/example_code/rds/list_subnet_groups.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[rds.ruby.listSubnetGroups] -require "aws-sdk-rds" # v2: require 'aws-sdk' +require 'aws-sdk-rds' # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) subnet groups. # @@ -22,7 +22,7 @@ def list_subnet_groups(rds_resource) end # snippet-end:[rds.ruby.listSubnetGroups] -if __FILE__ == $0 +if __FILE__ == $PROGRAM_NAME rds_resource = Aws::RDS::Resource.new list_subnet_groups(rds_resource) end diff --git a/ruby/example_code/rds/spec/rds_examples_spec.rb b/ruby/example_code/rds/spec/rds_examples_spec.rb index 688fddd5d58..6890d33dc5a 100644 --- a/ruby/example_code/rds/spec/rds_examples_spec.rb +++ b/ruby/example_code/rds/spec/rds_examples_spec.rb @@ -1,58 +1,58 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../create_snapshot" -require_relative "../create_cluster_snapshot" -require_relative "../list_cluster_snapshots" -require_relative "../list_security_groups" -require_relative "../list_instance_snapshots" -require_relative "../list_instances" -require_relative "../list_subnet_groups" -require_relative "../list_parameter_groups" - -describe "RDS example code" do +require 'rspec' +require_relative '../create_snapshot' +require_relative '../create_cluster_snapshot' +require_relative '../list_cluster_snapshots' +require_relative '../list_security_groups' +require_relative '../list_instance_snapshots' +require_relative '../list_instances' +require_relative '../list_subnet_groups' +require_relative '../list_parameter_groups' + +describe 'RDS example code' do let(:rds_resource) { Aws::RDS::Resource.new } - let(:multi_az_cluster) { "database-multi-az-cluster" } - let(:multi_az_instance) { "database-multi-az-instance" } - let(:instance) { "database-single" } + let(:multi_az_cluster) { 'database-multi-az-cluster' } + let(:multi_az_instance) { 'database-multi-az-instance' } + let(:instance) { 'database-single' } - it "list all instances" do + it 'list all instances' do instances = list_instances(rds_resource) expect(instances).not_to be_empty end - it "creates an instance snapshot" do + it 'creates an instance snapshot' do snapshot = create_snapshot(rds_resource, instance) puts expect(snapshot).to be_an_instance_of(Aws::RDS::DBSnapshot) end - it "creates a cluster snapshot" do + it 'creates a cluster snapshot' do db_cluster_snapshot = create_cluster_snapshot(rds_resource, multi_az_cluster) expect(db_cluster_snapshot).to be_an_instance_of(Aws::RDS::DBClusterSnapshot) end - it "lists all cluster snapshots" do + it 'lists all cluster snapshots' do cluster_snapshots = list_cluster_snapshots(rds_resource, multi_az_cluster) expect(cluster_snapshots).not_to be_empty end - it "lists all instance snapshots" do + it 'lists all instance snapshots' do snapshots = list_instance_snapshots(rds_resource) expect(snapshots).not_to be_empty end - it "lists parameter groups" do + it 'lists parameter groups' do parameter_groups = list_parameter_groups(rds_resource) expect(parameter_groups).not_to be_empty end - it "lists security groups" do + it 'lists security groups' do security_groups = list_security_groups(rds_resource) expect(security_groups).not_to be_empty end - it "lists subnet groups" do + it 'lists subnet groups' do subnet_groups = list_subnet_groups(rds_resource) expect(subnet_groups).not_to be_nil end diff --git a/ruby/example_code/s3/auth_federation_token_request_test.rb b/ruby/example_code/s3/auth_federation_token_request_test.rb index fa2a2feed87..e5cd79042ed 100644 --- a/ruby/example_code/s3/auth_federation_token_request_test.rb +++ b/ruby/example_code/s3/auth_federation_token_request_test.rb @@ -9,9 +9,9 @@ # Prerequisites: # - An existing Amazon S3 bucket. -require "aws-sdk-s3" -require "aws-sdk-iam" -require "json" +require 'aws-sdk-s3' +require 'aws-sdk-iam' +require 'json' # Checks to see whether a user exists in IAM; otherwise, # creates the user. @@ -28,14 +28,14 @@ def get_user(iam, user_name) puts "Checking for a user with the name '#{user_name}'..." response = iam.get_user(user_name: user_name) puts "A user with the name '#{user_name}' already exists." - return response.user + response.user # If the user doesn't exist, create them. rescue Aws::IAM::Errors::NoSuchEntity puts "A user with the name '#{user_name}' doesn't exist. Creating this user..." response = iam.create_user(user_name: user_name) iam.wait_until(:user_exists, user_name: user_name) puts "Created user with the name '#{user_name}'." - return response.user + response.user rescue StandardError => e puts "Error while accessing or creating the user named '#{user_name}': #{e.message}" end @@ -68,7 +68,7 @@ def get_temporary_credentials(sts, duration_seconds, user_name, policy) name: user_name, policy: policy.to_json ) - return response.credentials + response.credentials rescue StandardError => e puts "Error while getting federation token: #{e.message}" end @@ -90,23 +90,29 @@ def list_objects_in_bucket?(s3_client, bucket_name) if response.count.positive? puts "Contents of the bucket named '#{bucket_name}' (first 50 objects):" - puts "Name => ETag" + puts 'Name => ETag' response.contents.each do |obj| puts "#{obj.key} => #{obj.etag}" end else puts "No objects in the bucket named '#{bucket_name}'." end - return true + true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" end # Example usage: def run_me +<<<<<<< HEAD region = "us-west-2" user_name = "my-user" bucket_name = "amzn-s3-demo-bucket" +======= + region = 'us-west-2' + user_name = 'my-user' + bucket_name = 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) iam = Aws::IAM::Client.new(region: region) user = get_user(iam, user_name) @@ -116,16 +122,15 @@ def run_me puts "User's name: #{user.user_name}" sts = Aws::STS::Client.new(region: region) credentials = get_temporary_credentials(sts, 3600, user_name, - { - "Version" => "2012-10-17", - "Statement" => [ - "Sid" => "Stmt1", - "Effect" => "Allow", - "Action" => "s3:ListBucket", - "Resource" => "arn:aws:s3:::#{bucket_name}" - ] - } - ) + { + 'Version' => '2012-10-17', + 'Statement' => [ + 'Sid' => 'Stmt1', + 'Effect' => 'Allow', + 'Action' => 's3:ListBucket', + 'Resource' => "arn:aws:s3:::#{bucket_name}" + ] + }) exit 1 unless credentials.access_key_id diff --git a/ruby/example_code/s3/auth_request_object_keys.rb b/ruby/example_code/s3/auth_request_object_keys.rb index 4e9e2e880c0..1aba4178c1b 100644 --- a/ruby/example_code/s3/auth_request_object_keys.rb +++ b/ruby/example_code/s3/auth_request_object_keys.rb @@ -10,7 +10,7 @@ # Prerequisites: # - An existing Amazon S3 bucket. -require "aws-sdk-s3" +require 'aws-sdk-s3' # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param bucket_name [String] The bucket's name. @@ -26,24 +26,24 @@ def list_bucket_objects?(s3_client, bucket_name) ) if objects.count.positive? - puts "The object keys in this bucket are (first 50 objects):" + puts 'The object keys in this bucket are (first 50 objects):' objects.contents.each do |object| puts object.key end else - puts "No objects found in this bucket." + puts 'No objects found in this bucket.' end - return true + true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" - return false + false end # Example usage: def run_me - region = "us-west-2" - bucket_name = "BUCKET_NAME" + region = 'us-west-2' + bucket_name = 'BUCKET_NAME' s3_client = Aws::S3::Client.new(region: region) exit 1 unless list_bucket_objects?(s3_client, bucket_name) diff --git a/ruby/example_code/s3/auth_session_token_request_test.rb b/ruby/example_code/s3/auth_session_token_request_test.rb index db1381d979f..f03f1f63100 100644 --- a/ruby/example_code/s3/auth_session_token_request_test.rb +++ b/ruby/example_code/s3/auth_session_token_request_test.rb @@ -21,9 +21,9 @@ # resources in this code example. This role must also trust the preceding IAM user. # - An existing S3 bucket. -require "aws-sdk-core" -require "aws-sdk-s3" -require "aws-sdk-iam" +require 'aws-sdk-core' +require 'aws-sdk-s3' +require 'aws-sdk-iam' # Checks whether a user exists in IAM. # @@ -39,7 +39,7 @@ def user_exists?(iam_client, user_name) rescue Aws::IAM::Errors::NoSuchEntity # User doesn't exist. rescue StandardError => e - puts "Error while determining whether the user " \ + puts 'Error while determining whether the user ' \ "'#{user_name}' exists: #{e.message}" end @@ -54,7 +54,7 @@ def user_exists?(iam_client, user_name) # exit 1 unless user.user_name def create_user(iam_client, user_name) response = iam_client.create_user(user_name: user_name) - return response.user + response.user rescue StandardError => e puts "Error while creating the user '#{user_name}': #{e.message}" end @@ -70,7 +70,7 @@ def create_user(iam_client, user_name) # exit 1 unless user.user_name def get_user(iam_client, user_name) response = iam_client.get_user(user_name: user_name) - return response.user + response.user rescue StandardError => e puts "Error while getting the user '#{user_name}': #{e.message}" end @@ -87,7 +87,7 @@ def role_exists?(iam_client, role_name) response = iam_client.get_role(role_name: role_name) return true if response.role.role_name rescue StandardError => e - puts "Error while determining whether the role " \ + puts 'Error while determining whether the role ' \ "'#{role_name}' exists: #{e.message}" end @@ -153,14 +153,14 @@ def list_objects_in_bucket?(s3_client, bucket_name) if response.count.positive? puts "Contents of the bucket named '#{bucket_name}' (first 50 objects):" - puts "Name => ETag" + puts 'Name => ETag' response.contents.each do |obj| puts "#{obj.key} => #{obj.etag}" end else puts "No objects in the bucket named '#{bucket_name}'." end - return true + true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" end @@ -168,24 +168,27 @@ def list_objects_in_bucket?(s3_client, bucket_name) # Example usage: def run_me - user_name = "my-user" - region = "us-west-2" + user_name = 'my-user' + region = 'us-west-2' iam_client = Aws::IAM::Client.new(region: region) - user = "" - role_name = "AmazonS3ReadOnly" - role_arn = "arn:aws:iam::111111111111:role/" + role_name - role_session_name = "ReadAmazonS3Bucket" + role_name = 'AmazonS3ReadOnly' + role_arn = "arn:aws:iam::111111111111:role/#{role_name}" + role_session_name = 'ReadAmazonS3Bucket' duration_seconds = 3600 sts_client = Aws::STS::Client.new(region: region) +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" +======= + bucket_name = 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) puts "Getting or creating user '#{user_name}'..." - if user_exists?(iam_client, user_name) - user = get_user(iam_client, user_name) - else - user = create_user(iam_client, user_name) - end + user = if user_exists?(iam_client, user_name) + get_user(iam_client, user_name) + else + create_user(iam_client, user_name) + end if user.empty? puts "Cannot get or create user '#{user_name}'. Stopping program." @@ -202,15 +205,15 @@ def run_me puts "The role '#{role_name}' does not exist. Stopping program." end - puts "Getting credentials..." + puts 'Getting credentials...' credentials = get_credentials(sts_client, role_arn, role_session_name, duration_seconds) if credentials.nil? - puts "Cannot get credentials. Stopping program." + puts 'Cannot get credentials. Stopping program.' exit 1 else - puts "Got credentials." + puts 'Got credentials.' end s3_client = Aws::S3::Client.new( @@ -227,10 +230,10 @@ def run_me exit 1 end - unless list_objects_in_bucket?(s3_client, bucket_name) - puts "Cannot access the bucket '#{bucket_name}'. Stopping program." - exit 1 - end + return if list_objects_in_bucket?(s3_client, bucket_name) + + puts "Cannot access the bucket '#{bucket_name}'. Stopping program." + exit 1 end run_me if $PROGRAM_NAME == __FILE__ diff --git a/ruby/example_code/s3/bucket_cors.rb b/ruby/example_code/s3/bucket_cors.rb index f26bec8ead8..e6fc1b71a45 100644 --- a/ruby/example_code/s3/bucket_cors.rb +++ b/ruby/example_code/s3/bucket_cors.rb @@ -7,7 +7,7 @@ # Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[ruby.example_code.s3.helper.BucketCorsWrapper] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper @@ -17,13 +17,13 @@ class BucketCorsWrapper def initialize(bucket_cors) @bucket_cors = bucket_cors end -# snippet-end:[ruby.example_code.s3.helper.BucketCorsWrapper] + # snippet-end:[ruby.example_code.s3.helper.BucketCorsWrapper] # snippet-start:[ruby.example_code.s3.GetBucketCors] # Gets the CORS configuration of a bucket. # # @return [Aws::S3::Type::GetBucketCorsOutput, nil] The current CORS configuration for the bucket. - def get_cors + def cors @bucket_cors.data rescue Aws::Errors::ServiceError => e puts "Couldn't get CORS configuration for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" @@ -69,13 +69,17 @@ def delete_cors false end # snippet-end:[ruby.example_code.s3.DeleteBucketCors] -# snippet-start:[ruby.example_code.s3.helper.end.BucketCorsWrapper] + # snippet-start:[ruby.example_code.s3.helper.end.BucketCorsWrapper] end # snippet-end:[ruby.example_code.s3.helper.end.BucketCorsWrapper] # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" +======= + bucket_name = 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) allowed_methods = %w[GET PUT] allowed_origins = %w[http://www.example.com] diff --git a/ruby/example_code/s3/bucket_create.rb b/ruby/example_code/s3/bucket_create.rb index 4201f1aeae7..20f1a359b09 100644 --- a/ruby/example_code/s3/bucket_create.rb +++ b/ruby/example_code/s3/bucket_create.rb @@ -6,7 +6,7 @@ # Shows how to use the AWS SDK for Ruby to create an Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[s3.ruby.create_bucket_snippet.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 bucket actions. class BucketCreateWrapper @@ -35,7 +35,7 @@ def create?(region) # @return [String] The location of the bucket. def location if @bucket.nil? - "None. You must create a bucket before you can get its location!" + 'None. You must create a bucket before you can get its location!' else @bucket.client.get_bucket_location(bucket: @bucket.name).location_constraint end @@ -46,8 +46,13 @@ def location # Example usage: def run_demo +<<<<<<< HEAD region = "us-west-2" wrapper = BucketCreateWrapper.new(Aws::S3::Bucket.new("amzn-s3-demo-bucket-#{Random.uuid}")) +======= + region = 'us-west-2' + wrapper = BucketCreateWrapper.new(Aws::S3::Bucket.new("doc-example-bucket-#{Random.uuid}")) +>>>>>>> 999c6133e (fixes) return unless wrapper.create?(region) puts "Created bucket #{wrapper.bucket.name}." diff --git a/ruby/example_code/s3/bucket_list.rb b/ruby/example_code/s3/bucket_list.rb index d3c38122973..f572abe6a3a 100644 --- a/ruby/example_code/s3/bucket_list.rb +++ b/ruby/example_code/s3/bucket_list.rb @@ -6,7 +6,7 @@ # Shows how to list Amazon Simple Storage Service (Amazon S3) buckets. # snippet-start:[ruby.example_code.s3.ListBuckets] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 resource actions. class BucketListWrapper @@ -21,7 +21,7 @@ def initialize(s3_resource) # # @param count [Integer] The maximum number of buckets to list. def list_buckets(count) - puts "Found these buckets:" + puts 'Found these buckets:' @s3_resource.buckets.each do |bucket| puts "\t#{bucket.name}" count -= 1 diff --git a/ruby/example_code/s3/bucket_list_objects.rb b/ruby/example_code/s3/bucket_list_objects.rb index e3ffab553ea..b3c04f0b195 100644 --- a/ruby/example_code/s3/bucket_list_objects.rb +++ b/ruby/example_code/s3/bucket_list_objects.rb @@ -6,7 +6,7 @@ # Shows how to list the objects in an Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[ruby.example_code.s3.ListObjects] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 bucket actions. class BucketListObjectsWrapper @@ -38,7 +38,11 @@ def list_objects(max_objects) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" +======= + bucket_name = 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) wrapper = BucketListObjectsWrapper.new(Aws::S3::Bucket.new(bucket_name)) count = wrapper.list_objects(25) diff --git a/ruby/example_code/s3/bucket_policy.rb b/ruby/example_code/s3/bucket_policy.rb index ab4adc9d85c..a6579a23bb6 100644 --- a/ruby/example_code/s3/bucket_policy.rb +++ b/ruby/example_code/s3/bucket_policy.rb @@ -7,7 +7,7 @@ # Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[ruby.example_code.s3.Scenario_BucketPolicyBasics] -require "aws-sdk-s3" +require 'aws-sdk-s3' # snippet-start:[ruby.example_code.s3.helper.BucketPolicyWrapper] # Wraps an Amazon S3 bucket policy. @@ -18,13 +18,13 @@ class BucketPolicyWrapper def initialize(bucket_policy) @bucket_policy = bucket_policy end -# snippet-end:[ruby.example_code.s3.helper.BucketPolicyWrapper] + # snippet-end:[ruby.example_code.s3.helper.BucketPolicyWrapper] # snippet-start:[ruby.example_code.s3.GetBucketPolicy] # Gets the policy of a bucket. # # @return [Aws::S3::GetBucketPolicyOutput, nil] The current bucket policy. - def get_policy + def policy policy = @bucket_policy.data.policy policy.respond_to?(:read) ? policy.read : policy rescue Aws::Errors::ServiceError => e @@ -36,7 +36,7 @@ def get_policy # snippet-start:[ruby.example_code.s3.PutBucketPolicy] # Sets a policy on a bucket. # - def set_policy(policy) + def policy(policy) @bucket_policy.put(policy: policy) true rescue Aws::Errors::ServiceError => e @@ -54,20 +54,25 @@ def delete_policy false end # snippet-end:[ruby.example_code.s3.DeleteBucketPolicy] -# snippet-start:[ruby.example_code.s3.helper.end.BucketPolicyWrapper] + # snippet-start:[ruby.example_code.s3.helper.end.BucketPolicyWrapper] end # snippet-end:[ruby.example_code.s3.helper.end.BucketPolicyWrapper] # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" policy_user = "arn:aws:iam::111122223333:user/Martha" +======= + bucket_name = 'doc-example-bucket' + policy_user = 'arn:aws:iam::111122223333:user/Martha' +>>>>>>> 999c6133e (fixes) policy = { - 'Version': "2012-10-17", - 'Id': "DemoBucketPolicy", + 'Version': '2012-10-17', + 'Id': 'DemoBucketPolicy', 'Statement': [ { - 'Effect': "Deny", + 'Effect': 'Deny', 'Principal': { 'AWS': policy_user }, 'Action': %w[s3:GetObject s3:ListBucket], 'NotResource': %W[arn:aws:s3:::#{bucket_name}/* arn:aws:s3:::#{bucket_name}] diff --git a/ruby/example_code/s3/bucket_put_encryption.rb b/ruby/example_code/s3/bucket_put_encryption.rb index 3f172f54d5c..518a76ed7f1 100644 --- a/ruby/example_code/s3/bucket_put_encryption.rb +++ b/ruby/example_code/s3/bucket_put_encryption.rb @@ -7,7 +7,7 @@ # bucket using server-side encryption. # snippet-start:[ruby.example_code.s3.PutBucketEncryption] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 actions. class BucketEncryptionWrapper @@ -18,7 +18,7 @@ def initialize(s3_client) @s3_client = s3_client end - def set_encryption(bucket_name) + def encryption(bucket_name) @s3_client.put_bucket_encryption( bucket: bucket_name, server_side_encryption_configuration: @@ -27,7 +27,7 @@ def set_encryption(bucket_name) [ { apply_server_side_encryption_by_default: - { sse_algorithm: "AES256" } + { sse_algorithm: 'AES256' } } ] } @@ -41,7 +41,11 @@ def set_encryption(bucket_name) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" +======= + bucket_name = 'doc-example-bucket' +>>>>>>> 999c6133e (fixes) wrapper = BucketEncryptionWrapper.new(Aws::S3::Client.new) return unless wrapper.set_encryption(bucket_name) diff --git a/ruby/example_code/s3/bucket_put_website.rb b/ruby/example_code/s3/bucket_put_website.rb index 8254b9dcc32..9f591ef9615 100644 --- a/ruby/example_code/s3/bucket_put_website.rb +++ b/ruby/example_code/s3/bucket_put_website.rb @@ -6,7 +6,7 @@ # Shows how to configure an Amazon Simple Storage Service (Amazon S3) bucket as a static website. # snippet-start:[ruby.example_code.s3.PutBucketWebsite] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 bucket website actions. class BucketWebsiteWrapper @@ -38,9 +38,15 @@ def set_website(index_document, error_document) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" index_document = "index.html" error_document = "404.html" +======= + bucket_name = 'doc-example-bucket' + index_document = 'index.html' + error_document = '404.html' +>>>>>>> 999c6133e (fixes) wrapper = BucketWebsiteWrapper.new(Aws::S3::BucketWebsite.new(bucket_name)) return unless wrapper.set_website(index_document, error_document) diff --git a/ruby/example_code/s3/encryption_v2/s3_add_csaes_encrypt_item.rb b/ruby/example_code/s3/encryption_v2/s3_add_csaes_encrypt_item.rb index e279ecbe616..d0ae58b7017 100644 --- a/ruby/example_code/s3/encryption_v2/s3_add_csaes_encrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/s3_add_csaes_encrypt_item.rb @@ -7,9 +7,8 @@ # snippet-start:[s3.ruby.s3_add_csaes_encrypt_item] -require "aws-sdk-s3" -require "openssl" - +require 'aws-sdk-s3' +require 'openssl' # Prerequisites: # @@ -51,10 +50,10 @@ def encrypted_object_uploaded?( key: object_key, body: object_content ) - return true + true rescue Aws::Errors::ServiceError => e puts "Error uploading object: #{e.message}" - return false + false end # Generates a random AES256-GCM key. Call this function if you do not @@ -67,26 +66,32 @@ def encrypted_object_uploaded?( # have this key. # @ example # get_random_aes_256_gcm_key -def get_random_aes_256_gcm_key - cipher = OpenSSL::Cipher.new("aes-256-gcm") +def random_aes_256_gcm_key + cipher = OpenSSL::Cipher.new('aes-256-gcm') cipher.encrypt random_key = cipher.random_key - random_key_64_string = [random_key].pack("m") - random_key_64 = random_key_64_string.unpack("m")[0] - puts "The base 64-encoded string representation of the randomly-" \ - "generated AES256-GCM key is:" + random_key_64_string = [random_key].pack('m') + random_key_64 = random_key_64_string.unpack1('m') + puts 'The base 64-encoded string representation of the randomly-' \ + 'generated AES256-GCM key is:' puts random_key_64_string - puts "Keep a record of this key string. You will not be able to later " \ - "decrypt the contents of any object that is encrypted with this key " \ - "unless you have this key." - return random_key_64 + puts 'Keep a record of this key string. You will not be able to later ' \ + 'decrypt the contents of any object that is encrypted with this key ' \ + 'unless you have this key.' + random_key_64 end # Example usage: def run_me +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" region = "us-west-2" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + region = 'us-west-2' +>>>>>>> 999c6133e (fixes) object_content = File.read(object_key) # The following call generates a random AES256-GCM key. Alternatively, you can @@ -114,9 +119,9 @@ def run_me object_key, object_content ) - puts "Uploaded." + puts 'Uploaded.' else - puts "Not uploaded." + puts 'Not uploaded.' end end diff --git a/ruby/example_code/s3/encryption_v2/s3_add_cskms_encrypt_item.rb b/ruby/example_code/s3/encryption_v2/s3_add_cskms_encrypt_item.rb index 5ecac7bc7a6..fe6ea8c6f8f 100644 --- a/ruby/example_code/s3/encryption_v2/s3_add_cskms_encrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/s3_add_cskms_encrypt_item.rb @@ -6,7 +6,7 @@ # snippet-start:[s3.ruby.s3_add_cskms_encrypt_item] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Prerequisites: # @@ -49,18 +49,25 @@ def encrypted_object_uploaded?( key: object_key, body: object_content ) - return true + true rescue Aws::Errors::ServiceError => e puts "Error uploading object: #{e.message}" - return false + false end # Example usage: def run_me +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" region = "us-west-2" kms_key_id = "9041e78c-7a20-4db3-929e-828abEXAMPLE" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + region = 'us-west-2' + kms_key_id = '9041e78c-7a20-4db3-929e-828abEXAMPLE' +>>>>>>> 999c6133e (fixes) object_content = File.read(object_key) # Note that in the following call: @@ -81,9 +88,9 @@ def run_me object_key, object_content ) - puts "Uploaded." + puts 'Uploaded.' else - puts "Not uploaded." + puts 'Not uploaded.' end end diff --git a/ruby/example_code/s3/encryption_v2/s3_get_csaes_decrypt_item.rb b/ruby/example_code/s3/encryption_v2/s3_get_csaes_decrypt_item.rb index 90db79f7955..6e370c4b2d9 100644 --- a/ruby/example_code/s3/encryption_v2/s3_get_csaes_decrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/s3_get_csaes_decrypt_item.rb @@ -7,7 +7,7 @@ # snippet-start:[s3.s3_get_csaes_decrypt_item.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Prerequisites: # @@ -42,26 +42,31 @@ def get_decrypted_object_content( ) response = s3_encryption_client.get_object( bucket: bucket_name, - key: object_key) - if defined?(response.body) - return response.body.read - else - return "Error: Object content empty or unavailable." - end + key: object_key + ) + return response.body.read if defined?(response.body) + + 'Error: Object content empty or unavailable.' rescue Aws::Errors::ServiceError => e - return "Error getting object content: #{e.message}" + "Error getting object content: #{e.message}" end # Example usage: def run_me +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" region = "us-west-2" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + region = 'us-west-2' +>>>>>>> 999c6133e (fixes) # Provide a base64-encoded string representation of the key that # was originally used to encrypt the object. For example: - encryption_key_string = "XSiKrmzhtDKR9tTwJRSLjgwLhiMA82TC2z3GEXAMPLE=" - encryption_key = encryption_key_string.unpack("m")[0] + encryption_key_string = 'XSiKrmzhtDKR9tTwJRSLjgwLhiMA82TC2z3GEXAMPLE=' + encryption_key = encryption_key_string.unpack1('m') # Note that in the following call: # - key_wrap_schema must be aes_gcm for symmetric keys. diff --git a/ruby/example_code/s3/encryption_v2/s3_get_cskms_decrypt_item.rb b/ruby/example_code/s3/encryption_v2/s3_get_cskms_decrypt_item.rb index 47c72257250..63a2639b2b5 100644 --- a/ruby/example_code/s3/encryption_v2/s3_get_cskms_decrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/s3_get_cskms_decrypt_item.rb @@ -7,8 +7,7 @@ # snippet-start:[s3.s3_get_cskms_decrypt_item.rb] -require "aws-sdk-s3" - +require 'aws-sdk-s3' # Prerequisites: # @@ -43,21 +42,26 @@ def get_decrypted_object_content( bucket: bucket_name, key: object_key ) - if defined?(response.body) - return response.body.read - else - return "Error: Object content empty or unavailable." - end + return response.body.read if defined?(response.body) + + 'Error: Object content empty or unavailable.' rescue Aws::Errors::ServiceError => e - return "Error getting object content: #{e.message}" + "Error getting object content: #{e.message}" end # Example usage: def run_me +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" region = "us-west-2" kms_key_id = "9041e78c-7a20-4db3-929e-828abEXAMPLE" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + region = 'us-west-2' + kms_key_id = '9041e78c-7a20-4db3-929e-828abEXAMPLE' +>>>>>>> 999c6133e (fixes) # Note that in the following call: # - key_wrap_schema must be kms_context for AWS KMS. diff --git a/ruby/example_code/s3/encryption_v2/s3_ruby_example_add_cspk_item.rb b/ruby/example_code/s3/encryption_v2/s3_ruby_example_add_cspk_item.rb index 7640db5174d..9b7d00dca70 100644 --- a/ruby/example_code/s3/encryption_v2/s3_ruby_example_add_cspk_item.rb +++ b/ruby/example_code/s3/encryption_v2/s3_ruby_example_add_cspk_item.rb @@ -7,8 +7,8 @@ # snippet-start:[s3.ruby.s3-ruby-example-add-cspk-item] -require "aws-sdk-s3" -require "openssl" +require 'aws-sdk-s3' +require 'openssl' # Prerequisites: # @@ -44,10 +44,10 @@ def object_uploaded_with_public_key_encryption?( key: object_key, body: object_content ) - return true + true rescue Aws::Errors::ServiceError => e puts "Error uploading object: #{e.message}" - return false + false end # Full example call: @@ -55,11 +55,19 @@ def object_uploaded_with_public_key_encryption?( # Example usage: def run_me +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" object_content = "This is the content of my-file.txt." region = "us-west-2" public_key_file = "my-public-key.pem" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + object_content = 'This is the content of my-file.txt.' + region = 'us-west-2' + public_key_file = 'my-public-key.pem' +>>>>>>> 999c6133e (fixes) public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file)) # When initializing this Amazon S3 encryption client, note: @@ -80,9 +88,9 @@ def run_me object_key, object_content ) - puts "Object uploaded." + puts 'Object uploaded.' else - puts "Object not uploaded." + puts 'Object not uploaded.' end end diff --git a/ruby/example_code/s3/encryption_v2/s3_ruby_example_get_cspk_item.rb b/ruby/example_code/s3/encryption_v2/s3_ruby_example_get_cspk_item.rb index 06837bc58c5..6a183a1488e 100644 --- a/ruby/example_code/s3/encryption_v2/s3_ruby_example_get_cspk_item.rb +++ b/ruby/example_code/s3/encryption_v2/s3_ruby_example_get_cspk_item.rb @@ -7,9 +7,8 @@ # snippet-start:[s3.ruby.s3-ruby-example-get-cspk-item] -require "aws-sdk-s3" -require "openssl" - +require 'aws-sdk-s3' +require 'openssl' # # Prerequisites: @@ -44,17 +43,24 @@ def download_object_with_private_key_encryption( bucket: bucket_name, key: object_key ) - return response.body.read + response.body.read rescue Aws::Errors::ServiceError => e puts "Error downloading object: #{e.message}" end # Example usage: def run_me +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" region = "us-west-2" private_key_file = "my-private-key.pem" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + region = 'us-west-2' + private_key_file = 'my-private-key.pem' +>>>>>>> 999c6133e (fixes) private_key = OpenSSL::PKey::RSA.new(File.read(private_key_file)) # When initializing this Amazon S3 encryption client, note: diff --git a/ruby/example_code/s3/encryption_v2/spec/test_s3_add_csaes_encrypt_item.rb b/ruby/example_code/s3/encryption_v2/spec/test_s3_add_csaes_encrypt_item.rb index b5a20cc6405..744796a3f61 100644 --- a/ruby/example_code/s3/encryption_v2/spec/test_s3_add_csaes_encrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/spec/test_s3_add_csaes_encrypt_item.rb @@ -1,12 +1,19 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../s3_add_csaes_encrypt_item" +require_relative '../s3_add_csaes_encrypt_item' +<<<<<<< HEAD describe "#encrypted_object_uploaded?" do let(:bucket_name) { "amzn-s3-demo-bucket" } let(:object_key) { "my-file.txt" } let(:object_content) { "This is the content of my-file.txt." } +======= +describe '#encrypted_object_uploaded?' do + let(:bucket_name) { 'doc-example-bucket' } + let(:object_key) { 'my-file.txt' } + let(:object_content) { 'This is the content of my-file.txt.' } +>>>>>>> 999c6133e (fixes) let(:encryption_key) { get_random_aes_256_gcm_key } # Note that Aws::S3::EncryptionV2::Client is a wrapper around # Aws::S3::Client. So you must first stub Aws::S3::Client @@ -15,7 +22,7 @@ let(:s3_client) do Aws::S3::Client.new( stub_responses: { - put_object: { etag: "8c009a8b36167046a47caee5b3639de4" } + put_object: { etag: '8c009a8b36167046a47caee5b3639de4' } } ) end @@ -29,12 +36,12 @@ ) end - it "uploads an encrypted object to an Amazon S3 bucket" do + it 'uploads an encrypted object to an Amazon S3 bucket' do expect(encrypted_object_uploaded?( - s3_encryption_client, - bucket_name, - object_key, - object_content - )).to be(true) + s3_encryption_client, + bucket_name, + object_key, + object_content + )).to be(true) end end diff --git a/ruby/example_code/s3/encryption_v2/spec/test_s3_add_cskms_encrypt_item.rb b/ruby/example_code/s3/encryption_v2/spec/test_s3_add_cskms_encrypt_item.rb index 0d4fcad0035..4b82c69ed37 100644 --- a/ruby/example_code/s3/encryption_v2/spec/test_s3_add_cskms_encrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/spec/test_s3_add_cskms_encrypt_item.rb @@ -1,13 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../s3_add_cskms_encrypt_item" +require_relative '../s3_add_cskms_encrypt_item' +<<<<<<< HEAD describe "#encrypted_object_uploaded?" do let(:bucket_name) { "amzn-s3-demo-bucket" } let(:object_key) { "my-file.txt" } let(:object_content) { "This is the content of my-file.txt." } let(:kms_key_id) { "9041e78c-7a20-4db3-929e-828abEXAMPLE" } +======= +describe '#encrypted_object_uploaded?' do + let(:bucket_name) { 'doc-example-bucket' } + let(:object_key) { 'my-file.txt' } + let(:object_content) { 'This is the content of my-file.txt.' } + let(:kms_key_id) { '9041e78c-7a20-4db3-929e-828abEXAMPLE' } +>>>>>>> 999c6133e (fixes) # Note that Aws::S3::EncryptionV2::Client is a wrapper around # Aws::S3::Client. So you must first stub Aws::S3::Client # and then pass it into Aws::S3::EncryptionV2::Client @@ -15,7 +23,7 @@ let(:s3_client) do Aws::S3::Client.new( stub_responses: { - put_object: { etag: "8c009a8b36167046a47caee5b3639de4" } + put_object: { etag: '8c009a8b36167046a47caee5b3639de4' } } ) end @@ -27,8 +35,9 @@ Aws::KMS::Client.new( stub_responses: { generate_data_key: { - ciphertext_blob: "AQIDAHh58pZkpaY6Ifx4UPd9kZBp2ssaYk/T1eiY2dnLv9dP1QHFZ71+8g1Yq0ikFTvgjbzgAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMgGqjmfp6p9q3pqgsAgEQgDufNsOEtJJUAsZ6QkJoVUQz9tWgYQ0HMHNtXSObHsRbw6QejNCtGJAxip4/9HJWbmo8V+s+7+NEXAMPLE==", - key_id: "arn:aws:kms:us-west-2:111111111111:key/9041e78c-7a20-4db3-929e-828abEXAMPLE", + ciphertext_blob: 'AQIDAHh58pZkpaY6Ifx4UPd9kZBp2ssaYk/T1eiY2dnLv9dP1QHFZ71+8g1Yq0ikFTvgjbzgAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMgGqjmfp6p9q3pqgsAgEQgDufNsOEtJJUAsZ6QkJoVUQz9tWgYQ0HMHNtXSObHsRbw6QejNCtGJAxip4/9HJWbmo8V+s+7+NEXAMPLE==', + + key_id: 'arn:aws:kms:us-west-2:111111111111:key/9041e78c-7a20-4db3-929e-828abEXAMPLE', plaintext: "\xAD\xC8\xF0o\v\x0F\x1E\xD3\xEA\xF8\x05\x03\x9F?\xC2#\xB4_\xE3\xBD\x96\x1A\xC9S\xCA\xE8Ya\xB9{\t\x7F" } } @@ -45,12 +54,12 @@ ) end - it "uploads an encrypted object to an Amazon S3 bucket" do + it 'uploads an encrypted object to an Amazon S3 bucket' do expect(encrypted_object_uploaded?( - s3_encryption_client, - bucket_name, - object_key, - object_content - )).to be(true) + s3_encryption_client, + bucket_name, + object_key, + object_content + )).to be(true) end end diff --git a/ruby/example_code/s3/encryption_v2/spec/test_s3_get_csaes_decrypt_item.rb b/ruby/example_code/s3/encryption_v2/spec/test_s3_get_csaes_decrypt_item.rb index 0f8fe481f89..1454ef799ef 100644 --- a/ruby/example_code/s3/encryption_v2/spec/test_s3_get_csaes_decrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/spec/test_s3_get_csaes_decrypt_item.rb @@ -1,9 +1,9 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../s3_get_csaes_decrypt_item" +require_relative '../s3_get_csaes_decrypt_item' -describe "#get_decrypted_object_content" do +describe '#get_decrypted_object_content' do # Captures the data (metadata and body) put to an Amazon S3 object. def stub_put(s3_client) data = {} @@ -21,12 +21,8 @@ def stub_put(s3_client) # auth_tag. def stub_get(s3_client, data, stub_auth_tag) resp_headers = Hash[*data[:metadata].flat_map { |k, v| ["x-amz-meta-#{k}", v] }] - resp_headers["content-length"] = data[:enc_body].length - if stub_auth_tag - auth_tag = data[:enc_body].unpack("C*")[-16, 16].pack("C*") - else - auth_tag = nil - end + resp_headers['content-length'] = data[:enc_body].length + auth_tag = (data[:enc_body].unpack('C*')[-16, 16].pack('C*') if stub_auth_tag) s3_client.stub_responses( :get_object, { @@ -40,11 +36,19 @@ def stub_get(s3_client, data, stub_auth_tag) ) end +<<<<<<< HEAD let(:bucket_name) { "amzn-s3-demo-bucket" } let(:object_key) { "my-file.txt" } let(:object_content) { "This is the content of my-file.txt." } let(:encryption_key_string) { "XSiKrmzhtDKR9tTwJRSLjgwLhiMA82TC2z3GEXAMPLE=" } let(:encryption_key) { encryption_key_string.unpack("m")[0] } +======= + let(:bucket_name) { 'doc-example-bucket' } + let(:object_key) { 'my-file.txt' } + let(:object_content) { 'This is the content of my-file.txt.' } + let(:encryption_key_string) { 'XSiKrmzhtDKR9tTwJRSLjgwLhiMA82TC2z3GEXAMPLE=' } + let(:encryption_key) { encryption_key_string.unpack1('m') } +>>>>>>> 999c6133e (fixes) # Note that Aws::S3::EncryptionV2::Client is a wrapper around # Aws::S3::Client. So you must first stub Aws::S3::Client # and then pass it into Aws::S3::EncryptionV2::Client @@ -66,7 +70,7 @@ def stub_get(s3_client, data, stub_auth_tag) ) end - it "gets the decrypted content of an object in an Amazon S3 bucket" do + it 'gets the decrypted content of an object in an Amazon S3 bucket' do data = stub_put(s3_client) s3_encryption_client.put_object( bucket: bucket_name, @@ -75,9 +79,9 @@ def stub_get(s3_client, data, stub_auth_tag) ) stub_get(s3_client, data, true) expect(get_decrypted_object_content( - s3_encryption_client, - bucket_name, - object_key - )).to eq(object_content) + s3_encryption_client, + bucket_name, + object_key + )).to eq(object_content) end end diff --git a/ruby/example_code/s3/encryption_v2/spec/test_s3_get_cskms_decrypt_item.rb b/ruby/example_code/s3/encryption_v2/spec/test_s3_get_cskms_decrypt_item.rb index 5d986ed1654..a592079023e 100644 --- a/ruby/example_code/s3/encryption_v2/spec/test_s3_get_cskms_decrypt_item.rb +++ b/ruby/example_code/s3/encryption_v2/spec/test_s3_get_cskms_decrypt_item.rb @@ -1,9 +1,9 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../s3_get_cskms_decrypt_item" +require_relative '../s3_get_cskms_decrypt_item' -describe "#get_decrypted_object_content" do +describe '#get_decrypted_object_content' do # Captures the data (metadata and body) put to an Amason S3 object. def stub_put(s3_client) data = {} @@ -21,12 +21,8 @@ def stub_put(s3_client) # auth_tag. def stub_get(s3_client, data, stub_auth_tag) resp_headers = Hash[*data[:metadata].flat_map { |k, v| ["x-amz-meta-#{k}", v] }] - resp_headers["content-length"] = data[:enc_body].length - if stub_auth_tag - auth_tag = data[:enc_body].unpack("C*")[-16, 16].pack("C*") - else - auth_tag = nil - end + resp_headers['content-length'] = data[:enc_body].length + auth_tag = (data[:enc_body].unpack('C*')[-16, 16].pack('C*') if stub_auth_tag) s3_client.stub_responses( :get_object, { @@ -44,24 +40,33 @@ def stub_decrypt(kms_client, opts) kms_client.stub_responses( :decrypt, lambda do |context| if opts[:any_kms_key] - expect(context.params["key_id"]).to be_nil + expect(context.params['key_id']).to be_nil else - if opts[:raise] && context.params["key_id"] != opts[:response][:key_id] - raise Aws::KMS::Errors::IncorrectKeyException.new(context, "") - else - expect(context.params[:key_id]).to eq(opts[:response][:key_id]) - end + raise Aws::KMS::Errors::IncorrectKeyException.new(context, '') if opts[:raise] && context.params['key_id'] != opts[:response][:key_id] + + expect(context.params[:key_id]).to eq(opts[:response][:key_id]) + end opts[:response] end ) end +<<<<<<< HEAD let(:bucket_name) { "amzn-s3-demo-bucket" } let(:object_key) { "my-file.txt" } let(:object_content) { "This is the content of my-file.txt." } let(:kms_key_id) { "9041e78c-7a20-4db3-929e-828abEXAMPLE" } let(:kms_ciphertext_blob) { Base64.decode64("AQIDAHiWj6qDEnwihp7W7g6VZb1xqsat5jdSUdEaGhgZepHdLAGASCQI7LZz\nz7GzCpm6y4sHAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEH\nATAeBglghkgBZQMEAS4wEQQMJMJe6d8DkRTWwlvtAgEQgDtBCwiibCTS8pb7\n6BYKklVjy+CmO9q3r6y4u/9jJ8lk9eg5GwiskmcBtPMcWogMzx/vh+/65Cjb\nsQBpLQ==\n") } +======= + let(:bucket_name) { 'doc-example-bucket' } + let(:object_key) { 'my-file.txt' } + let(:object_content) { 'This is the content of my-file.txt.' } + let(:kms_key_id) { '9041e78c-7a20-4db3-929e-828abEXAMPLE' } + let(:kms_ciphertext_blob) do + Base64.decode64("AQIDAHiWj6qDEnwihp7W7g6VZb1xqsat5jdSUdEaGhgZepHdLAGASCQI7LZz\nz7GzCpm6y4sHAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEH\nATAeBglghkgBZQMEAS4wEQQMJMJe6d8DkRTWwlvtAgEQgDtBCwiibCTS8pb7\n6BYKklVjy+CmO9q3r6y4u/9jJ8lk9eg5GwiskmcBtPMcWogMzx/vh+/65Cjb\nsQBpLQ==\n") + end +>>>>>>> 999c6133e (fixes) let(:kms_plaintext) { Base64.decode64("5V7JWe+UDRhv66TaDg+tP6JONf/GkTdXk6Jq61weM+w=\n") } # Note that Aws::S3::EncryptionV2::Client is a wrapper around # Aws::S3::Client. So you must first stub Aws::S3::Client @@ -85,7 +90,7 @@ def stub_decrypt(kms_client, opts) stub_responses: { generate_data_key: { ciphertext_blob: kms_ciphertext_blob, - key_id: "arn:aws:kms:us-west-2:111111111111:key/9041e78c-7a20-4db3-929e-828abEXAMPLE", + key_id: 'arn:aws:kms:us-west-2:111111111111:key/9041e78c-7a20-4db3-929e-828abEXAMPLE', plaintext: kms_plaintext } } @@ -102,7 +107,7 @@ def stub_decrypt(kms_client, opts) ) end - it "gets the decrypted content of an object in an Amazon S3 bucket" do + it 'gets the decrypted content of an object in an Amazon S3 bucket' do data = stub_put(s3_client) s3_encryption_client.put_object( bucket: bucket_name, @@ -114,13 +119,12 @@ def stub_decrypt(kms_client, opts) { key_id: kms_key_id, plaintext: kms_plaintext, - encryption_algorithm: "SYMMETRIC_DEFAULT" - } - ) + encryption_algorithm: 'SYMMETRIC_DEFAULT' + }) expect(get_decrypted_object_content( - s3_encryption_client, - bucket_name, - object_key - )).to eq(object_content) + s3_encryption_client, + bucket_name, + object_key + )).to eq(object_content) end end diff --git a/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_add_cspk_item.rb b/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_add_cspk_item.rb index bdc76297a03..4d678d9da61 100644 --- a/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_add_cspk_item.rb +++ b/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_add_cspk_item.rb @@ -1,12 +1,19 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../s3-ruby-example-add-cspk-item" +require_relative '../s3-ruby-example-add-cspk-item' +<<<<<<< HEAD describe "#object_uploaded_with_public_key_encryption?" do let(:bucket_name) { "amzn-s3-demo-bucket" } let(:object_key) { "my-file.txt" } let(:object_content) { "This is the content of my-file.txt." } +======= +describe '#object_uploaded_with_public_key_encryption?' do + let(:bucket_name) { 'doc-example-bucket' } + let(:object_key) { 'my-file.txt' } + let(:object_content) { 'This is the content of my-file.txt.' } +>>>>>>> 999c6133e (fixes) # Note that Aws::S3::EncryptionV2::Client is a wrapper around # Aws::S3::Client. So you must first stub Aws::S3::Client # and then pass it into Aws::S3::EncryptionV2::Client @@ -29,7 +36,7 @@ ) end - it "uploads an object to a bucket with public key encryption" do + it 'uploads an object to a bucket with public key encryption' do expect( object_uploaded_with_public_key_encryption?( s3_encryption_client, diff --git a/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_get_cspk_item.rb b/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_get_cspk_item.rb index 355141843f0..4948672fb34 100644 --- a/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_get_cspk_item.rb +++ b/ruby/example_code/s3/encryption_v2/spec/test_s3_ruby_example_get_cspk_item.rb @@ -1,9 +1,9 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../s3-ruby-example-get-cspk-item" +require_relative '../s3-ruby-example-get-cspk-item' -describe "#download_object_with_private_key_encryption" do +describe '#download_object_with_private_key_encryption' do # Captures the data (metadata and body) put to an Amason S3 object. def stub_put(s3_client) data = {} @@ -21,12 +21,8 @@ def stub_put(s3_client) # auth_tag. def stub_get(s3_client, data, stub_auth_tag) resp_headers = Hash[*data[:metadata].flat_map { |k, v| ["x-amz-meta-#{k}", v] }] - resp_headers["content-length"] = data[:enc_body].length - if stub_auth_tag - auth_tag = data[:enc_body].unpack("C*")[-16, 16].pack("C*") - else - auth_tag = nil - end + resp_headers['content-length'] = data[:enc_body].length + auth_tag = (data[:enc_body].unpack('C*')[-16, 16].pack('C*') if stub_auth_tag) s3_client.stub_responses( :get_object, { @@ -40,9 +36,15 @@ def stub_get(s3_client, data, stub_auth_tag) ) end +<<<<<<< HEAD let(:bucket_name) { "amzn-s3-demo-bucket" } let(:object_key) { "my-file.txt" } let(:object_content) { "This is the content of my-file.txt." } +======= + let(:bucket_name) { 'doc-example-bucket' } + let(:object_key) { 'my-file.txt' } + let(:object_content) { 'This is the content of my-file.txt.' } +>>>>>>> 999c6133e (fixes) # Note that Aws::S3::EncryptionV2::Client is a wrapper around # Aws::S3::Client. So you must first stub Aws::S3::Client # and then pass it into Aws::S3::EncryptionV2::Client @@ -67,7 +69,7 @@ def stub_get(s3_client, data, stub_auth_tag) ) end - it "downloads an object from a bucket with private key encryption" do + it 'downloads an object from a bucket with private key encryption' do data = stub_put(s3_client) s3_encryption_client.put_object( bucket: bucket_name, diff --git a/ruby/example_code/s3/object_copy.rb b/ruby/example_code/s3/object_copy.rb index c3e415708b8..7f7a3fa172b 100644 --- a/ruby/example_code/s3/object_copy.rb +++ b/ruby/example_code/s3/object_copy.rb @@ -6,7 +6,7 @@ # Shows how to copy an object from one Amazon Simple Storage Service (Amazon S3) bucket to another. # snippet-start:[s3.ruby.copy_object_between_buckets.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectCopyWrapper @@ -33,10 +33,17 @@ def copy_object(target_bucket, target_object_key) # Example usage: def run_demo +<<<<<<< HEAD source_bucket_name = "amzn-s3-demo-bucket1" source_key = "my-source-file.txt" target_bucket_name = "amzn-s3-demo-bucket2" target_key = "my-target-file.txt" +======= + source_bucket_name = 'doc-example-bucket1' + source_key = 'my-source-file.txt' + target_bucket_name = 'doc-example-bucket2' + target_key = 'my-target-file.txt' +>>>>>>> 999c6133e (fixes) source_bucket = Aws::S3::Bucket.new(source_bucket_name) wrapper = ObjectCopyWrapper.new(source_bucket.object(source_key)) diff --git a/ruby/example_code/s3/object_copy_encrypt.rb b/ruby/example_code/s3/object_copy_encrypt.rb index 680c1552e7e..df9e54f5eec 100644 --- a/ruby/example_code/s3/object_copy_encrypt.rb +++ b/ruby/example_code/s3/object_copy_encrypt.rb @@ -7,7 +7,7 @@ # target object. # snippet-start:[s3.ruby.copy_object_encrypt_copy.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectCopyEncryptWrapper @@ -34,11 +34,19 @@ def copy_object(target_bucket, target_object_key, encryption) # Example usage: def run_demo +<<<<<<< HEAD source_bucket_name = "amzn-s3-demo-bucket1" source_key = "my-source-file.txt" target_bucket_name = "amzn-s3-demo-bucket2" target_key = "my-target-file.txt" target_encryption = "AES256" +======= + source_bucket_name = 'doc-example-bucket1' + source_key = 'my-source-file.txt' + target_bucket_name = 'doc-example-bucket2' + target_key = 'my-target-file.txt' + target_encryption = 'AES256' +>>>>>>> 999c6133e (fixes) source_bucket = Aws::S3::Bucket.new(source_bucket_name) wrapper = ObjectCopyEncryptWrapper.new(source_bucket.object(source_key)) diff --git a/ruby/example_code/s3/object_exists.rb b/ruby/example_code/s3/object_exists.rb index 05307f9fb66..e58ccad4c10 100644 --- a/ruby/example_code/s3/object_exists.rb +++ b/ruby/example_code/s3/object_exists.rb @@ -6,7 +6,7 @@ # Shows how to check if an Amazon Simple Storage Service (Amazon S3) object exists. # snippet-start:[ruby.example_code.s3.exists] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectExistsWrapper @@ -30,8 +30,13 @@ def exists? # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-object.txt" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-object.txt' +>>>>>>> 999c6133e (fixes) wrapper = ObjectExistsWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) exists = wrapper.exists? diff --git a/ruby/example_code/s3/object_get.rb b/ruby/example_code/s3/object_get.rb index c8a443b5194..40befcb45bb 100644 --- a/ruby/example_code/s3/object_get.rb +++ b/ruby/example_code/s3/object_get.rb @@ -6,7 +6,7 @@ # Shows how to get an object from an Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[ruby.example_code.s3.GetObject] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectGetWrapper @@ -30,9 +30,15 @@ def get_object(target_path) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-object.txt" target_path = "my-object-as-file.txt" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-object.txt' + target_path = 'my-object-as-file.txt' +>>>>>>> 999c6133e (fixes) wrapper = ObjectGetWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) obj_data = wrapper.get_object(target_path) diff --git a/ruby/example_code/s3/object_get_encryption.rb b/ruby/example_code/s3/object_get_encryption.rb index 48a0fde0cac..607b804a250 100644 --- a/ruby/example_code/s3/object_get_encryption.rb +++ b/ruby/example_code/s3/object_get_encryption.rb @@ -7,7 +7,7 @@ # encryption state. # snippet-start:[s3.ruby.determine_object_encryption_state.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectGetEncryptionWrapper @@ -21,7 +21,7 @@ def initialize(object) # Gets the object into memory. # # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil. - def get_object + def object @object.get rescue Aws::Errors::ServiceError => e puts "Couldn't get object #{@object.key}. Here's why: #{e.message}" @@ -30,14 +30,19 @@ def get_object # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-object.txt" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-object.txt' +>>>>>>> 999c6133e (fixes) wrapper = ObjectGetEncryptionWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) obj_data = wrapper.get_object return unless obj_data - encryption = obj_data.server_side_encryption.nil? ? "no" : obj_data.server_side_encryption + encryption = obj_data.server_side_encryption.nil? ? 'no' : obj_data.server_side_encryption puts "Object #{object_key} uses #{encryption} encryption." end diff --git a/ruby/example_code/s3/object_presigned_url_upload.rb b/ruby/example_code/s3/object_presigned_url_upload.rb index 84095125feb..1e3c2d913bc 100644 --- a/ruby/example_code/s3/object_presigned_url_upload.rb +++ b/ruby/example_code/s3/object_presigned_url_upload.rb @@ -6,8 +6,8 @@ # Shows how to upload an object to an Amazon Simple Storage Service (Amazon S3) bucket by using a presigned URL. # snippet-start:[s3.ruby.upload_object_presigned_url.rb] -require "aws-sdk-s3" -require "net/http" +require 'aws-sdk-s3' +require 'net/http' # Creates a presigned URL that can be used to upload content to an object. # @@ -24,21 +24,27 @@ def get_presigned_url(bucket, object_key) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-file.txt" object_content = "This is the content of my-file.txt." +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-file.txt' + object_content = 'This is the content of my-file.txt.' +>>>>>>> 999c6133e (fixes) bucket = Aws::S3::Bucket.new(bucket_name) presigned_url = get_presigned_url(bucket, object_key) return unless presigned_url response = Net::HTTP.start(presigned_url.host) do |http| - http.send_request("PUT", presigned_url.request_uri, object_content, "content_type" => "") + http.send_request('PUT', presigned_url.request_uri, object_content, 'content_type' => '') end case response when Net::HTTPSuccess - puts "Content uploaded!" + puts 'Content uploaded!' else puts response.value end diff --git a/ruby/example_code/s3/object_put.rb b/ruby/example_code/s3/object_put.rb index 63dd10010fd..07fe2795442 100644 --- a/ruby/example_code/s3/object_put.rb +++ b/ruby/example_code/s3/object_put.rb @@ -6,7 +6,7 @@ # Shows how to put a local file into an object in an Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[s3.ruby.upload_files_using_put_object_method.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectPutWrapper @@ -18,7 +18,7 @@ def initialize(object) end def put_object(source_file_path) - File.open(source_file_path, "rb") do |file| + File.open(source_file_path, 'rb') do |file| @object.put(body: file) end true @@ -30,9 +30,15 @@ def put_object(source_file_path) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-object-key" file_path = "my-local-file.txt" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-object-key' + file_path = 'my-local-file.txt' +>>>>>>> 999c6133e (fixes) wrapper = ObjectPutWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) success = wrapper.put_object(file_path) diff --git a/ruby/example_code/s3/object_put_sse.rb b/ruby/example_code/s3/object_put_sse.rb index a90b499d583..a3f2770d103 100644 --- a/ruby/example_code/s3/object_put_sse.rb +++ b/ruby/example_code/s3/object_put_sse.rb @@ -8,7 +8,7 @@ # block cipher. # snippet-start:[s3.ruby.s3_encrypt_file_upload.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectPutSseWrapper @@ -30,10 +30,17 @@ def put_object_encrypted(object_content, encryption) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-encrypted-content" object_content = "This is my super-secret content." encryption = "AES256" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-encrypted-content' + object_content = 'This is my super-secret content.' + encryption = 'AES256' +>>>>>>> 999c6133e (fixes) wrapper = ObjectPutSseWrapper.new(Aws::S3::Object.new(bucket_name, object_content)) return unless wrapper.put_object_encrypted(object_content, encryption) diff --git a/ruby/example_code/s3/object_upload_file.rb b/ruby/example_code/s3/object_upload_file.rb index ecd2be8f949..83b022e7546 100644 --- a/ruby/example_code/s3/object_upload_file.rb +++ b/ruby/example_code/s3/object_upload_file.rb @@ -6,7 +6,7 @@ # Shows how to use a managed uploader to upload an object to an Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[s3.ruby.upload_files_using_managed_file_uploader.rb] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectUploadFileWrapper @@ -32,9 +32,15 @@ def upload_file(file_path) # Example usage: def run_demo +<<<<<<< HEAD bucket_name = "amzn-s3-demo-bucket" object_key = "my-uploaded-file" file_path = "object_upload_file.rb" +======= + bucket_name = 'doc-example-bucket' + object_key = 'my-uploaded-file' + file_path = 'object_upload_file.rb' +>>>>>>> 999c6133e (fixes) wrapper = ObjectUploadFileWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) return unless wrapper.upload_file(file_path) diff --git a/ruby/example_code/s3/s3.rb b/ruby/example_code/s3/s3.rb index 088fafa37b8..d82460f7a16 100644 --- a/ruby/example_code/s3/s3.rb +++ b/ruby/example_code/s3/s3.rb @@ -5,11 +5,11 @@ # s3.rb demonstrates how to list, create, and delete a bucket in Amazon Simple Storage Service (Amazon S3). # snippet-start:[s3.ruby.bucket_operations.list_create_delete] -require "aws-sdk" +require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon S3. if ARGV.length < 2 - puts "Usage: ruby s3.rb \n" + - "Example: ruby s3.rb my-test-bucket us-west-2" + puts "Usage: ruby s3.rb \n" \ + 'Example: ruby s3.rb my-test-bucket us-west-2' end bucket_name = ARGV[0] @@ -24,7 +24,6 @@ def list_my_buckets(s3) resp.buckets.each do |bucket| puts bucket.name end - end list_my_buckets(s3) @@ -33,16 +32,16 @@ def list_my_buckets(s3) begin puts "\nCreating a new bucket named '#{bucket_name}'...\n\n" s3.create_bucket({ - bucket: bucket_name, - create_bucket_configuration: { - location_constraint: region - } - }) + bucket: bucket_name, + create_bucket_configuration: { + location_constraint: region + } + }) - s3.wait_until(:bucket_exists, {bucket: bucket_name, }) + s3.wait_until(:bucket_exists, { bucket: bucket_name }) rescue Aws::S3::Errors::BucketAlreadyExists - puts "Cannot create the bucket. " + - "A bucket with the name '#{bucket_name}' already exists. Exiting." + puts 'Cannot create the bucket. ' \ + "A bucket with the name '#{bucket_name}' already exists. Exiting." exit(false) end @@ -52,7 +51,7 @@ def list_my_buckets(s3) puts "\nDeleting the bucket named '#{bucket_name}'...\n\n" s3.delete_bucket(bucket: bucket_name) -s3.wait_until(:bucket_not_exists, {bucket: bucket_name, }) +s3.wait_until(:bucket_not_exists, { bucket: bucket_name }) list_my_buckets(s3) # snippet-end:[s3.ruby.bucket_operations.list_create_delete] diff --git a/ruby/example_code/s3/scenario_getting_started.rb b/ruby/example_code/s3/scenario_getting_started.rb index ead5032f888..69ccf995332 100644 --- a/ruby/example_code/s3/scenario_getting_started.rb +++ b/ruby/example_code/s3/scenario_getting_started.rb @@ -12,7 +12,7 @@ # - https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html # snippet-start:[ruby.example_code.s3.Scenario_GettingStarted] -require "aws-sdk-s3" +require 'aws-sdk-s3' # Wraps the getting started scenario actions. class ScenarioGettingStarted @@ -31,12 +31,12 @@ def create_bucket bucket = @s3_resource.create_bucket( bucket: "amzn-s3-demo-bucket-#{Random.uuid}", create_bucket_configuration: { - location_constraint: "us-east-1" # Note: only certain regions permitted + location_constraint: 'us-east-1' # NOTE: only certain regions permitted } ) puts("Created demo bucket named #{bucket.name}.") rescue Aws::Errors::ServiceError => e - puts("Tried and failed to create demo bucket.") + puts('Tried and failed to create demo bucket.') puts("\t#{e.code}: #{e.message}") puts("\nCan't continue the demo without a bucket!") raise @@ -48,7 +48,7 @@ def create_bucket # # @return The name of the file. def create_file - File.open("demo.txt", w) { |f| f.write("This is a demo file.") } + File.open('demo.txt', w) { |f| f.write('This is a demo file.') } end # Uploads a file to an Amazon S3 bucket. @@ -56,9 +56,9 @@ def create_file # @param bucket [Aws::S3::Bucket] The bucket object representing the upload destination # @return [Aws::S3::Object] The Amazon S3 object that contains the uploaded file. def upload_file(bucket) - File.open("demo.txt", "w+") { |f| f.write("This is a demo file.") } - s3_object = bucket.object(File.basename("demo.txt")) - s3_object.upload_file("demo.txt") + File.open('demo.txt', 'w+') { |f| f.write('This is a demo file.') } + s3_object = bucket.object(File.basename('demo.txt')) + s3_object.upload_file('demo.txt') puts("Uploaded file demo.txt into bucket #{bucket.name} with key #{s3_object.key}.") rescue Aws::Errors::ServiceError => e puts("Couldn't upload file demo.txt to #{bucket.name}.") @@ -74,8 +74,8 @@ def upload_file(bucket) def download_file(s3_object) puts("\nDo you want to download #{s3_object.key} to a local file (y/n)? ") answer = gets.chomp.downcase - if answer == "y" - puts("Enter a name for the downloaded file: ") + if answer == 'y' + puts('Enter a name for the downloaded file: ') file_name = gets.chomp s3_object.download_file(file_name) puts("Object #{s3_object.key} successfully downloaded to #{file_name}.") @@ -94,7 +94,7 @@ def copy_object(source_object) dest_object = nil puts("\nDo you want to copy #{source_object.key} to a subfolder in your bucket (y/n)? ") answer = gets.chomp.downcase - if answer == "y" + if answer == 'y' dest_object = source_object.bucket.object("demo-folder/#{source_object.key}") dest_object.copy_from(source_object) puts("Copied #{source_object.key} to #{dest_object.key}.") @@ -129,7 +129,7 @@ def list_objects(bucket) def delete_bucket(bucket) puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ") answer = gets.chomp.downcase - if answer == "y" + if answer == 'y' bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") @@ -145,9 +145,9 @@ def delete_bucket(bucket) # Runs the Amazon S3 getting started scenario. def run_scenario(scenario) - puts("-" * 88) - puts("Welcome to the Amazon S3 getting started demo!") - puts("-" * 88) + puts('-' * 88) + puts('Welcome to the Amazon S3 getting started demo!') + puts('-' * 88) bucket = scenario.create_bucket s3_object = scenario.upload_file(bucket) @@ -156,10 +156,10 @@ def run_scenario(scenario) scenario.list_objects(bucket) scenario.delete_bucket(bucket) - puts("Thanks for watching!") - puts("-" * 88) + puts('Thanks for watching!') + puts('-' * 88) rescue Aws::Errors::ServiceError - puts("Something went wrong with the demo!") + puts('Something went wrong with the demo!') end run_scenario(ScenarioGettingStarted.new(Aws::S3::Resource.new)) if $PROGRAM_NAME == __FILE__ diff --git a/ruby/example_code/s3/spec/bucket_cors_spec.rb b/ruby/example_code/s3/spec/bucket_cors_spec.rb index ee8309b7306..80db6971508 100644 --- a/ruby/example_code/s3/spec/bucket_cors_spec.rb +++ b/ruby/example_code/s3/spec/bucket_cors_spec.rb @@ -1,25 +1,25 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_cors" +require 'rspec' +require_relative '../bucket_cors' describe BucketCorsWrapper do - let(:bucket_name) { "test-bucket" } + let(:bucket_name) { 'test-bucket' } let(:bucket_cors) { Aws::S3::BucketCors.new(bucket_name, stub_responses: true) } let(:wrapper) { BucketCorsWrapper.new(bucket_cors) } - it "confirms CORS rules were set" do + it 'confirms CORS rules were set' do bucket_cors.client.stub_responses(:put_bucket_cors) expect(wrapper.set_cors(%w[GET DELETE], %w[http://www.example1.com http://www.example2.com])).to be_eql(true) end it "confirms error is caught when CORS can't be set" do - bucket_cors.client.stub_responses(:put_bucket_cors, "TestError") + bucket_cors.client.stub_responses(:put_bucket_cors, 'TestError') expect(wrapper.set_cors(%w[GET DELETE], %w[http://www.example1.com])).to be_eql(false) end - it "confirms CORS rules were retrieved" do + it 'confirms CORS rules were retrieved' do data = bucket_cors.client.stub_data( :get_bucket_cors, { cors_rules: [{ allowed_methods: %w[GET POST], allowed_origins: %w[https://www.example.com] }] @@ -30,17 +30,17 @@ end it "confirms error is caught when CORS can't be retrieved" do - bucket_cors.client.stub_responses(:get_bucket_cors, "TestError") + bucket_cors.client.stub_responses(:get_bucket_cors, 'TestError') expect(wrapper.get_cors).to be_nil end - it "confirms CORS rules were deleted" do + it 'confirms CORS rules were deleted' do bucket_cors.client.stub_responses(:delete_bucket_cors) expect(wrapper.delete_cors).to be_eql(true) end it "confirms error is caught when CORS can't be deleted" do - bucket_cors.client.stub_responses(:delete_bucket_cors, "TestError") + bucket_cors.client.stub_responses(:delete_bucket_cors, 'TestError') expect(wrapper.delete_cors).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/bucket_create_spec.rb b/ruby/example_code/s3/spec/bucket_create_spec.rb index 88502b54534..1d7bfd53064 100644 --- a/ruby/example_code/s3/spec/bucket_create_spec.rb +++ b/ruby/example_code/s3/spec/bucket_create_spec.rb @@ -1,34 +1,38 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_create" +require 'rspec' +require_relative '../bucket_create' describe BucketCreateWrapper do +<<<<<<< HEAD let(:bucket_name) { "amzn-s3-demo-bucket" } +======= + let(:bucket_name) { 'doc-example-bucket' } +>>>>>>> 999c6133e (fixes) let(:bucket) { Aws::S3::Bucket.new(bucket_name, stub_responses: true) } let(:wrapper) { BucketCreateWrapper.new(bucket) } - it "confirms the bucket was created" do + it 'confirms the bucket was created' do bucket.client.stub_responses(:create_bucket) - expect(wrapper.create?("us-test-2")).to be_eql(true) + expect(wrapper.create?('us-test-2')).to be_eql(true) expect(wrapper.bucket.name).to be_eql(bucket_name) end it "confirms error is caught when bucket can't be created" do - bucket.client.stub_responses(:create_bucket, "TestError") - expect(wrapper.create?("us-test-2")).to be_eql(false) + bucket.client.stub_responses(:create_bucket, 'TestError') + expect(wrapper.create?('us-test-2')).to be_eql(false) end - it "confirms bucket location" do - loc = "us-test-2" + it 'confirms bucket location' do + loc = 'us-test-2' stub_data = bucket.client.stub_data(:get_bucket_location, { location_constraint: loc }) bucket.client.stub_responses(:get_bucket_location, stub_data) expect(wrapper.location).to be_eql(loc) end it "confirms error is caught when bucket location can't be retrieved" do - bucket.client.stub_responses(:get_bucket_location, "TestError") + bucket.client.stub_responses(:get_bucket_location, 'TestError') expect(wrapper.location).to start_with("Couldn't get the location") end end diff --git a/ruby/example_code/s3/spec/bucket_list_objects_spec.rb b/ruby/example_code/s3/spec/bucket_list_objects_spec.rb index e8a73fbd7c9..808dedf3de3 100644 --- a/ruby/example_code/s3/spec/bucket_list_objects_spec.rb +++ b/ruby/example_code/s3/spec/bucket_list_objects_spec.rb @@ -1,22 +1,22 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_list_objects" +require 'rspec' +require_relative '../bucket_list_objects' describe BucketListObjectsWrapper do - let(:bucket_name) { "test-bucket" } + let(:bucket_name) { 'test-bucket' } let(:bucket) { Aws::S3::Bucket.new(bucket_name, stub_responses: true) } let(:wrapper) { BucketListObjectsWrapper.new(bucket) } - it "confirms the objects were listed" do - data = bucket.client.stub_data(:list_objects_v2, { contents: [{ key: "test-1" }, { key: "test-2" }] }) + it 'confirms the objects were listed' do + data = bucket.client.stub_data(:list_objects_v2, { contents: [{ key: 'test-1' }, { key: 'test-2' }] }) bucket.client.stub_responses(:list_objects_v2, data) expect(wrapper.list_objects(5)).to be_eql(2) end it "confirms error is caught when objects can't be listed" do - bucket.client.stub_responses(:list_objects_v2, "TestError") + bucket.client.stub_responses(:list_objects_v2, 'TestError') expect(wrapper.list_objects(5)).to be_eql(0) end end diff --git a/ruby/example_code/s3/spec/bucket_list_spec.rb b/ruby/example_code/s3/spec/bucket_list_spec.rb index 6e89850fd88..d7b2a274356 100644 --- a/ruby/example_code/s3/spec/bucket_list_spec.rb +++ b/ruby/example_code/s3/spec/bucket_list_spec.rb @@ -1,24 +1,24 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_list" +require 'rspec' +require_relative '../bucket_list' describe BucketListWrapper do let(:resource) { Aws::S3::Resource.new(stub_responses: true) } subject { BucketListWrapper.new(resource) } - it "confirms buckets were listed" do + it 'confirms buckets were listed' do data = resource.client.stub_data( :list_buckets, - { 'buckets': [{ 'name': "bucket-1" }, { 'name': "bucket-2" }] } + { 'buckets': [{ 'name': 'bucket-1' }, { 'name': 'bucket-2' }] } ) resource.client.stub_responses(:list_buckets, data) expect(subject.list_buckets(20)).to be(true) end it "confirms error is caught when bucket can't be created" do - resource.client.stub_responses(:list_buckets, "TestError") + resource.client.stub_responses(:list_buckets, 'TestError') expect(subject.list_buckets(20)).to be(false) end end diff --git a/ruby/example_code/s3/spec/bucket_policy_spec.rb b/ruby/example_code/s3/spec/bucket_policy_spec.rb index c021e1947bd..5e1eabef04e 100644 --- a/ruby/example_code/s3/spec/bucket_policy_spec.rb +++ b/ruby/example_code/s3/spec/bucket_policy_spec.rb @@ -1,45 +1,45 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_policy" +require 'rspec' +require_relative '../bucket_policy' describe BucketPolicyWrapper do - let(:bucket_name) { "test-bucket" } + let(:bucket_name) { 'test-bucket' } let(:bucket_policy) { Aws::S3::BucketPolicy.new(bucket_name, stub_responses: true) } let(:wrapper) { BucketPolicyWrapper.new(bucket_policy) } - it "confirms policy was set" do + it 'confirms policy was set' do bucket_policy.client.stub_responses(:put_bucket_policy) - expect(wrapper.set_policy("test policy")).to be_eql(true) + expect(wrapper.set_policy('test policy')).to be_eql(true) end it "confirms error is caught when policy can't be set" do - bucket_policy.client.stub_responses(:put_bucket_policy, "TestError") - expect(wrapper.set_policy("test policy")).to be_eql(false) + bucket_policy.client.stub_responses(:put_bucket_policy, 'TestError') + expect(wrapper.set_policy('test policy')).to be_eql(false) end - it "confirms policy was retrieved" do - policy = "test policy" + it 'confirms policy was retrieved' do + policy = 'test policy' data = bucket_policy.client.stub_data( - :get_bucket_policy, { policy: "test policy" } + :get_bucket_policy, { policy: 'test policy' } ) bucket_policy.client.stub_responses(:get_bucket_policy, data) expect(wrapper.get_policy).to be_eql(policy) end it "confirms error is caught when policy can't be retrieved" do - bucket_policy.client.stub_responses(:get_bucket_policy, "TestError") + bucket_policy.client.stub_responses(:get_bucket_policy, 'TestError') expect(wrapper.get_policy).to be_nil end - it "confirms policy was deleted" do + it 'confirms policy was deleted' do bucket_policy.client.stub_responses(:delete_bucket_policy) expect(wrapper.delete_policy).to be_eql(true) end it "confirms error is caught when policy can't be deleted" do - bucket_policy.client.stub_responses(:delete_bucket_policy, "TestError") + bucket_policy.client.stub_responses(:delete_bucket_policy, 'TestError') expect(wrapper.delete_policy).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/bucket_put_encryption_spec.rb b/ruby/example_code/s3/spec/bucket_put_encryption_spec.rb index c7d900a168d..84ee962367c 100644 --- a/ruby/example_code/s3/spec/bucket_put_encryption_spec.rb +++ b/ruby/example_code/s3/spec/bucket_put_encryption_spec.rb @@ -1,20 +1,20 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_put_encryption" +require 'rspec' +require_relative '../bucket_put_encryption' describe BucketEncryptionWrapper do let(:client) { Aws::S3::Client.new(stub_responses: true) } subject { BucketEncryptionWrapper.new(client) } - it "confirms the encryption state was set" do + it 'confirms the encryption state was set' do client.stub_responses(:put_bucket_encryption) - expect(subject.set_encryption("test-bucket")).to be_eql(true) + expect(subject.set_encryption('test-bucket')).to be_eql(true) end it "confirms error is caught when objects can't be listed" do - client.stub_responses(:put_bucket_encryption, "TestError") - expect(subject.set_encryption("test-bucket")).to be_eql(false) + client.stub_responses(:put_bucket_encryption, 'TestError') + expect(subject.set_encryption('test-bucket')).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/bucket_put_website_spec.rb b/ruby/example_code/s3/spec/bucket_put_website_spec.rb index 1bf659ec70b..af458b19c0f 100644 --- a/ruby/example_code/s3/spec/bucket_put_website_spec.rb +++ b/ruby/example_code/s3/spec/bucket_put_website_spec.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../bucket_put_website" +require 'rspec' +require_relative '../bucket_put_website' describe BucketWebsiteWrapper do - let(:bucket_name) { "test-bucket" } + let(:bucket_name) { 'test-bucket' } let(:bucket_website) { Aws::S3::BucketWebsite.new(bucket_name, stub_responses: true) } let(:wrapper) { BucketWebsiteWrapper.new(bucket_website) } - it "confirms the website was set" do + it 'confirms the website was set' do bucket_website.client.stub_responses(:put_bucket_website) - expect(wrapper.set_website("index-test", "error-test")).to be_eql(true) + expect(wrapper.set_website('index-test', 'error-test')).to be_eql(true) end it "confirms error is caught when the website can't be set" do - bucket_website.client.stub_responses(:put_bucket_website, "TestError") - expect(wrapper.set_website("index-test", "error-test")).to be_eql(false) + bucket_website.client.stub_responses(:put_bucket_website, 'TestError') + expect(wrapper.set_website('index-test', 'error-test')).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/object_copy_encrypt_spec.rb b/ruby/example_code/s3/spec/object_copy_encrypt_spec.rb index d1af92d8e1a..c3ce3d5b5c9 100644 --- a/ruby/example_code/s3/spec/object_copy_encrypt_spec.rb +++ b/ruby/example_code/s3/spec/object_copy_encrypt_spec.rb @@ -1,23 +1,23 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_copy_encrypt" +require 'rspec' +require_relative '../object_copy_encrypt' describe ObjectCopyEncryptWrapper do - let(:source_object) { Aws::S3::Object.new("test-source-bucket", "test-source-key", stub_responses: true) } - let(:target_bucket) { Aws::S3::Bucket.new("test-target-bucket", stub_responses: true) } + let(:source_object) { Aws::S3::Object.new('test-source-bucket', 'test-source-key', stub_responses: true) } + let(:target_bucket) { Aws::S3::Bucket.new('test-target-bucket', stub_responses: true) } let(:wrapper) { ObjectCopyEncryptWrapper.new(source_object) } - it "confirms the object was copied" do + it 'confirms the object was copied' do source_object.client.stub_responses(:copy_object) - target_obj = wrapper.copy_object(target_bucket, "test-target-key", "ServerSideEncryption") - expect(target_obj.key).to be_eql("test-target-key") - expect(target_obj.server_side_encryption).to be_eql("ServerSideEncryption") + target_obj = wrapper.copy_object(target_bucket, 'test-target-key', 'ServerSideEncryption') + expect(target_obj.key).to be_eql('test-target-key') + expect(target_obj.server_side_encryption).to be_eql('ServerSideEncryption') end it "confirms error is caught when object can't be copied" do - source_object.client.stub_responses(:copy_object, "TestError") - expect(wrapper.copy_object(target_bucket, "test-target-key", "ServerSideEncryption")).to be_nil + source_object.client.stub_responses(:copy_object, 'TestError') + expect(wrapper.copy_object(target_bucket, 'test-target-key', 'ServerSideEncryption')).to be_nil end end diff --git a/ruby/example_code/s3/spec/object_copy_spec.rb b/ruby/example_code/s3/spec/object_copy_spec.rb index 98c026c96fd..a4dfe1747d9 100644 --- a/ruby/example_code/s3/spec/object_copy_spec.rb +++ b/ruby/example_code/s3/spec/object_copy_spec.rb @@ -1,22 +1,22 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_copy" +require 'rspec' +require_relative '../object_copy' describe ObjectCopyWrapper do - let(:source_object) { Aws::S3::Object.new("test-source-bucket", "test-source-key", stub_responses: true) } - let(:target_bucket) { Aws::S3::Bucket.new("test-target-bucket", stub_responses: true) } + let(:source_object) { Aws::S3::Object.new('test-source-bucket', 'test-source-key', stub_responses: true) } + let(:target_bucket) { Aws::S3::Bucket.new('test-target-bucket', stub_responses: true) } let(:wrapper) { ObjectCopyWrapper.new(source_object) } - it "confirms the object was copied" do + it 'confirms the object was copied' do source_object.client.stub_responses(:copy_object) - target_obj = wrapper.copy_object(target_bucket, "test-target-key") - expect(target_obj.key).to be_eql("test-target-key") + target_obj = wrapper.copy_object(target_bucket, 'test-target-key') + expect(target_obj.key).to be_eql('test-target-key') end it "confirms error is caught when object can't be copied" do - source_object.client.stub_responses(:copy_object, "TestError") - expect(wrapper.copy_object(target_bucket, "test-target-key")).to be_nil + source_object.client.stub_responses(:copy_object, 'TestError') + expect(wrapper.copy_object(target_bucket, 'test-target-key')).to be_nil end end diff --git a/ruby/example_code/s3/spec/object_exists_spec.rb b/ruby/example_code/s3/spec/object_exists_spec.rb index 5a358486d60..20017361225 100644 --- a/ruby/example_code/s3/spec/object_exists_spec.rb +++ b/ruby/example_code/s3/spec/object_exists_spec.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_exists" +require 'rspec' +require_relative '../object_exists' describe ObjectExistsWrapper do - let(:object) { Aws::S3::Object.new("test-bucket", "test-key", stub_responses: true) } + let(:object) { Aws::S3::Object.new('test-bucket', 'test-key', stub_responses: true) } let(:wrapper) { ObjectExistsWrapper.new(object) } - it "confirms the object exists" do - object.client.stub_responses(:head_object, { status_code: 200, headers: {}, body: "body" }) + it 'confirms the object exists' do + object.client.stub_responses(:head_object, { status_code: 200, headers: {}, body: 'body' }) exists = wrapper.exists? expect(exists).to be_eql(true) end it "confirms error is caught when object can't be retrieved" do - object.client.stub_responses(:head_object, "TestError") + object.client.stub_responses(:head_object, 'TestError') expect(wrapper.exists?).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/object_get_encryption_spec.rb b/ruby/example_code/s3/spec/object_get_encryption_spec.rb index 888548bf050..2629839c87f 100644 --- a/ruby/example_code/s3/spec/object_get_encryption_spec.rb +++ b/ruby/example_code/s3/spec/object_get_encryption_spec.rb @@ -1,22 +1,22 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_get_encryption" +require 'rspec' +require_relative '../object_get_encryption' describe ObjectGetEncryptionWrapper do - let(:object) { Aws::S3::Object.new("test-bucket", "test-key", stub_responses: true) } + let(:object) { Aws::S3::Object.new('test-bucket', 'test-key', stub_responses: true) } let(:wrapper) { ObjectGetEncryptionWrapper.new(object) } - it "confirms the object encryption state was retrieved" do - obj_data = object.client.stub_data(:get_object, { server_side_encryption: "TEST" }) + it 'confirms the object encryption state was retrieved' do + obj_data = object.client.stub_data(:get_object, { server_side_encryption: 'TEST' }) object.client.stub_responses(:get_object, obj_data) obj = wrapper.get_object - expect(obj.server_side_encryption).to be_eql("TEST") + expect(obj.server_side_encryption).to be_eql('TEST') end it "confirms error is caught when object can't be retrieved" do - object.client.stub_responses(:get_object, "TestError") + object.client.stub_responses(:get_object, 'TestError') expect(wrapper.get_object).to be_nil end end diff --git a/ruby/example_code/s3/spec/object_get_spec.rb b/ruby/example_code/s3/spec/object_get_spec.rb index f8da96a31c9..116c2ea043d 100644 --- a/ruby/example_code/s3/spec/object_get_spec.rb +++ b/ruby/example_code/s3/spec/object_get_spec.rb @@ -1,22 +1,22 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_get" +require 'rspec' +require_relative '../object_get' describe ObjectGetWrapper do - let(:object) { Aws::S3::Object.new("test-bucket", "test-key", stub_responses: true) } + let(:object) { Aws::S3::Object.new('test-bucket', 'test-key', stub_responses: true) } let(:wrapper) { ObjectGetWrapper.new(object) } - it "confirms the object was retrieved" do + it 'confirms the object was retrieved' do obj_data = object.client.stub_data(:get_object, { content_length: 100 }) object.client.stub_responses(:get_object, obj_data) - obj = wrapper.get_object("test-file-name.txt") + obj = wrapper.get_object('test-file-name.txt') expect(obj.content_length).to be_eql(100) end it "confirms error is caught when object can't be retrieved" do - object.client.stub_responses(:get_object, "TestError") - expect(wrapper.get_object("test-file-name.txt")).to be_nil + object.client.stub_responses(:get_object, 'TestError') + expect(wrapper.get_object('test-file-name.txt')).to be_nil end end diff --git a/ruby/example_code/s3/spec/object_presigned_url_upload_spec.rb b/ruby/example_code/s3/spec/object_presigned_url_upload_spec.rb index d2146543fde..701de921afd 100644 --- a/ruby/example_code/s3/spec/object_presigned_url_upload_spec.rb +++ b/ruby/example_code/s3/spec/object_presigned_url_upload_spec.rb @@ -1,14 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_presigned_url_upload" +require 'rspec' +require_relative '../object_presigned_url_upload' -describe "object_presigned_url_upload" do - let(:bucket) { Aws::S3::Bucket.new("test-bucket") } +describe 'object_presigned_url_upload' do + let(:bucket) { Aws::S3::Bucket.new('test-bucket') } - it "confirms the presigned URL is created" do - url = get_presigned_url(bucket, "test-key") + it 'confirms the presigned URL is created' do + url = get_presigned_url(bucket, 'test-key') expect(url).not_to be_nil end end diff --git a/ruby/example_code/s3/spec/object_put_spec.rb b/ruby/example_code/s3/spec/object_put_spec.rb index bdc04c67966..e183b2cc221 100644 --- a/ruby/example_code/s3/spec/object_put_spec.rb +++ b/ruby/example_code/s3/spec/object_put_spec.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_put" +require 'rspec' +require_relative '../object_put' describe ObjectPutWrapper do - let(:object) { Aws::S3::Object.new("test-bucket", "test-key", stub_responses: true) } + let(:object) { Aws::S3::Object.new('test-bucket', 'test-key', stub_responses: true) } let(:wrapper) { ObjectPutWrapper.new(object) } - it "confirms the object was put" do + it 'confirms the object was put' do object.client.stub_responses(:put_object) success = wrapper.put_object(__FILE__) expect(success).to be_eql(true) end it "confirms error is caught when object can't be put" do - object.client.stub_responses(:put_object, "TestError") + object.client.stub_responses(:put_object, 'TestError') expect(wrapper.put_object(__FILE__)).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/object_put_sse_spec.rb b/ruby/example_code/s3/spec/object_put_sse_spec.rb index da5f0e201ec..8b5534d677b 100644 --- a/ruby/example_code/s3/spec/object_put_sse_spec.rb +++ b/ruby/example_code/s3/spec/object_put_sse_spec.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_put_sse" +require 'rspec' +require_relative '../object_put_sse' describe ObjectPutSseWrapper do - let(:object) { Aws::S3::Object.new("test-bucket", "test-key", stub_responses: true) } + let(:object) { Aws::S3::Object.new('test-bucket', 'test-key', stub_responses: true) } let(:wrapper) { ObjectPutSseWrapper.new(object) } - it "confirms the object was put" do + it 'confirms the object was put' do object.client.stub_responses(:put_object) - success = wrapper.put_object_encrypted("Test content", "TEST") + success = wrapper.put_object_encrypted('Test content', 'TEST') expect(success).to be_eql(true) end it "confirms error is caught when object can't be put" do - object.client.stub_responses(:put_object, "TestError") - expect(wrapper.put_object_encrypted("Test content", "TEST")).to be_eql(false) + object.client.stub_responses(:put_object, 'TestError') + expect(wrapper.put_object_encrypted('Test content', 'TEST')).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/object_upload_file_spec.rb b/ruby/example_code/s3/spec/object_upload_file_spec.rb index e58405dae0f..b8aa63114c6 100644 --- a/ruby/example_code/s3/spec/object_upload_file_spec.rb +++ b/ruby/example_code/s3/spec/object_upload_file_spec.rb @@ -1,21 +1,21 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../object_upload_file" +require 'rspec' +require_relative '../object_upload_file' describe ObjectUploadFileWrapper do - let(:object) { Aws::S3::Object.new("test-bucket", "test-key", stub_responses: true) } + let(:object) { Aws::S3::Object.new('test-bucket', 'test-key', stub_responses: true) } let(:wrapper) { ObjectUploadFileWrapper.new(object) } - it "confirms the object was uploaded" do + it 'confirms the object was uploaded' do object.client.stub_responses(:put_object) success = wrapper.upload_file(__FILE__) expect(success).to be_eql(true) end it "confirms error is caught when object can't be uploaded" do - object.client.stub_responses(:put_object, "TestError") + object.client.stub_responses(:put_object, 'TestError') expect(wrapper.upload_file(__FILE__)).to be_eql(false) end end diff --git a/ruby/example_code/s3/spec/scenario_getting_started_spec.rb b/ruby/example_code/s3/spec/scenario_getting_started_spec.rb index 5e4d31ee4a4..a19217088de 100644 --- a/ruby/example_code/s3/spec/scenario_getting_started_spec.rb +++ b/ruby/example_code/s3/spec/scenario_getting_started_spec.rb @@ -1,63 +1,62 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../scenario_getting_started" +require 'rspec' +require_relative '../scenario_getting_started' -describe "getting started scenario" do +describe 'getting started scenario' do after do - File.delete("download.test") if File.exist?("download.test") + File.delete('download.test') if File.exist?('download.test') end - context "runs against AWS (integration tests)", integ: true do - - it "runs without errors", integ: true do + context 'runs against AWS (integration tests)', integ: true do + it 'runs without errors', integ: true do s3_resource = Aws::S3::Resource.new scenario = ScenarioGettingStarted.new(s3_resource) allow(scenario).to receive(:gets).and_return( - __FILE__, "y", "download.test", "y", "y" + __FILE__, 'y', 'download.test', 'y', 'y' ) - expect { run_scenario(scenario) }.not_to output("Something went wrong with the demo!").to_stdout + expect { run_scenario(scenario) }.not_to output('Something went wrong with the demo!').to_stdout end end - context "runs using stubs" do + context 'runs using stubs' do let(:s3_resource) { Aws::S3::Resource.new(stub_responses: true) } let(:scenario) { ScenarioGettingStarted.new(s3_resource) } - inputs = [__FILE__, "y", "download.test", "y", "y"] + inputs = [__FILE__, 'y', 'download.test', 'y', 'y'] - it "runs without errors" do + it 'runs without errors' do allow(scenario).to receive(:gets).and_return(*inputs) - expect { run_scenario(scenario) }.not_to output("Something went wrong with the demo!").to_stdout + expect { run_scenario(scenario) }.not_to output('Something went wrong with the demo!').to_stdout end - it "outputs correct error when create_bucket fails" do - s3_resource.client.stub_responses(:create_bucket, "TestError") + it 'outputs correct error when create_bucket fails' do + s3_resource.client.stub_responses(:create_bucket, 'TestError') allow(scenario).to receive(:gets).and_return(*inputs) expect { run_scenario(scenario) }.to output(/TestError: stubbed-response-error-message/).to_stdout end - it "outputs correct error when upload_file fails" do - s3_resource.client.stub_responses(:put_object, "TestError") + it 'outputs correct error when upload_file fails' do + s3_resource.client.stub_responses(:put_object, 'TestError') allow(scenario).to receive(:gets).and_return(*inputs) expect { run_scenario(scenario) }.to output(/TestError: stubbed-response-error-message/).to_stdout end - it "outputs correct error when copy_object fails" do - s3_resource.client.stub_responses(:copy_object, "TestError") + it 'outputs correct error when copy_object fails' do + s3_resource.client.stub_responses(:copy_object, 'TestError') allow(scenario).to receive(:gets).and_return(*inputs) expect { run_scenario(scenario) }.to output(/TestError: stubbed-response-error-message/).to_stdout end - it "outputs correct error when list_objects fails" do - s3_resource.client.stub_responses(:create_bucket, "TestError") + it 'outputs correct error when list_objects fails' do + s3_resource.client.stub_responses(:create_bucket, 'TestError') allow(scenario).to receive(:gets).and_return(*inputs) expect { run_scenario(scenario) }.to output(/TestError: stubbed-response-error-message/).to_stdout end - it "outputs correct error when delete_bucket fails" do - s3_resource.client.stub_responses(:create_bucket, "TestError") + it 'outputs correct error when delete_bucket fails' do + s3_resource.client.stub_responses(:create_bucket, 'TestError') allow(scenario).to receive(:gets).and_return(*inputs) expect { run_scenario(scenario) }.to output(/TestError: stubbed-response-error-message/).to_stdout end diff --git a/ruby/example_code/secretsmanager/sm_get_secrets.rb b/ruby/example_code/secretsmanager/sm_get_secrets.rb index 79befc9b554..05de2192fe2 100644 --- a/ruby/example_code/secretsmanager/sm_get_secrets.rb +++ b/ruby/example_code/secretsmanager/sm_get_secrets.rb @@ -9,27 +9,23 @@ # snippet-start:[s3.ruby.sm_get_secrets.rb] -require "aws-sdk-secretsmanager" +require 'aws-sdk-secretsmanager' # Gets all secrets in us-west-2 # Replace us-west-2 with the AWS Region you're using for Amazon Secrets Manager. -sm = Aws::SecretsManager::Client.new(region: "us-west-2") +sm = Aws::SecretsManager::Client.new(region: 'us-west-2') resp = sm.list_secrets -puts "Secrets:" +puts 'Secrets:' resp.secret_list.each do |s| - puts " name: " + s.name - puts " key/value:" + puts " name: #{s.name}" + puts ' key/value:' resp = sm.get_secret_value(secret_id: s.name) - if resp.secret_string - puts " " + resp.secret_string - else - # do something with resp.secret_binary - end + puts " #{resp.secret_string}" if resp.secret_string puts end diff --git a/ruby/example_code/ses/v1/list_identities.rb b/ruby/example_code/ses/v1/list_identities.rb index f3120ccc61c..a8de1feeabd 100644 --- a/ruby/example_code/ses/v1/list_identities.rb +++ b/ruby/example_code/ses/v1/list_identities.rb @@ -6,27 +6,25 @@ # snippet-start:[ruby.example_code.ses.v1.list_identities] -require "aws-sdk-ses" # v2: require 'aws-sdk' +require 'aws-sdk-ses' # v2: require 'aws-sdk' # Create client in us-west-2 region # Replace us-west-2 with the AWS Region you're using for Amazon SES. -client = Aws::SES::Client.new(region: "us-west-2") +client = Aws::SES::Client.new(region: 'us-west-2') # Get up to 1000 identities ids = client.list_identities({ - identity_type: "EmailAddress" -}) + identity_type: 'EmailAddress' + }) ids.identities.each do |email| attrs = client.get_identity_verification_attributes({ - identities: [email] - }) + identities: [email] + }) status = attrs.verification_attributes[email].verification_status # Display email addresses that have been verified - if status == "Success" - puts email - end + puts email if status == 'Success' end # snippet-end:[ruby.example_code.ses.v1.list_identities] diff --git a/ruby/example_code/ses/v1/ses_get_statistics.rb b/ruby/example_code/ses/v1/ses_get_statistics.rb index 63197696260..b3db2185cf4 100644 --- a/ruby/example_code/ses/v1/ses_get_statistics.rb +++ b/ruby/example_code/ses/v1/ses_get_statistics.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-sesv2" # Ensure you're using the aws-sdk-sesv2 gem for AWS SDK for Ruby V3. +require 'aws-sdk-sesv2' # Ensure you're using the aws-sdk-sesv2 gem for AWS SDK for Ruby V3. # This class encapsulates operations for fetching Amazon Simple Email Service (Amazon SES) sending statistics. class SESStatisticsFetcher @@ -42,8 +42,8 @@ def print_data_point(dp) end # If something goes wrong, display an error message. -rescue Aws::SES::Errors::ServiceError => error - puts "Error: #{error}" +rescue Aws::SES::Errors::ServiceError => e + puts "Error: #{e}" end # Example usage: diff --git a/ruby/example_code/ses/v1/ses_send_email.rb b/ruby/example_code/ses/v1/ses_send_email.rb index 9cd252ca98a..33f95b2e828 100644 --- a/ruby/example_code/ses/v1/ses_send_email.rb +++ b/ruby/example_code/ses/v1/ses_send_email.rb @@ -6,39 +6,39 @@ # snippet-start:[ruby.example_code.ses.v1.send_email] -require "aws-sdk-ses" # v2: require 'aws-sdk' +require 'aws-sdk-ses' # v2: require 'aws-sdk' # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. -sender = "sender@example.com" +sender = 'sender@example.com' # Replace recipient@example.com with a "To" address. If your account # is still in the sandbox, this address must be verified. -recipient = "recipient@example.com" +recipient = 'recipient@example.com' # Specify a configuration set. To use a configuration # set, uncomment the next line and line 74. # configsetname = "ConfigSet" # The subject line for the email. -subject = "Amazon SES test (AWS SDK for Ruby)" +subject = 'Amazon SES test (AWS SDK for Ruby)' # The HTML body of the email. htmlbody = - "

Amazon SES test (AWS SDK for Ruby)

"\ + '

Amazon SES test (AWS SDK for Ruby)

'\ '

This email was sent with '\ 'Amazon SES using the '\ - "AWS SDK for Ruby." + 'AWS SDK for Ruby.' # The email body for recipients with non-HTML email clients. -textbody = "This email was sent with Amazon SES using the AWS SDK for Ruby." +textbody = 'This email was sent with Amazon SES using the AWS SDK for Ruby.' # Specify the text encoding scheme. -encoding = "UTF-8" +encoding = 'UTF-8' # Create a new SES client in the us-west-2 region. # Replace us-west-2 with the AWS Region you're using for Amazon SES. -ses = Aws::SES::Client.new(region: "us-west-2") +ses = Aws::SES::Client.new(region: 'us-west-2') # Try to send the email. begin @@ -65,15 +65,15 @@ data: subject } }, - source: sender, + source: sender # Uncomment the following line to use a configuration set. # configuration_set_name: configsetname, - ) + ) - puts "Email sent to " + recipient + puts "Email sent to #{recipient}" # If something goes wrong, display an error message. -rescue Aws::SES::Errors::ServiceError => error - puts "Email not sent. Error message: #{error}" +rescue Aws::SES::Errors::ServiceError => e + puts "Email not sent. Error message: #{e}" end # snippet-end:[ruby.example_code.ses.v1.send_email] diff --git a/ruby/example_code/ses/v1/ses_send_verification.rb b/ruby/example_code/ses/v1/ses_send_verification.rb index 7e4d91c8099..53b8ef992b4 100644 --- a/ruby/example_code/ses/v1/ses_send_verification.rb +++ b/ruby/example_code/ses/v1/ses_send_verification.rb @@ -6,25 +6,25 @@ # snippet-start:[ruby.example_code.ses.v1.send_verification] -require "aws-sdk-ses" # v2: require 'aws-sdk' +require 'aws-sdk-ses' # v2: require 'aws-sdk' # Replace recipient@example.com with a "To" address. -recipient = "recipient@example.com" +recipient = 'recipient@example.com' # Create a new SES resource in the us-west-2 region. # Replace us-west-2 with the AWS Region you're using for Amazon SES. -ses = Aws::SES::Client.new(region: "us-west-2") +ses = Aws::SES::Client.new(region: 'us-west-2') # Try to verify email address. begin ses.verify_email_identity({ - email_address: recipient - }) + email_address: recipient + }) - puts "Email sent to " + recipient + puts "Email sent to #{recipient}" # If something goes wrong, display an error message. -rescue Aws::SES::Errors::ServiceError => error - puts "Email not sent. Error message: #{error}" +rescue Aws::SES::Errors::ServiceError => e + puts "Email not sent. Error message: #{e}" end # snippet-end:[ruby.example_code.ses.v1.send_verification] diff --git a/ruby/example_code/ses/v2/config.rb b/ruby/example_code/ses/v2/config.rb index e95120080a9..3764786c289 100644 --- a/ruby/example_code/ses/v2/config.rb +++ b/ruby/example_code/ses/v2/config.rb @@ -2,11 +2,11 @@ # SPDX-License-Identifier: Apache-2.0 # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. -SENDER_EMAIL = "sender@example.com" +SENDER_EMAIL = 'sender@example.com'.freeze # Replace recipient@example.com with a "To" address. If your account # is still in the sandbox, this address must be verified. -RECIPIENT_EMAIL = "recipient@example.com" +RECIPIENT_EMAIL = 'recipient@example.com'.freeze # Replace 'us-east-1' with your preferred AWS Region. -AWS_REGION = "us-east-1" +AWS_REGION = 'us-east-1'.freeze diff --git a/ruby/example_code/ses/v2/send_email.rb b/ruby/example_code/ses/v2/send_email.rb index dde093cddd0..fad0f1713e3 100644 --- a/ruby/example_code/ses/v2/send_email.rb +++ b/ruby/example_code/ses/v2/send_email.rb @@ -5,8 +5,8 @@ # This code example demonstrates how to send a message using the Amazon Simple Email Service (Amazon SES) v2 client. # snippet-start:[ruby.example_code.ses.v2.send_email] -require "aws-sdk-sesv2" -require_relative "config" # Recipient and sender email addresses. +require 'aws-sdk-sesv2' +require_relative 'config' # Recipient and sender email addresses. # Set up the SESv2 client. client = Aws::SESV2::Client.new(region: AWS_REGION) @@ -14,22 +14,22 @@ def send_email(client, sender_email, recipient_email) response = client.send_email( { - from_email_address: sender_email, - destination: { - to_addresses: [recipient_email] - }, - content: { - simple: { - subject: { - data: "Test email subject" - }, - body: { - text: { - data: "Test email body" - } - } - } - } + from_email_address: sender_email, + destination: { + to_addresses: [recipient_email] + }, + content: { + simple: { + subject: { + data: 'Test email subject' + }, + body: { + text: { + data: 'Test email body' + } + } + } + } } ) puts "Email sent from #{SENDER_EMAIL} to #{RECIPIENT_EMAIL} with message ID: #{response.message_id}" diff --git a/ruby/example_code/sns/create_subscription.rb b/ruby/example_code/sns/create_subscription.rb index 389acb5ef6c..f864663b5d0 100644 --- a/ruby/example_code/sns/create_subscription.rb +++ b/ruby/example_code/sns/create_subscription.rb @@ -2,8 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 # snippet-start:[sns.Ruby.createSubscription] -require "aws-sdk-sns" -require "logger" +require 'aws-sdk-sns' +require 'logger' # Represents a service for creating subscriptions in Amazon Simple Notification Service (SNS) class SubscriptionService @@ -23,7 +23,7 @@ def initialize(sns_client) # @return [Boolean] true if subscription was successfully created, false otherwise def create_subscription(topic_arn, protocol, endpoint) @sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint) - @logger.info("Subscription created successfully.") + @logger.info('Subscription created successfully.') true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while creating the subscription: #{e.message}") @@ -33,16 +33,16 @@ def create_subscription(topic_arn, protocol, endpoint) # Main execution if the script is run directly if $PROGRAM_NAME == __FILE__ - protocol = "email" - endpoint = "EMAIL_ADDRESS" # Should be replaced with a real email address - topic_arn = "TOPIC_ARN" # Should be replaced with a real topic ARN + protocol = 'email' + endpoint = 'EMAIL_ADDRESS' # Should be replaced with a real email address + topic_arn = 'TOPIC_ARN' # Should be replaced with a real topic ARN sns_client = Aws::SNS::Client.new subscription_service = SubscriptionService.new(sns_client) - @logger.info("Creating the subscription.") + @logger.info('Creating the subscription.') unless subscription_service.create_subscription(topic_arn, protocol, endpoint) - @logger.error("Subscription creation failed. Stopping program.") + @logger.error('Subscription creation failed. Stopping program.') exit 1 end end diff --git a/ruby/example_code/sns/create_topic.rb b/ruby/example_code/sns/create_topic.rb index 143900d9c90..7b54a751e6d 100644 --- a/ruby/example_code/sns/create_topic.rb +++ b/ruby/example_code/sns/create_topic.rb @@ -1,6 +1,6 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-sns" # Use aws-sdk-sns for AWS SDK for Ruby V3. +require 'aws-sdk-sns' # Use aws-sdk-sns for AWS SDK for Ruby V3. # snippet-start:[sns.Ruby.createTopic] # This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic. @@ -29,12 +29,12 @@ def create_topic(topic_name) # Example usage: if $PROGRAM_NAME == __FILE__ - topic_name = "YourTopicName" # Replace with your topic name + topic_name = 'YourTopicName' # Replace with your topic name sns_topic_creator = SNSTopicCreator.new puts "Creating the topic '#{topic_name}'..." unless sns_topic_creator.create_topic(topic_name) - puts "The topic was not created. Stopping program." + puts 'The topic was not created. Stopping program.' exit 1 end end diff --git a/ruby/example_code/sns/enable_resource.rb b/ruby/example_code/sns/enable_resource.rb index db36fac1dfd..c4fd12621f5 100644 --- a/ruby/example_code/sns/enable_resource.rb +++ b/ruby/example_code/sns/enable_resource.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-sns" -require "logger" +require 'aws-sdk-sns' +require 'logger' # snippet-start:[sns.Ruby.enableResource] # Service class to enable an SNS resource with a specified policy @@ -41,29 +41,29 @@ def enable_resource(topic_arn, resource_arn, policy_name) # @return [String] The policy as a JSON string def generate_policy(topic_arn, resource_arn) { - Version: "2008-10-17", - Id: "__default_policy_ID", + Version: '2008-10-17', + Id: '__default_policy_ID', Statement: [{ - Sid: "__default_statement_ID", - Effect: "Allow", - Principal: { "AWS": "*" }, - Action: ["SNS:Publish"], - Resource: topic_arn, - Condition: { - ArnEquals: { - "AWS:SourceArn": resource_arn - } - } - }] + Sid: '__default_statement_ID', + Effect: 'Allow', + Principal: { "AWS": '*' }, + Action: ['SNS:Publish'], + Resource: topic_arn, + Condition: { + ArnEquals: { + "AWS:SourceArn": resource_arn + } + } + }] }.to_json end end # Example usage: if $PROGRAM_NAME == __FILE__ - topic_arn = "MY_TOPIC_ARN" # Should be replaced with a real topic ARN - resource_arn = "MY_RESOURCE_ARN" # Should be replaced with a real resource ARN - policy_name = "POLICY_NAME" # Typically, this is "Policy" + topic_arn = 'MY_TOPIC_ARN' # Should be replaced with a real topic ARN + resource_arn = 'MY_RESOURCE_ARN' # Should be replaced with a real resource ARN + policy_name = 'POLICY_NAME' # Typically, this is "Policy" sns_resource = Aws::SNS::Resource.new enabler = SnsResourceEnabler.new(sns_resource) diff --git a/ruby/example_code/sns/send_message.rb b/ruby/example_code/sns/send_message.rb index c977eca8c33..efa281f25a4 100644 --- a/ruby/example_code/sns/send_message.rb +++ b/ruby/example_code/sns/send_message.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.00 -require "aws-sdk-sns" -require "logger" +require 'aws-sdk-sns' +require 'logger' # snippet-start:[sns.Ruby.sendMessage] # Service class for sending messages using Amazon Simple Notification Service (SNS) @@ -31,15 +31,15 @@ def send_message(topic_arn, message) # Example usage: if $PROGRAM_NAME == __FILE__ - topic_arn = "SNS_TOPIC_ARN" # Should be replaced with a real topic ARN - message = "MESSAGE" # Should be replaced with the actual message content + topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN + message = 'MESSAGE' # Should be replaced with the actual message content sns_client = Aws::SNS::Client.new message_sender = SnsMessageSender.new(sns_client) - @logger.info("Sending message.") + @logger.info('Sending message.') unless message_sender.send_message(topic_arn, message) - @logger.error("Message sending failed. Stopping program.") + @logger.error('Message sending failed. Stopping program.') exit 1 end end diff --git a/ruby/example_code/sns/show_subscriptions.rb b/ruby/example_code/sns/show_subscriptions.rb index 9650f540c84..1d8785c71df 100644 --- a/ruby/example_code/sns/show_subscriptions.rb +++ b/ruby/example_code/sns/show_subscriptions.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-sns" -require "logger" +require 'aws-sdk-sns' +require 'logger' # snippet-start:[sns.Ruby.showSubscription] # This class demonstrates how to list subscriptions to an Amazon Simple Notification Service (SNS) topic @@ -30,7 +30,7 @@ def list_subscriptions(topic_arn) # Example usage: if $PROGRAM_NAME == __FILE__ sns_client = Aws::SNS::Client.new - topic_arn = "SNS_TOPIC_ARN" # Replace with your SNS topic ARN + topic_arn = 'SNS_TOPIC_ARN' # Replace with your SNS topic ARN lister = SnsSubscriptionLister.new(sns_client) begin diff --git a/ruby/example_code/sns/show_topics.rb b/ruby/example_code/sns/show_topics.rb index 64c15a4ec08..86f632c3088 100644 --- a/ruby/example_code/sns/show_topics.rb +++ b/ruby/example_code/sns/show_topics.rb @@ -10,28 +10,26 @@ # snippet-start:[sns.Ruby.showTopics] -require "aws-sdk-sns" # v2: require 'aws-sdk' +require 'aws-sdk-sns' # v2: require 'aws-sdk' def list_topics?(sns_client) sns_client.topics.each do |topic| puts topic.arn -rescue StandardError => e - puts "Error while listing the topics: #{e.message}" + rescue StandardError => e + puts "Error while listing the topics: #{e.message}" end end def run_me - - region = "REGION" + region = 'REGION' sns_client = Aws::SNS::Resource.new(region: region) - puts "Listing the topics." + puts 'Listing the topics.' - if list_topics?(sns_client) - else - puts "The bucket was not created. Stopping program." - exit 1 - end + return if list_topics?(sns_client) + + puts 'The bucket was not created. Stopping program.' + exit 1 end # Example usage: diff --git a/ruby/example_code/sns/spec/create_subscriptions_spec.rb b/ruby/example_code/sns/spec/create_subscriptions_spec.rb index c751ea70062..de584821543 100644 --- a/ruby/example_code/sns/spec/create_subscriptions_spec.rb +++ b/ruby/example_code/sns/spec/create_subscriptions_spec.rb @@ -1,29 +1,29 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-sns" -require "rspec" -require_relative "../create_subscription" +require 'aws-sdk-sns' +require 'rspec' +require_relative '../create_subscription' RSpec.describe SubscriptionService do let(:sns_client) { Aws::SNS::Client.new } let(:service) { SubscriptionService.new(sns_client) } - let(:topic_arn) { "your-test-topic-arn" } # Replace with your test topic ARN - let(:protocol) { "email" } - let(:endpoint) { "your-email@example.com" } # Replace with a valid email for testing + let(:topic_arn) { 'your-test-topic-arn' } # Replace with your test topic ARN + let(:protocol) { 'email' } + let(:endpoint) { 'your-email@example.com' } # Replace with a valid email for testing - describe "#create_subscription" do - it "creates a subscription successfully" do - VCR.use_cassette("create_subscription") do # Using VCR to record AWS interactions + describe '#create_subscription' do + it 'creates a subscription successfully' do + VCR.use_cassette('create_subscription') do # Using VCR to record AWS interactions expect(service.create_subscription(topic_arn, protocol, endpoint)).to eq(true) end end - context "when AWS service error occurs" do + context 'when AWS service error occurs' do before do - allow(sns_client).to receive(:subscribe).and_raise(Aws::SNS::Errors::ServiceError.new("", "test error")) + allow(sns_client).to receive(:subscribe).and_raise(Aws::SNS::Errors::ServiceError.new('', 'test error')) end - it "logs an error and returns false" do + it 'logs an error and returns false' do expect(service.create_subscription(topic_arn, protocol, endpoint)).to eq(false) end end diff --git a/ruby/example_code/sns/spec/show_subscriptions_spec.rb b/ruby/example_code/sns/spec/show_subscriptions_spec.rb index 1a8c0f9d74d..7f8e9cef2b2 100644 --- a/ruby/example_code/sns/spec/show_subscriptions_spec.rb +++ b/ruby/example_code/sns/spec/show_subscriptions_spec.rb @@ -1,15 +1,15 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-sns" -require_relative "../show_subscriptions" +require 'aws-sdk-sns' +require_relative '../show_subscriptions' RSpec.describe SnsSubscriptionLister do let(:sns_client) { Aws::SNS::Client.new } - let(:topic_arn) { "SNS_TOPIC_ARN" } # Replace with your SNS topic ARN + let(:topic_arn) { 'SNS_TOPIC_ARN' } # Replace with your SNS topic ARN let(:lister) { SnsSubscriptionLister.new(sns_client) } - describe "#list_subscriptions" do - it "lists subscriptions without raising an error" do + describe '#list_subscriptions' do + it 'lists subscriptions without raising an error' do expect { lister.list_subscriptions(topic_arn) }.not_to raise_error end end diff --git a/ruby/example_code/sns/tests/test-sns-ruby-example-create-subscription.rb b/ruby/example_code/sns/tests/test-sns-ruby-example-create-subscription.rb index b62158c7e16..a5c137366c3 100644 --- a/ruby/example_code/sns/tests/test-sns-ruby-example-create-subscription.rb +++ b/ruby/example_code/sns/tests/test-sns-ruby-example-create-subscription.rb @@ -1,13 +1,13 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../create_subscription" +require_relative '../create_subscription' -describe "#subscription_created?" do +describe '#subscription_created?' do let(:sns_client) { Aws::SNS::Client.new(stub_responses: true) } - let(:endpoint) { "example@server.com" } + let(:endpoint) { 'example@server.com' } - it "confirms the subscriptions was created" do + it 'confirms the subscriptions was created' do subscriptions_data = sns_client.stub_data( :create_subscriptions ) diff --git a/ruby/example_code/sns/tests/test-sns-ruby-example-create-topic.rb b/ruby/example_code/sns/tests/test-sns-ruby-example-create-topic.rb index 6e0b534783e..fa388c9ae63 100644 --- a/ruby/example_code/sns/tests/test-sns-ruby-example-create-topic.rb +++ b/ruby/example_code/sns/tests/test-sns-ruby-example-create-topic.rb @@ -1,13 +1,13 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../create_topic" +require_relative '../create_topic' -describe "#topic_created?" do +describe '#topic_created?' do let(:sns_client) { Aws::SNS::Client.new(stub_responses: true) } - let(:name) { "doc-example-topic" } + let(:name) { 'doc-example-topic' } - it "confirms the topic was created" do + it 'confirms the topic was created' do topic_data = sns_client.stub_data( :create_topic ) diff --git a/ruby/example_code/sns/tests/test_create_bucket_snippet.rb b/ruby/example_code/sns/tests/test_create_bucket_snippet.rb index 9fd4ccbc3dd..f14829ca2f0 100644 --- a/ruby/example_code/sns/tests/test_create_bucket_snippet.rb +++ b/ruby/example_code/sns/tests/test_create_bucket_snippet.rb @@ -1,20 +1,24 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../create_bucket_snippet" +require_relative '../create_bucket_snippet' -describe "#bucket_created?" do +describe '#bucket_created?' do let(:s3_client) { Aws::S3::Client.new(stub_responses: true) } +<<<<<<< HEAD let(:bucket_name) { "amzn-s3-demo-bucket" } +======= + let(:bucket_name) { 'doc-example-bucket' } +>>>>>>> 999c6133e (fixes) - it "confirms the bucket was created" do + it 'confirms the bucket was created' do bucket_data = s3_client.stub_data( :create_bucket, { - location: "us-west-2" + location: 'us-west-2' } ) s3_client.stub_responses(:create_bucket, bucket_data) - expect(bucket_created?(s3_client, bucket_name).location).to eq("us-west-2") + expect(bucket_created?(s3_client, bucket_name).location).to eq('us-west-2') end end diff --git a/ruby/example_code/sqs/create_queue.rb b/ruby/example_code/sqs/create_queue.rb index 4c3b0c7ec62..93e21747f6b 100644 --- a/ruby/example_code/sqs/create_queue.rb +++ b/ruby/example_code/sqs/create_queue.rb @@ -6,7 +6,7 @@ # snippet-start:[ruby.example_code.sqs.CreateQueue] # This code example demonstrates how to create a queue in Amazon Simple Queue Service (Amazon SQS). -require "aws-sdk-sqs" +require 'aws-sdk-sqs' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_name [String] The name of the queue. @@ -27,16 +27,16 @@ def queue_created?(sqs_client, queue_name) # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me - region = "us-west-2" - queue_name = "my-queue" + region = 'us-west-2' + queue_name = 'my-queue' sqs_client = Aws::SQS::Client.new(region: region) puts "Creating the queue named '#{queue_name}'..." if queue_created?(sqs_client, queue_name) - puts "Queue created." + puts 'Queue created.' else - puts "Queue not created." + puts 'Queue not created.' end end diff --git a/ruby/example_code/sqs/delete_queue.rb b/ruby/example_code/sqs/delete_queue.rb index 9f0616e4222..cfb782c7f59 100644 --- a/ruby/example_code/sqs/delete_queue.rb +++ b/ruby/example_code/sqs/delete_queue.rb @@ -5,9 +5,9 @@ # This code example demonstrates how to delete an Amazon Simple Queue Service (Amazon SQS) service. # snippet-start:[ruby.example_code.sqs.DeleteQueue] -require "aws-sdk-sqs" # v2: require 'aws-sdk' +require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. -sqs = Aws::SQS::Client.new(region: "us-west-2") +sqs = Aws::SQS::Client.new(region: 'us-west-2') sqs.delete_queue(queue_url: URL) # snippet-end:[ruby.example_code.sqs.DeleteQueue] diff --git a/ruby/example_code/sqs/enable_resource.rb b/ruby/example_code/sqs/enable_resource.rb index fe14c40ba1e..42ea742b455 100644 --- a/ruby/example_code/sqs/enable_resource.rb +++ b/ruby/example_code/sqs/enable_resource.rb @@ -6,12 +6,12 @@ # Amazon Simple Queue Service (Amazon SQS) queue. # snippet-start:[sqs.Ruby.enableResource] -require "aws-sdk-sqs" # v2: require 'aws-sdk' +require 'aws-sdk-sqs' # v2: require 'aws-sdk' sqs = Aws::SQS::Client.new -policy = '{ +policy = '{ "Version":"2008-10-17", - "Id":' + my-queue-arn + '/SQSDefaultPolicy", + "Id":' + my - queue - arn + '/SQSDefaultPolicy", "Statement":[{ "Sid":"__default_statement_ID", "Effect":"Allow", @@ -19,18 +19,18 @@ "AWS":"*" }, "Action":["SQS:SendMessage"], - "Resource":"' + my-queue-arn + '", + "Resource":"' + my - queue - arn + '", "Condition":{ "ArnEquals":{ - "AWS:SourceArn":"' + my-resource-arn + '"} + "AWS:SourceArn":"' + my - resource - arn + '"} } }] }' sqs.set_queue_attributes({ - queue_url: my-queue-url, - attributes: { - Policy: policy - } -}) + queue_url: my - queue - url, + attributes: { + Policy: policy + } + }) # snippet-end:[sqs.Ruby.enableResource] diff --git a/ruby/example_code/sqs/message_visibility_timeout.rb b/ruby/example_code/sqs/message_visibility_timeout.rb index 09e6c8ba23e..7b7a182cf25 100644 --- a/ruby/example_code/sqs/message_visibility_timeout.rb +++ b/ruby/example_code/sqs/message_visibility_timeout.rb @@ -7,38 +7,38 @@ # snippet-start:[ruby.example_code.sqs.MessageVisibilityTimeout] -require "aws-sdk-sqs" # v2: require 'aws-sdk' +require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. -sqs = Aws::SQS::Client.new(region: "us-west-2") +sqs = Aws::SQS::Client.new(region: 'us-west-2') begin - queue_name = "my-queue" + queue_name = 'my-queue' queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url + # Receive up to 10 messages receive_message_result_before = sqs.receive_message({ - queue_url: queue_url, - max_number_of_messages: 10 # Receive up to 10 messages, if there are that many. - }) + queue_url: queue_url, + max_number_of_messages: 10 + }) puts "Before attempting to change message visibility timeout: received #{receive_message_result_before.messages.count} message(s)." receive_message_result_before.messages.each do |message| sqs.change_message_visibility({ - queue_url: queue_url, - receipt_handle: message.receipt_handle, - visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt. - }) + queue_url: queue_url, + receipt_handle: message.receipt_handle, + visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt. + }) end # Try to retrieve the original messages after setting their visibility timeout. receive_message_result_after = sqs.receive_message({ - queue_url: queue_url, - max_number_of_messages: 10 - }) + queue_url: queue_url, + max_number_of_messages: 10 + }) puts "\nAfter attempting to change message visibility timeout: received #{receive_message_result_after.messages.count} message(s)." - rescue Aws::SQS::Errors::NonExistentQueue - puts "Cannot receive messages for a queue named '#{receive_queue_name}', as it does not exist." + puts "Cannot receive messages for a queue named '#{queue_name}', as it does not exist." end # snippet-end:[ruby.example_code.sqs.MessageVisibilityTimeout] diff --git a/ruby/example_code/sqs/receive_messages.rb b/ruby/example_code/sqs/receive_messages.rb index 86f36637063..c8baab7a3f0 100644 --- a/ruby/example_code/sqs/receive_messages.rb +++ b/ruby/example_code/sqs/receive_messages.rb @@ -6,8 +6,8 @@ # snippet-start:[ruby.example_code.sqs.ReceiveMessages] -require "aws-sdk-sqs" -require "aws-sdk-sts" +require 'aws-sdk-sqs' +require 'aws-sdk-sts' # Receives messages in a queue in Amazon Simple Queue Service (Amazon SQS). # @@ -22,10 +22,9 @@ # 10 # ) def receive_messages(sqs_client, queue_url, max_number_of_messages = 10) - if max_number_of_messages > 10 - puts "Maximum number of messages to receive must be 10 or less. " \ - "Stopping program." + puts 'Maximum number of messages to receive must be 10 or less. ' \ + 'Stopping program.' return end @@ -35,17 +34,16 @@ def receive_messages(sqs_client, queue_url, max_number_of_messages = 10) ) if response.messages.count.zero? - puts "No messages to receive, or all messages have already " \ - "been previously received." + puts 'No messages to receive, or all messages have already ' \ + 'been previously received.' return end response.messages.each do |message| - puts "-" * 20 + puts '-' * 20 puts "Message body: #{message.body}" puts "Message ID: #{message.message_id}" end - rescue StandardError => e puts "Error receiving messages: #{e.message}" end @@ -53,16 +51,15 @@ def receive_messages(sqs_client, queue_url, max_number_of_messages = 10) # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me - region = "us-west-2" - queue_name = "my-queue" + region = 'us-west-2' + queue_name = 'my-queue' max_number_of_messages = 10 sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' - queue_url = "https://sqs." + region + ".amazonaws.com/" + - sts_client.get_caller_identity.account + "/" + queue_name + queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) diff --git a/ruby/example_code/sqs/scenario_dead_letter_queue.rb b/ruby/example_code/sqs/scenario_dead_letter_queue.rb index 849a6eb1752..af2bfec606e 100644 --- a/ruby/example_code/sqs/scenario_dead_letter_queue.rb +++ b/ruby/example_code/sqs/scenario_dead_letter_queue.rb @@ -7,58 +7,57 @@ # snippet-start:[ruby.example_code.sqs.ScenarioDeadLetterQueue] -require "aws-sdk-sqs" # v2: require 'aws-sdk' +require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Uncomment for Windows. # Aws.use_bundled_cert! # Replace us-west-2 with the AWS Region you're using for Amazon SQS. -sqs = Aws::SQS::Client.new(region: "us-west-2") +sqs = Aws::SQS::Client.new(region: 'us-west-2') # Create a queue representing a dead-letter queue. -dead_letter_queue_name = "dead-letter-queue" +dead_letter_queue_name = 'dead-letter-queue' sqs.create_queue({ - queue_name: dead_letter_queue_name -}) + queue_name: dead_letter_queue_name + }) # Get the dead letter queue's URL and ARN, so that you can associate it with an existing queue. dead_letter_queue_url = sqs.get_queue_url(queue_name: dead_letter_queue_name).queue_url dead_letter_queue_arn = sqs.get_queue_attributes({ - queue_url: dead_letter_queue_url, - attribute_names: ["QueueArn"] -}).attributes["QueueArn"] + queue_url: dead_letter_queue_url, + attribute_names: ['QueueArn'] + }).attributes['QueueArn'] # Associate the dead letter queue with an existing queue. begin - queue_name = "my-queue" + queue_name = 'my-queue' queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url # Use a redrive policy to specify the dead letter queue and its behavior. redrive_policy = { - "maxReceiveCount" => "5", # After the queue receives the same message 5 times, send that message to the dead letter queue. - "deadLetterTargetArn" => dead_letter_queue_arn + 'maxReceiveCount' => '5', # After the queue receives the same message 5 times, + 'deadLetterTargetArn' => dead_letter_queue_arn # send that message to the dead letter queue. }.to_json sqs.set_queue_attributes({ - queue_url: queue_url, - attributes: { - "RedrivePolicy" => redrive_policy - } - }) - + queue_url: queue_url, + attributes: { + 'RedrivePolicy' => redrive_policy + } + }) rescue Aws::SQS::Errors::NonExistentQueue puts "A queue named '#{queue_name}' does not exist." exit(false) end # Send a message to the queue. -puts "Sending a message..." +puts 'Sending a message...' sqs.send_message({ - queue_url: queue_url, - message_body: "I hope I get moved to the dead letter queue." -}) + queue_url: queue_url, + message_body: 'I hope I get moved to the dead letter queue.' + }) 30.downto(0) do |i| print "\rWaiting #{i} second(s) for sent message to be receivable..." @@ -77,11 +76,11 @@ # Check to see if Amazon SQS moved the message to the dead letter queue. receive_message_result = sqs.receive_message({ - queue_url: dead_letter_queue_url, - max_number_of_messages: 1 -}) + queue_url: dead_letter_queue_url, + max_number_of_messages: 1 + }) -if receive_message_result.messages.count > 0 +if receive_message_result.messages.count.positive? puts "\n#{receive_message_result.messages[0].body}" else puts "\nNo messages received." diff --git a/ruby/example_code/sqs/scenario_getting_started.rb b/ruby/example_code/sqs/scenario_getting_started.rb index a3067d83da1..87deee7c236 100644 --- a/ruby/example_code/sqs/scenario_getting_started.rb +++ b/ruby/example_code/sqs/scenario_getting_started.rb @@ -10,9 +10,9 @@ # snippet-start:[ruby.example_code.sqs.ScenarioGettingStarted] -require "aws-sdk-sqs" # v2: require 'aws-sdk' +require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. -sqs = Aws::SQS::Client.new(region: "us-west-2") +sqs = Aws::SQS::Client.new(region: 'us-west-2') # Get a list of your queues. sqs.list_queues.queue_urls.each do |queue_url| @@ -20,16 +20,16 @@ end # Create a queue. -queue_name = "my-queue" +queue_name = 'my-queue' begin sqs.create_queue({ - queue_name: queue_name, - attributes: { - "DelaySeconds" => "60", # Delay message delivery for 1 minute (60 seconds). - "MessageRetentionPeriod" => "86400" # Delete message after 1 day (24 hours * 60 minutes * 60 seconds). - } - }) + queue_name: queue_name, + attributes: { + 'DelaySeconds' => '60', # Delay message delivery for 1 minute (60 seconds). + 'MessageRetentionPeriod' => '86400' # Delete message after 1 day (24 hours * 60 minutes * 60 seconds). + } + }) rescue Aws::SQS::Errors::QueueDeletedRecently puts "A queue with the name '#{queue_name}' was recently deleted. Wait at least 60 seconds and try again." exit(false) @@ -43,19 +43,20 @@ # Create a message with three custom attributes: Title, Author, and WeeksOn. send_message_result = sqs.send_message({ queue_url: queue_url, - message_body: "Information about current NY Times fiction bestseller for week of 2016-12-11.", + message_body: 'Information about current NY Times fiction bestseller for week of 2016-12-11.', + message_attributes: { - "Title" => { - string_value: "The Whistler", - data_type: "String" + 'Title' => { + string_value: 'The Whistler', + data_type: 'String' }, - "Author" => { - string_value: "John Grisham", - data_type: "String" + 'Author' => { + string_value: 'John Grisham', + data_type: 'String' }, - "WeeksOn" => { - string_value: "6", - data_type: "Number" + 'WeeksOn' => { + string_value: '6', + data_type: 'Number' } } }) @@ -68,7 +69,7 @@ # Receive the message in the queue. receive_message_result = sqs.receive_message({ queue_url: queue_url, - message_attribute_names: ["All"], # Receive all custom attributes. + message_attribute_names: ['All'], # Receive all custom attributes. max_number_of_messages: 1, # Receive at most one message. wait_time_seconds: 0 # Do not wait to check for the message. }) @@ -77,9 +78,9 @@ # Display the message's body and each custom attribute value. receive_message_result.messages.each do |message| puts message.body - puts "Title: #{message.message_attributes["Title"]["string_value"]}" - puts "Author: #{message.message_attributes["Author"]["string_value"]}" - puts "WeeksOn: #{message.message_attributes["WeeksOn"]["string_value"]}" + puts "Title: #{message.message_attributes['Title']['string_value']}" + puts "Author: #{message.message_attributes['Author']['string_value']}" + puts "WeeksOn: #{message.message_attributes['WeeksOn']['string_value']}" # Delete the message from the queue. sqs.delete_message({ diff --git a/ruby/example_code/sqs/scenario_polling.rb b/ruby/example_code/sqs/scenario_polling.rb index 4eb56107c40..29c0989838b 100644 --- a/ruby/example_code/sqs/scenario_polling.rb +++ b/ruby/example_code/sqs/scenario_polling.rb @@ -9,34 +9,34 @@ # snippet-start:[ruby.example_code.sqs.ScenarioPolling] -require "aws-sdk-sqs" # v2: require 'aws-sdk' +require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. -sqs = Aws::SQS::Client.new(region: "us-west-2") +sqs = Aws::SQS::Client.new(region: 'us-west-2') # Create a queue and set it for long polling. -new_queue_name = "new-queue" +new_queue_name = 'new-queue' create_queue_result = sqs.create_queue({ - queue_name: new_queue_name, - attributes: { - "ReceiveMessageWaitTimeSeconds" => "20" # Wait 20 seconds to receive messages. - }, -}) + queue_name: new_queue_name, + attributes: { + 'ReceiveMessageWaitTimeSeconds' => '20' # Wait 20 seconds to receive messages. + } + }) puts create_queue_result.queue_url # Set long polling for an existing queue. begin - existing_queue_name = "existing-queue" + existing_queue_name = 'existing-queue' existing_queue_url = sqs.get_queue_url(queue_name: existing_queue_name).queue_url sqs.set_queue_attributes({ - queue_url: existing_queue_url, - attributes: { - "ReceiveMessageWaitTimeSeconds" => "20" # Wait 20 seconds to receive messages. - }, - }) + queue_url: existing_queue_url, + attributes: { + 'ReceiveMessageWaitTimeSeconds' => '20' # Wait 20 seconds to receive messages. + } + }) rescue Aws::SQS::Errors::NonExistentQueue puts "Cannot set long polling for a queue named '#{existing_queue_name}', as it does not exist." end @@ -45,15 +45,16 @@ # 1. Using receive_message. begin - receive_queue_name = "receive-queue" + receive_queue_name = 'receive-queue' receive_queue_url = sqs.get_queue_url(queue_name: receive_queue_name).queue_url - puts "Begin receipt of any messages using receive_message..." + puts 'Begin receipt of any messages using receive_message...' receive_message_result = sqs.receive_message({ - queue_url: receive_queue_url, - wait_time_seconds: 10, # Poll messages for 10 seconds at a time. Default: 0. - max_number_of_messages: 10 # Receive up to 10 messages, if there are that many. - }) + queue_url: receive_queue_url, + wait_time_seconds: 10, + # Poll messages for 10 seconds at a time. Default: 0. + max_number_of_messages: 10 # Receive up to 10 messages, if there are that many. + }) puts "Received #{receive_message_result.messages.count} message(s)." rescue Aws::SQS::Errors::NonExistentQueue @@ -64,22 +65,22 @@ # NOTE: Using this class, messages are received using a "long poll" of 20 seconds. # If you prefer to use settings configured in the queue, then pass a nil value for :wait_time_seconds. begin - puts "Begin receipt of any messages using Aws::SQS::QueuePoller..." - puts "(Will keep polling until no more messages available for at least 60 seconds.)" + puts 'Begin receipt of any messages using Aws::SQS::QueuePoller...' + puts '(Will keep polling until no more messages available for at least 60 seconds.)' poller = Aws::SQS::QueuePoller.new(receive_queue_url) poller_stats = poller.poll({ - wait_time_seconds: 30, # Poll messages for 30 seconds at a time. Default: 20. - max_number_of_messages: 10, # Return up to 10 messages at a time. - idle_timeout: 60 # Terminate polling loop after 60 seconds. - }) do |messages| + wait_time_seconds: 30, # Poll messages for 30 seconds at a time. Default: 20. + max_number_of_messages: 10, # Return up to 10 messages at a time. + idle_timeout: 60 # Terminate polling loop after 60 seconds. + }) do |messages| messages.each do |message| puts "Message body: #{message.body}" end end - # Note: If poller.poll is successful, all received messages are automatically deleted from the queue. + # NOTE: If poller.poll is successful, all received messages are automatically deleted from the queue. - puts "Poller stats:" + puts 'Poller stats:' puts " Polling started at: #{poller_stats.polling_started_at}" puts " Polling stopped at: #{poller_stats.polling_stopped_at}" puts " Last message received at: #{poller_stats.last_message_received_at}" diff --git a/ruby/example_code/sqs/send_message.rb b/ruby/example_code/sqs/send_message.rb index 174d69f3583..e406f17eb7c 100644 --- a/ruby/example_code/sqs/send_message.rb +++ b/ruby/example_code/sqs/send_message.rb @@ -6,8 +6,8 @@ # snippet-start:[ruby.example_code.sqs.SendMessage] -require "aws-sdk-sqs" -require "aws-sdk-sts" +require 'aws-sdk-sqs' +require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. @@ -33,25 +33,24 @@ def message_sent?(sqs_client, queue_url, message_body) # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me - region = "us-west-2" - queue_name = "my-queue" - message_body = "This is my message." + region = 'us-west-2' + queue_name = 'my-queue' + message_body = 'This is my message.' sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' - queue_url = "https://sqs." + region + ".amazonaws.com/" + - sts_client.get_caller_identity.account + "/" + queue_name + queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) puts "Sending a message to the queue named '#{queue_name}'..." if message_sent?(sqs_client, queue_url, message_body) - puts "Message sent." + puts 'Message sent.' else - puts "Message not sent." + puts 'Message not sent.' end end diff --git a/ruby/example_code/sqs/send_message_batch.rb b/ruby/example_code/sqs/send_message_batch.rb index 4b88fb55ddf..1876f6ef0b0 100644 --- a/ruby/example_code/sqs/send_message_batch.rb +++ b/ruby/example_code/sqs/send_message_batch.rb @@ -6,8 +6,8 @@ # snippet-start:[ruby.example_code.sqs.SendMessageBatch] -require "aws-sdk-sqs" -require "aws-sdk-sts" +require 'aws-sdk-sqs' +require 'aws-sdk-sts' # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. @@ -44,16 +44,16 @@ def messages_sent?(sqs_client, queue_url, entries) # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me - region = "us-west-2" - queue_name = "my-queue" + region = 'us-west-2' + queue_name = 'my-queue' entries = [ { - id: "Message1", - message_body: "This is the first message." + id: 'Message1', + message_body: 'This is the first message.' }, { - id: "Message2", - message_body: "This is the second message." + id: 'Message2', + message_body: 'This is the second message.' } ] @@ -61,17 +61,16 @@ def run_me # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' - queue_url = "https://sqs." + region + ".amazonaws.com/" + - sts_client.get_caller_identity.account + "/" + queue_name + queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) puts "Sending messages to the queue named '#{queue_name}'..." if messages_sent?(sqs_client, queue_url, entries) - puts "Messages sent." + puts 'Messages sent.' else - puts "Messages not sent." + puts 'Messages not sent.' end end diff --git a/ruby/example_code/sqs/show_queues.rb b/ruby/example_code/sqs/show_queues.rb index 1c4a6d1cdad..dcd9ed1ae40 100644 --- a/ruby/example_code/sqs/show_queues.rb +++ b/ruby/example_code/sqs/show_queues.rb @@ -6,8 +6,8 @@ # snippet-start:[ruby.example_code.sqs.ShowQueues] -require "aws-sdk-sqs" -require "aws-sdk-sts" +require 'aws-sdk-sqs' +require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @example @@ -34,13 +34,12 @@ def list_queue_urls(sqs_client) def list_queue_attributes(sqs_client, queue_url) attributes = sqs_client.get_queue_attributes( queue_url: queue_url, - attribute_names: ["All"] + attribute_names: ['All'] ) attributes.attributes.each do |key, value| puts "#{key}: #{value}" end - rescue StandardError => e puts "Error getting queue attributes: #{e.message}" end @@ -48,20 +47,19 @@ def list_queue_attributes(sqs_client, queue_url) # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me - region = "us-west-2" - queue_name = "my-queue" + region = 'us-west-2' + queue_name = 'my-queue' sqs_client = Aws::SQS::Client.new(region: region) - puts "Listing available queue URLs..." + puts 'Listing available queue URLs...' list_queue_urls(sqs_client) sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' - queue_url = "https://sqs." + region + ".amazonaws.com/" + - sts_client.get_caller_identity.account + "/" + queue_name + queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}" puts "\nGetting information about queue '#{queue_name}'..." list_queue_attributes(sqs_client, queue_url) diff --git a/ruby/example_code/sqs/tests/test_create_queue.rb b/ruby/example_code/sqs/tests/test_create_queue.rb index 3f92f0f3d8e..28d95d65379 100644 --- a/ruby/example_code/sqs/tests/test_create_queue.rb +++ b/ruby/example_code/sqs/tests/test_create_queue.rb @@ -1,11 +1,11 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../create_queue" +require_relative '../create_queue' -describe "#queue_created?" do - let(:queue_name) { "my-queue" } - let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/" + queue_name } +describe '#queue_created?' do + let(:queue_name) { 'my-queue' } + let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/#{queue_name}" } let(:sqs_client) do Aws::SQS::Client.new( stub_responses: { @@ -16,7 +16,7 @@ ) end - it "creates a queue" do + it 'creates a queue' do expect(queue_created?(sqs_client, queue_name)).to be(true) end end diff --git a/ruby/example_code/sqs/tests/test_receive_messages.rb b/ruby/example_code/sqs/tests/test_receive_messages.rb index 227b7bf50f5..d57d61d2e47 100644 --- a/ruby/example_code/sqs/tests/test_receive_messages.rb +++ b/ruby/example_code/sqs/tests/test_receive_messages.rb @@ -1,11 +1,11 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../receive_messages" +require_relative '../receive_messages' -describe "#receive_messages" do - let(:queue_name) { "my-queue" } - let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/" + queue_name } +describe '#receive_messages' do + let(:queue_name) { 'my-queue' } + let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/#{queue_name}" } let(:max_number_of_messages) { 10 } let(:sqs_client) do Aws::SQS::Client.new( @@ -13,10 +13,10 @@ receive_message: { messages: [ { - body: "This is my first message." + body: 'This is my first message.' }, { - body: "This is my second message." + body: 'This is my second message.' } ] } @@ -24,7 +24,7 @@ ) end - it "receives messages" do + it 'receives messages' do expect { receive_messages(sqs_client, queue_url, max_number_of_messages) }.to_not raise_error end end diff --git a/ruby/example_code/sqs/tests/test_send_message.rb b/ruby/example_code/sqs/tests/test_send_message.rb index 81622e4bbe2..78cebfee18d 100644 --- a/ruby/example_code/sqs/tests/test_send_message.rb +++ b/ruby/example_code/sqs/tests/test_send_message.rb @@ -1,23 +1,23 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../send_message" +require_relative '../send_message' -describe "#message_sent?" do - let(:queue_name) { "my-queue" } - let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/" + queue_name } - let(:message_body) { "This is my message." } +describe '#message_sent?' do + let(:queue_name) { 'my-queue' } + let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/#{queue_name}" } + let(:message_body) { 'This is my message.' } let(:sqs_client) do Aws::SQS::Client.new( stub_responses: { send_message: { - message_id: "3fd53020-3da2-4a7e-afef-d36dfEXAMPLE" + message_id: '3fd53020-3da2-4a7e-afef-d36dfEXAMPLE' } } ) end - it "sends a message" do + it 'sends a message' do expect(message_sent?(sqs_client, queue_url, message_body)).to be(true) end end diff --git a/ruby/example_code/sqs/tests/test_send_message_batch.rb b/ruby/example_code/sqs/tests/test_send_message_batch.rb index 56d99086af3..eb169178d70 100644 --- a/ruby/example_code/sqs/tests/test_send_message_batch.rb +++ b/ruby/example_code/sqs/tests/test_send_message_batch.rb @@ -1,20 +1,20 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../send_message_batch" +require_relative '../send_message_batch' -describe "#messages_sent?" do - let(:queue_name) { "my-queue" } - let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/" + queue_name } +describe '#messages_sent?' do + let(:queue_name) { 'my-queue' } + let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/#{queue_name}" } let(:entries) do [ { - id: "Message1", - message_body: "This is the first message." + id: 'Message1', + message_body: 'This is the first message.' }, { - id: "Message2", - message_body: "This is the second message." + id: 'Message2', + message_body: 'This is the second message.' } ] end @@ -24,14 +24,14 @@ send_message_batch: { successful: [ { - id: "Message1", - md5_of_message_body: "c49f3d613918add9690e54615EXAMPLE", - message_id: "3fd53020-3da2-4a7e-afef-d36dfEXAMPLE" + id: 'Message1', + md5_of_message_body: 'c49f3d613918add9690e54615EXAMPLE', + message_id: '3fd53020-3da2-4a7e-afef-d36dfEXAMPLE' }, { - id: "Message2", - md5_of_message_body: "8fa387fa05fc48179f1f052cbEXAMPLE", - message_id: "7365097c-b104-4f41-b7b7-fa31eEXAMPLE" + id: 'Message2', + md5_of_message_body: '8fa387fa05fc48179f1f052cbEXAMPLE', + message_id: '7365097c-b104-4f41-b7b7-fa31eEXAMPLE' } ], failed: [] @@ -40,7 +40,7 @@ ) end - it "sends messages in a batch" do + it 'sends messages in a batch' do expect(messages_sent?(sqs_client, queue_url, entries)).to be(true) end end diff --git a/ruby/example_code/sqs/tests/test_show_queues.rb b/ruby/example_code/sqs/tests/test_show_queues.rb index 1b496c172b8..44d218e7264 100644 --- a/ruby/example_code/sqs/tests/test_show_queues.rb +++ b/ruby/example_code/sqs/tests/test_show_queues.rb @@ -1,46 +1,46 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require_relative "../show_queues" +require_relative '../show_queues' -describe "#list_queue_urls" do +describe '#list_queue_urls' do let(:sqs_client) do Aws::SQS::Client.new( stub_responses: { list_queues: { queue_urls: [ - "https://sqs.us-west-2.amazonaws.com/111111111111/my-queue", - "https://sqs.us-west-2.amazonaws.com/111111111111/my-queue-2" + 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', + 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue-2' ] } } ) end - it "lists available queue URLs" do + it 'lists available queue URLs' do expect { list_queue_urls(sqs_client) }.to_not raise_error end end -describe "#list_queue_attributes" do - let(:queue_name) { "my-queue" } - let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/" + queue_name } +describe '#list_queue_attributes' do + let(:queue_name) { 'my-queue' } + let(:queue_url) { "https://sqs.us-west-2.amazonaws.com/111111111111/#{queue_name}" } let(:sqs_client) do Aws::SQS::Client.new( stub_responses: { get_queue_attributes: { attributes: { - "QueueArn" => "arn:aws:sqs:us-west-2:992648334831:my-queue", - "ApproximateNumberOfMessages" => "2", - "ApproximateNumberOfMessagesNotVisible" => "0", - "ApproximateNumberOfMessagesDelayed" => "0", - "CreatedTimestamp" => "1612302412", - "LastModifiedTimestamp" => "1612302412", - "VisibilityTimeout" => "30", - "MaximumMessageSize" => "262144", - "MessageRetentionPeriod" => "345600", - "DelaySeconds" => "0", - "ReceiveMessageWaitTimeSeconds" => "0" + 'QueueArn' => 'arn:aws:sqs:us-west-2:992648334831:my-queue', + 'ApproximateNumberOfMessages' => '2', + 'ApproximateNumberOfMessagesNotVisible' => '0', + 'ApproximateNumberOfMessagesDelayed' => '0', + 'CreatedTimestamp' => '1612302412', + 'LastModifiedTimestamp' => '1612302412', + 'VisibilityTimeout' => '30', + 'MaximumMessageSize' => '262144', + 'MessageRetentionPeriod' => '345600', + 'DelaySeconds' => '0', + 'ReceiveMessageWaitTimeSeconds' => '0' } } } diff --git a/ruby/example_code/workdocs/README.md b/ruby/example_code/workdocs/README.md index d68a1e5b5b3..ac219c552a8 100644 --- a/ruby/example_code/workdocs/README.md +++ b/ruby/example_code/workdocs/README.md @@ -33,7 +33,7 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `ruby` Code excerpts that show you how to call individual service functions. -- [DescribeRootFolders](workdocs_basics.rb#L36) +- [DescribeRootFolders](workdocs_basics.rb#L37) - [DescribeUsers](workdocs_basics.rb#L12) diff --git a/ruby/example_code/workdocs/spec/workdocs_basics_spec.rb b/ruby/example_code/workdocs/spec/workdocs_basics_spec.rb index f5cacdf16d4..592adbca235 100644 --- a/ruby/example_code/workdocs/spec/workdocs_basics_spec.rb +++ b/ruby/example_code/workdocs/spec/workdocs_basics_spec.rb @@ -1,31 +1,31 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "rspec" -require_relative "../workdocs_basics" +require 'rspec' +require_relative '../workdocs_basics' describe WorkDocsManager do let(:client) { Aws::WorkDocs::Client.new(stub_responses: true) } let(:manager) { WorkDocsManager.new(client) } - let(:org_id) { "d-123456789c" } - let(:user_email) { "someone@somewhere" } + let(:org_id) { 'd-123456789c' } + let(:user_email) { 'someone@somewhere' } - describe "#describe_users" do - it "calls describe_users on the WorkDocs client" do + describe '#describe_users' do + it 'calls describe_users on the WorkDocs client' do client.stub_responses(:describe_users, users: []) expect { manager.describe_users(org_id) }.not_to raise_error end end - describe "#get_user_folder" do - it "returns the root folder id for a given user email" do - users = [{email_address: user_email, root_folder_id: "root-folder-id"}] - expect(manager.get_user_folder(users, user_email)).to eq("root-folder-id") + describe '#get_user_folder' do + it 'returns the root folder id for a given user email' do + users = [{ email_address: user_email, root_folder_id: 'root-folder-id' }] + expect(manager.get_user_folder(users, user_email)).to eq('root-folder-id') end end - describe "#describe_folder_contents" do - it "calls describe_folder_contents on the WorkDocs client" do - folder_id = "root-folder-id" + describe '#describe_folder_contents' do + it 'calls describe_folder_contents on the WorkDocs client' do + folder_id = 'root-folder-id' client.stub_responses(:describe_folder_contents, documents: []) expect { manager.describe_folder_contents(folder_id) }.not_to raise_error end diff --git a/ruby/example_code/workdocs/workdocs_basics.rb b/ruby/example_code/workdocs/workdocs_basics.rb index ecdebbec8c1..dcc7ad8f672 100644 --- a/ruby/example_code/workdocs/workdocs_basics.rb +++ b/ruby/example_code/workdocs/workdocs_basics.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "aws-sdk-workdocs" -require "logger" +require 'aws-sdk-workdocs' +require 'logger' class WorkDocsManager def initialize(client, logger: Logger.new($stdout)) @@ -15,16 +15,17 @@ def initialize(client, logger: Logger.new($stdout)) def describe_users(org_id) resp = @client.describe_users({ organization_id: org_id, - include: "ALL", # accepts ALL, ACTIVE_PENDING - order: "ASCENDING", # accepts ASCENDING, DESCENDING - sort: "USER_NAME", # accepts USER_NAME, FULL_NAME, STORAGE_LIMIT, USER_STATUS, STORAGE_USED + include: 'ALL', # accepts ALL, ACTIVE_PENDING + order: 'ASCENDING', # accepts ASCENDING, DESCENDING + sort: 'USER_NAME', # accepts USER_NAME + fields: %w[FULL_NAME STORAGE_LIMIT USER_STATUS STORAGE_USED] # Corrected field names }) resp.users.each do |user| @logger.info "First name: #{user.given_name}" @logger.info "Last name: #{user.surname}" @logger.info "Email: #{user.email_address}" @logger.info "Root folder: #{user.root_folder_id}" - @logger.info "" + @logger.info '' end resp.users rescue Aws::WorkDocs::Errors::ServiceError => e @@ -52,8 +53,8 @@ def get_user_folder(users, user_email) def describe_folder_contents(folder_id) resp = @client.describe_folder_contents({ folder_id: folder_id, # required - sort: "NAME", # accepts DATE, NAME - order: "ASCENDING", # accepts ASCENDING, DESCENDING + sort: 'NAME', # accepts DATE, NAME + order: 'ASCENDING' # accepts ASCENDING, DESCENDING }) resp.documents.each do |doc| md = doc.latest_version_metadata @@ -62,20 +63,19 @@ def describe_folder_contents(folder_id) @logger.info "Last modified: #{doc.modified_timestamp}" @logger.info "Doc ID: #{doc.id}" @logger.info "Version ID: #{md.id}" - @logger.info "" + @logger.info '' end rescue Aws::WorkDocs::Errors::ServiceError => e @logger.error "Error listing folder contents: #{e.message}" exit(1) end # snippet-end:[workdocs.Ruby.DescribeRootFolders] - end # Example usage: if $PROGRAM_NAME == __FILE__ - user_email = "someone@somewhere" - org_id = "d-123456789c" + user_email = 'someone@somewhere' + org_id = 'd-123456789c' client = Aws::WorkDocs::Client.new manager = WorkDocsManager.new(client) users = manager.describe_users(org_id) diff --git a/ruby/helpers/decorators.rb b/ruby/helpers/decorators.rb index 05454088806..7dced79b520 100644 --- a/ruby/helpers/decorators.rb +++ b/ruby/helpers/decorators.rb @@ -2,7 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 # frozen_string_literal: true -require_relative "colorizer" + +require_relative 'colorizer' def banner(filepath) text = File.read(filepath) @@ -11,7 +12,7 @@ def banner(filepath) def confirm_begin # not actually a password - reply = CLI::UI::Prompt.ask_password("Press any key to continue.") + reply = CLI::UI::Prompt.ask_password('Press any key to continue.') exit unless reply end diff --git a/ruby/helpers/disclaimers.rb b/ruby/helpers/disclaimers.rb index 7702847c12b..fd656fa15a0 100644 --- a/ruby/helpers/disclaimers.rb +++ b/ruby/helpers/disclaimers.rb @@ -1,36 +1,36 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -require "cli/ui" -require_relative("colorizer") +require 'cli/ui' +require_relative('colorizer') def billing puts "\e[H\e[2J" - puts "========================== BILLING DISCLAIMER =============================".yellow - puts "Running this code will create actual resources that may incur charges." - puts "While the code attempts to destroy all resources it creates, unexpected " - puts "errors may leave orphaned resources that must be manually deleted." - puts "" - puts "For more information on how AWS pricing works, see:" - puts " https://aws.amazon.com/pricing/?aws-products-pricing" - puts "" - puts "==========================================================================".yellow - reply = CLI::UI::Prompt.confirm("Do you understand the above BILLING DISCLAIMER and wish to continue?") + puts '========================== BILLING DISCLAIMER ============================='.yellow + puts 'Running this code will create actual resources that may incur charges.' + puts 'While the code attempts to destroy all resources it creates, unexpected ' + puts 'errors may leave orphaned resources that must be manually deleted.' + puts '' + puts 'For more information on how AWS pricing works, see:' + puts ' https://aws.amazon.com/pricing/?aws-products-pricing' + puts '' + puts '=========================================================================='.yellow + reply = CLI::UI::Prompt.confirm('Do you understand the above BILLING DISCLAIMER and wish to continue?') exit unless reply end def security puts "\e[H\e[2J" - puts "========================== SECURITY DISCLAIMER =============================".yellow + puts '========================== SECURITY DISCLAIMER ============================='.yellow puts "Per Amazon Web Service's Shared Responsibility Model, you, the customer," - puts "assume a certain level of responsibility and should carefully consider" - puts "the security impact of the services used in this demo, the integration" - puts "of these services into your IT environment, and applicable laws and regulations." - puts "" - puts "For more information on the Shared Repsonsibility Model, please see: " - puts " https://aws.amazon.com/compliance/shared-responsibility-model/" - puts "" - puts "==========================================================================".yellow - reply = CLI::UI::Prompt.confirm("Do you understand the above SECURITY DISCLAIMER and wish to continue?") + puts 'assume a certain level of responsibility and should carefully consider' + puts 'the security impact of the services used in this demo, the integration' + puts 'of these services into your IT environment, and applicable laws and regulations.' + puts '' + puts 'For more information on the Shared Repsonsibility Model, please see: ' + puts ' https://aws.amazon.com/compliance/shared-responsibility-model/' + puts '' + puts '=========================================================================='.yellow + reply = CLI::UI::Prompt.confirm('Do you understand the above SECURITY DISCLAIMER and wish to continue?') exit unless reply end diff --git a/ruby/helpers/question.rb b/ruby/helpers/question.rb index a95c31640b1..5dc7a3bd0ec 100644 --- a/ruby/helpers/question.rb +++ b/ruby/helpers/question.rb @@ -6,7 +6,6 @@ # Helper class for running scenarios at a command prompt. Asks questions, validates # and converts input, and returns answers. - # snippet-start:[ruby.example_code.dynamodb.helper.Question] # Asks a single question and validates it against a list of validators. # When an answer fails validation, the complaint is printed and the question @@ -37,23 +36,21 @@ def self.ask(question, *validators) # Validates that the answer is not empty. # @return [Array] The non-empty answer, or nil. def non_empty(answer) - answer = nil unless answer != "" - [answer, "I need an answer. Please?"] + answer = nil unless answer != '' + [answer, 'I need an answer. Please?'] end # Validates a yes/no answer. # @return [Array] True when the answer is 'y'; otherwise, False. def is_yesno(answer) - [answer.downcase == "y", ""] + [answer.downcase == 'y', ''] end # Validates that the answer can be converted to an int. # @return [Array] The int answer; otherwise, nil. def is_int(answer) int_answer = answer.to_i - if int_answer == 0 - int_answer = nil - end + int_answer = nil if int_answer.zero? [int_answer, "#{answer} must be a valid integer."] end @@ -61,9 +58,7 @@ def is_int(answer) # :return [Array] The float answer; otherwise, None. def is_float(answer) float_answer = answer.to_f - if float_answer == 0.0 - float_answer = nil - end + float_answer = nil if float_answer == 0.0 [float_answer, "#{answer} must be a valid float."] end @@ -72,9 +67,9 @@ def is_float(answer) # @return [Proc] A Proc that can be called to determine whether the answer is within # the expected range. def in_range(lower, upper) - Proc.new { |answer| - answer.between?(lower, upper) ? range_answer = answer : range_answer = nil + proc do |answer| + range_answer = answer.between?(lower, upper) ? answer : nil [range_answer, "#{answer} must be between #{lower} and #{upper}."] - } + end end # snippet-end:[ruby.example_code.dynamodb.helper.Question] diff --git a/ruby/helpers/waiters.rb b/ruby/helpers/waiters.rb index cc5a7fe2764..f55dc6b17a2 100644 --- a/ruby/helpers/waiters.rb +++ b/ruby/helpers/waiters.rb @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def custom_wait(seconds, tick = 12) - progress = "|/-\\" + progress = '|/-\\' waited = 0 while waited < seconds tick.times do |frame|