SDK for Ruby を使用した Amazon S3 の例 - AWS SDK コードの例

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

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

SDK for Ruby を使用した Amazon S3 の例

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

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。ここでは GitHub、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

アクション

次の例は、CopyObject を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

オブジェクトをコピーします。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectCopyWrapper attr_reader :source_object # @param source_object [Aws::S3::Object] An existing Amazon S3 object. This is used as the source object for # copy actions. def initialize(source_object) @source_object = source_object end # Copy the source object to the specified target bucket and rename it with the target key. # # @param target_bucket [Aws::S3::Bucket] An existing Amazon S3 bucket where the object is copied. # @param target_object_key [String] The key to give the copy of the object. # @return [Aws::S3::Object, nil] The copied object when successful; otherwise, nil. def copy_object(target_bucket, target_object_key) @source_object.copy_to(bucket: target_bucket.name, key: target_object_key) target_bucket.object(target_object_key) rescue Aws::Errors::ServiceError => e puts "Couldn't copy #{@source_object.key} to #{target_object_key}. Here's why: #{e.message}" end end # Example usage: def run_demo source_bucket_name = "doc-example-bucket1" source_key = "my-source-file.txt" target_bucket_name = "doc-example-bucket2" target_key = "my-target-file.txt" source_bucket = Aws::S3::Bucket.new(source_bucket_name) wrapper = ObjectCopyWrapper.new(source_bucket.object(source_key)) target_bucket = Aws::S3::Bucket.new(target_bucket_name) target_object = wrapper.copy_object(target_bucket, target_key) return unless target_object puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key}." end run_demo if $PROGRAM_NAME == __FILE__

オブジェクトをコピーし、宛先オブジェクトにサーバー側の暗号化を追加します。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectCopyEncryptWrapper attr_reader :source_object # @param source_object [Aws::S3::Object] An existing Amazon S3 object. This is used as the source object for # copy actions. def initialize(source_object) @source_object = source_object end # Copy the source object to the specified target bucket, rename it with the target key, and encrypt it. # # @param target_bucket [Aws::S3::Bucket] An existing Amazon S3 bucket where the object is copied. # @param target_object_key [String] The key to give the copy of the object. # @return [Aws::S3::Object, nil] The copied object when successful; otherwise, nil. def copy_object(target_bucket, target_object_key, encryption) @source_object.copy_to(bucket: target_bucket.name, key: target_object_key, server_side_encryption: encryption) target_bucket.object(target_object_key) rescue Aws::Errors::ServiceError => e puts "Couldn't copy #{@source_object.key} to #{target_object_key}. Here's why: #{e.message}" end end # Example usage: def run_demo 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" source_bucket = Aws::S3::Bucket.new(source_bucket_name) wrapper = ObjectCopyEncryptWrapper.new(source_bucket.object(source_key)) target_bucket = Aws::S3::Bucket.new(target_bucket_name) target_object = wrapper.copy_object(target_bucket, target_key, target_encryption) return unless target_object puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key} and "\ "encrypted the target with #{target_object.server_side_encryption} encryption." end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスCopyObject」の「」を参照してください。 AWS SDK for Ruby

次の例は、CreateBucket を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 bucket actions. class BucketCreateWrapper attr_reader :bucket # @param bucket [Aws::S3::Bucket] An Amazon S3 bucket initialized with a name. This is a client-side object until # create is called. def initialize(bucket) @bucket = bucket end # Creates an Amazon S3 bucket in the specified AWS Region. # # @param region [String] The Region where the bucket is created. # @return [Boolean] True when the bucket is created; otherwise, false. def create?(region) @bucket.create(create_bucket_configuration: { location_constraint: region }) true rescue Aws::Errors::ServiceError => e puts "Couldn't create bucket. Here's why: #{e.message}" false end # Gets the Region where the bucket is located. # # @return [String] The location of the bucket. def location if @bucket.nil? "None. You must create a bucket before you can get its location!" else @bucket.client.get_bucket_location(bucket: @bucket.name).location_constraint end rescue Aws::Errors::ServiceError => e "Couldn't get the location of #{@bucket.name}. Here's why: #{e.message}" end end # Example usage: def run_demo region = "us-west-2" wrapper = BucketCreateWrapper.new(Aws::S3::Bucket.new("doc-example-bucket-#{Random.uuid}")) return unless wrapper.create?(region) puts "Created bucket #{wrapper.bucket.name}." puts "Your bucket's region is: #{wrapper.location}" end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスCreateBucket」の「」を参照してください。 AWS SDK for Ruby

次の例は、DeleteBucket を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. 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" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • API の詳細については、「 API リファレンスDeleteBucket」の「」を参照してください。 AWS SDK for Ruby

次の例は、DeleteBucketCors を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # Deletes the CORS configuration of a bucket. # # @return [Boolean] True if the CORS rules were deleted; otherwise, false. def delete_cors @bucket_cors.delete true rescue Aws::Errors::ServiceError => e puts "Couldn't delete CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" false end end
  • API の詳細については、「 API リファレンスDeleteBucketCors」の「」を参照してください。 AWS SDK for Ruby

次の例は、DeleteBucketPolicy を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

# Wraps an Amazon S3 bucket policy. class BucketPolicyWrapper attr_reader :bucket_policy # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket. def initialize(bucket_policy) @bucket_policy = bucket_policy end def delete_policy @bucket_policy.delete true rescue Aws::Errors::ServiceError => e puts "Couldn't delete the policy from #{@bucket_policy.bucket.name}. Here's why: #{e.message}" false end end
  • API の詳細については、「 API リファレンスDeleteBucketPolicy」の「」を参照してください。 AWS SDK for Ruby

次の例は、DeleteObjects を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. 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" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • API の詳細については、「 API リファレンスDeleteObjects」の「」を参照してください。 AWS SDK for Ruby

次の例は、GetBucketCors を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # Gets the CORS configuration of a bucket. # # @return [Aws::S3::Type::GetBucketCorsOutput, nil] The current CORS configuration for the bucket. def get_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}" nil end end
  • API の詳細については、「 API リファレンスGetBucketCors」の「」を参照してください。 AWS SDK for Ruby

次の例は、GetBucketPolicy を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

# Wraps an Amazon S3 bucket policy. class BucketPolicyWrapper attr_reader :bucket_policy # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket. def initialize(bucket_policy) @bucket_policy = bucket_policy end # Gets the policy of a bucket. # # @return [Aws::S3::GetBucketPolicyOutput, nil] The current bucket policy. def get_policy policy = @bucket_policy.data.policy policy.respond_to?(:read) ? policy.read : policy rescue Aws::Errors::ServiceError => e puts "Couldn't get the policy for #{@bucket_policy.bucket.name}. Here's why: #{e.message}" nil end end
  • API の詳細については、「 API リファレンスGetBucketPolicy」の「」を参照してください。 AWS SDK for Ruby

次の例は、GetObject を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

オブジェクトを取得します。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectGetWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end # Gets the object directly to a file. # # @param target_path [String] The path to the file where the object is downloaded. # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil. def get_object(target_path) @object.get(response_target: target_path) rescue Aws::Errors::ServiceError => e puts "Couldn't get object #{@object.key}. Here's why: #{e.message}" end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-object.txt" target_path = "my-object-as-file.txt" wrapper = ObjectGetWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) obj_data = wrapper.get_object(target_path) return unless obj_data puts "Object #{object_key} (#{obj_data.content_length} bytes} downloaded to #{target_path}." end run_demo if $PROGRAM_NAME == __FILE__

