Last active
December 26, 2015 15:49
-
-
Save EronHennessey/7175552 to your computer and use it in GitHub Desktop.
List the S3 buckets for your AWS account/region. Can also list the contents of a bucket or the contents of a file, depending on how many command-line arguments you supply. ;) Uses the AWS SDK for Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# List the S3 buckets that are available for the user identified by either | |
# `aws-config.txt` or in the environment. | |
require 'aws-sdk' | |
require 'yaml' | |
CONFIG_FILE_NAME = 'aws-config.txt' | |
# Load aws-config.txt to see if there are AWS credentials there. | |
# | |
# We're expecting a YAML-formatted file like this: | |
# | |
# --- | |
# access_key_id: ACCESSKEYID | |
# secret_access_key: SECRETACCESKEY | |
# | |
begin | |
config_file = File.open(CONFIG_FILE_NAME) { |f| f.read } | |
options = YAML.load(config_file) | |
AWS.config(options) | |
rescue | |
puts "** Hmmm, no config file (#{CONFIG_FILE_NAME})!" | |
# Without setting AWS credentials specifically, the AWS SDK will try to load | |
# them from the environment variables. Check the environment variables, just | |
# to make sure... | |
if ENV['AWS_ACCESS_KEY_ID'].nil? or ENV['AWS_SECRET_ACCESS_KEY'].nil? | |
puts "** No AWS access information in environment, either. Aborting!" | |
exit | |
end | |
end | |
# Create a new S3 object | |
s3 = AWS::S3.new | |
# If the user supplied arguments, the first is the bucket name, the second is | |
# the object name. | |
bucket_name, object_name = ARGV | |
if bucket_name.nil? | |
# No bucket name given, so list all of the buckets. | |
s3.buckets.each { |b| puts b.name } | |
else | |
# The user provided at least a bucket name... | |
b = s3.buckets[bucket_name] | |
# If the user specified a bucket but it's not there, alert the user. | |
unless b.exists? | |
puts "The bucket \"#{bucket_name}\" doesn't exist!" | |
exit | |
end | |
# Did the user also provide an object name? | |
if object_name.nil? | |
# List the contents of the bucket. | |
b.objects.each { |o| puts o.key } | |
else | |
# Get the contents of the object and send to stdout. We can use this to | |
# download objects from S3. | |
o = b.objects[object_name] | |
if o.exists? | |
# It is better to read the file in *chunks* rather than all at once. This | |
# is not so important for small objects, but much more important for large | |
# ones... Without a block, read will return the entire object, even if | |
# it's HUUUGE. | |
o.read { |chunk| $stdout.write(chunk) } | |
else | |
puts "object \"#{object_name}\" doesn't exist in bucket \"#{bucket_name}\"" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment