Setting Default Server-Side Encryption for an Amazon S3 Bucket
The following example uses the
put_bucket_encryption
method to enable KMS server-side encryption on any items added to
my_bucket
in the us-west-2
region.
The only exception is if the user configures their request to explicitly use server-side encryption. In that case, the specified encryption takes precedence.
Choose Copy
to save the code locally.
Create the file add_default_sse_encryption.rb.
Add the required Amazon S3 gem.
Note
Version 2 of the AWS SDK for Ruby didn't have service-specific gems.
require 'aws-sdk-s3' # In v2: require 'aws-sdk'
Get the KMS key from the command line,
Where key
is a KMS key ID as created in the Creating a CMK in AWS KMS example.
if ARGV.empty?() puts 'You must supply a key' exit 1 end key = ARGV[0]
Create an Amazon S3 client and call put_bucket_encryption
to add
default encryption to the bucket.
client.put_bucket_encryption( bucket: 'my_bucket', server_side_encryption_configuration: { rules: [{ apply_server_side_encryption_by_default: { sse_algorithm: 'aws:kms', kms_master_key_id: key } }] } )
See the complete example on GitHub.