オブジェクトを取得し、サーバー側の暗号化状態をレポートします。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectGetEncryptionWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end # Gets the object into memory. # # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil. def get_object @object.get rescue Aws::Errors::ServiceError => e puts "Couldn't get object #{@object.key}. Here's why: #{e.message}" end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-object.txt" 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 puts "Object #{object_key} uses #{encryption} encryption." end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスGetObject」の「」を参照してください。 AWS SDK for Ruby

次の例は、HeadObject を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectExistsWrapper attr_reader :object # @param object [Aws::S3::Object] An Amazon S3 object. def initialize(object) @object = object end # Checks whether the object exists. # # @return [Boolean] True if the object exists; otherwise false. def exists? @object.exists? rescue Aws::Errors::ServiceError => e puts "Couldn't check existence of object #{@object.bucket.name}:#{@object.key}. Here's why: #{e.message}" false end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-object.txt" wrapper = ObjectExistsWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) exists = wrapper.exists? puts "Object #{object_key} #{exists ? 'does' : 'does not'} exist." end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスHeadObject」の「」を参照してください。 AWS SDK for Ruby

次の例は、ListBuckets を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 resource actions. class BucketListWrapper attr_reader :s3_resource # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def initialize(s3_resource) @s3_resource = s3_resource end # Lists buckets for the current account. # # @param count [Integer] The maximum number of buckets to list. def list_buckets(count) puts "Found these buckets:" @s3_resource.buckets.each do |bucket| puts "\t#{bucket.name}" count -= 1 break if count.zero? end true rescue Aws::Errors::ServiceError => e puts "Couldn't list buckets. Here's why: #{e.message}" false end end # Example usage: def run_demo wrapper = BucketListWrapper.new(Aws::S3::Resource.new) wrapper.list_buckets(25) end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスListBuckets」の「」を参照してください。 AWS SDK for Ruby

次の例は、ListObjectsV2 を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 bucket actions. class BucketListObjectsWrapper attr_reader :bucket # @param bucket [Aws::S3::Bucket] An existing Amazon S3 bucket. def initialize(bucket) @bucket = bucket end # Lists object in a bucket. # # @param max_objects [Integer] The maximum number of objects to list. # @return [Integer] The number of objects listed. def list_objects(max_objects) count = 0 puts "The objects in #{@bucket.name} are:" @bucket.objects.each do |obj| puts "\t#{obj.key}" count += 1 break if count == max_objects end count rescue Aws::Errors::ServiceError => e puts "Couldn't list objects in bucket #{bucket.name}. Here's why: #{e.message}" 0 end end # Example usage: def run_demo bucket_name = "doc-example-bucket" wrapper = BucketListObjectsWrapper.new(Aws::S3::Bucket.new(bucket_name)) count = wrapper.list_objects(25) puts "Listed #{count} objects." end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンス」のListObjectsV2」を参照してください。 AWS SDK for Ruby

次の例は、PutBucketCors を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # Sets CORS rules on a bucket. # # @param allowed_methods [Array<String>] The types of HTTP requests to allow. # @param allowed_origins [Array<String>] The origins to allow. # @returns [Boolean] True if the CORS rules were set; otherwise, false. def set_cors(allowed_methods, allowed_origins) @bucket_cors.put( cors_configuration: { cors_rules: [ { allowed_methods: allowed_methods, allowed_origins: allowed_origins, allowed_headers: %w[*], max_age_seconds: 3600 } ] } ) true rescue Aws::Errors::ServiceError => e puts "Couldn't set CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" false end end
  • API の詳細については、「 API リファレンスPutBucketCors」の「」を参照してください。 AWS SDK for Ruby

次の例は、PutBucketPolicy を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

# Wraps an Amazon S3 bucket policy. class BucketPolicyWrapper attr_reader :bucket_policy # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket. def initialize(bucket_policy) @bucket_policy = bucket_policy end # Sets a policy on a bucket. # def set_policy(policy) @bucket_policy.put(policy: policy) true rescue Aws::Errors::ServiceError => e puts "Couldn't set the policy for #{@bucket_policy.bucket.name}. Here's why: #{e.message}" false end end
  • API の詳細については、「 API リファレンスPutBucketPolicy」の「」を参照してください。 AWS SDK for Ruby

次の例は、PutBucketWebsite を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps Amazon S3 bucket website actions. class BucketWebsiteWrapper attr_reader :bucket_website # @param bucket_website [Aws::S3::BucketWebsite] A bucket website object configured with an existing bucket. def initialize(bucket_website) @bucket_website = bucket_website end # Sets a bucket as a static website. # # @param index_document [String] The name of the index document for the website. # @param error_document [String] The name of the error document to show for 4XX errors. # @return [Boolean] True when the bucket is configured as a website; otherwise, false. def set_website(index_document, error_document) @bucket_website.put( website_configuration: { index_document: { suffix: index_document }, error_document: { key: error_document } } ) true rescue Aws::Errors::ServiceError => e puts "Couldn't configure #{@bucket_website.bucket.name} as a website. Here's why: #{e.message}" false end end # Example usage: def run_demo bucket_name = "doc-example-bucket" index_document = "index.html" error_document = "404.html" wrapper = BucketWebsiteWrapper.new(Aws::S3::BucketWebsite.new(bucket_name)) return unless wrapper.set_website(index_document, error_document) puts "Successfully configured bucket #{bucket_name} as a static website." end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスPutBucketWebsite」の「」を参照してください。 AWS SDK for Ruby

次の例は、PutObject を使用する方法を説明しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

マネージドアップローダー (Object.upload_file) を使用してファイルをアップロードします。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectUploadFileWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end # Uploads a file to an Amazon S3 object by using a managed uploader. # # @param file_path [String] The path to the file to upload. # @return [Boolean] True when the file is uploaded; otherwise false. def upload_file(file_path) @object.upload_file(file_path) true rescue Aws::Errors::ServiceError => e puts "Couldn't upload file #{file_path} to #{@object.key}. Here's why: #{e.message}" false end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-uploaded-file" file_path = "object_upload_file.rb" wrapper = ObjectUploadFileWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) return unless wrapper.upload_file(file_path) puts "File #{file_path} successfully uploaded to #{bucket_name}:#{object_key}." end run_demo if $PROGRAM_NAME == __FILE__

Object.put を使用してファイルをアップロードします。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectPutWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end def put_object(source_file_path) File.open(source_file_path, "rb") do |file| @object.put(body: file) end true rescue Aws::Errors::ServiceError => e puts "Couldn't put #{source_file_path} to #{object.key}. Here's why: #{e.message}" false end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-object-key" file_path = "my-local-file.txt" wrapper = ObjectPutWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) success = wrapper.put_object(file_path) return unless success puts "Put file #{file_path} into #{object_key} in #{bucket_name}." end run_demo if $PROGRAM_NAME == __FILE__

Object.put を使用してファイルをアップロードし、サーバー側の暗号化を追加します。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectPutSseWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end def put_object_encrypted(object_content, encryption) @object.put(body: object_content, server_side_encryption: encryption) true rescue Aws::Errors::ServiceError => e puts "Couldn't put your content to #{object.key}. Here's why: #{e.message}" false end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-encrypted-content" object_content = "This is my super-secret content." encryption = "AES256" wrapper = ObjectPutSseWrapper.new(Aws::S3::Object.new(bucket_name, object_content)) return unless wrapper.put_object_encrypted(object_content, encryption) puts "Put your content into #{bucket_name}:#{object_key} and encrypted it with #{encryption}." end run_demo if $PROGRAM_NAME == __FILE__
  • API の詳細については、「 API リファレンスPutObject」の「」を参照してください。 AWS SDK for Ruby

シナリオ

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" require "net/http" # Creates a presigned URL that can be used to upload content to an object. # # @param bucket [Aws::S3::Bucket] An existing Amazon S3 bucket. # @param object_key [String] The key to give the uploaded object. # @return [URI, nil] The parsed URI if successful; otherwise nil. def get_presigned_url(bucket, object_key) url = bucket.object(object_key).presigned_url(:put) puts "Created presigned URL: #{url}" URI(url) rescue Aws::Errors::ServiceError => e puts "Couldn't create presigned URL for #{bucket.name}:#{object_key}. Here's why: #{e.message}" end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-file.txt" object_content = "This is the content of my-file.txt." 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" => "") end case response when Net::HTTPSuccess puts "Content uploaded!" else puts response.value end end run_demo if $PROGRAM_NAME == __FILE__

次のコードサンプルは、以下の操作方法を示しています。

  • バケットを作成し、そこにファイルをアップロードします。

  • バケットからオブジェクトをダウンロードします。

  • バケット内のサブフォルダにオブジェクトをコピーします。

  • バケット内のオブジェクトを一覧表示します。

  • バケットオブジェクトとバケットを削除します。

SDK for Ruby
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

require "aws-sdk-s3" # Wraps the getting started scenario actions. class ScenarioGettingStarted attr_reader :s3_resource # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def initialize(s3_resource) @s3_resource = s3_resource end # Creates a bucket with a random name in the currently configured account and # AWS Region. # # @return [Aws::S3::Bucket] The newly created bucket. def create_bucket bucket = @s3_resource.create_bucket( bucket: "doc-example-bucket-#{Random.uuid}", create_bucket_configuration: { 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("\t#{e.code}: #{e.message}") puts("\nCan't continue the demo without a bucket!") raise else bucket end # Requests a file name from the user. # # @return The name of the file. def create_file File.open("demo.txt", w) { |f| f.write("This is a demo file.") } end # Uploads a file to an Amazon S3 bucket. # # @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") 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}.") puts("\t#{e.code}: #{e.message}") raise else s3_object end # Downloads an Amazon S3 object to a file. # # @param s3_object [Aws::S3::Object] The object to download. 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: ") file_name = gets.chomp s3_object.download_file(file_name) puts("Object #{s3_object.key} successfully downloaded to #{file_name}.") end rescue Aws::Errors::ServiceError => e puts("Couldn't download #{s3_object.key}.") puts("\t#{e.code}: #{e.message}") raise end # Copies an Amazon S3 object to a subfolder within the same bucket. # # @param source_object [Aws::S3::Object] The source object to copy. # @return [Aws::S3::Object, nil] The destination object. 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" 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}.") end rescue Aws::Errors::ServiceError => e puts("Couldn't copy #{source_object.key}.") puts("\t#{e.code}: #{e.message}") raise else dest_object end # Lists the objects in an Amazon S3 bucket. # # @param bucket [Aws::S3::Bucket] The bucket to query. def list_objects(bucket) puts("\nYour bucket contains the following objects:") bucket.objects.each do |obj| puts("\t#{obj.key}") end rescue Aws::Errors::ServiceError => e puts("Couldn't list the objects in bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end # Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. 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" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end end # Runs the Amazon S3 getting started scenario. def run_scenario(scenario) puts("-" * 88) puts("Welcome to the Amazon S3 getting started demo!") puts("-" * 88) bucket = scenario.create_bucket s3_object = scenario.upload_file(bucket) scenario.download_file(s3_object) scenario.copy_object(s3_object) scenario.list_objects(bucket) scenario.delete_bucket(bucket) puts("Thanks for watching!") puts("-" * 88) rescue Aws::Errors::ServiceError puts("Something went wrong with the demo!") end run_scenario(ScenarioGettingStarted.new(Aws::S3::Resource.new)) if $PROGRAM_NAME == __FILE__

サーバーレスサンプル

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

SDK for Ruby
注記

については、「」を参照してください GitHub。サーバーレスサンプルリポジトリで完全な例を検索し、設定および実行の方法を確認してください。

Ruby を使用して Lambda での S3 イベントの消費。

require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: #{JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: #{response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end