Sunday, June 21, 2015

Ruby script to use Azure Blob Storage

Azure Blob storage is a service for storing large amounts of unstructured data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.

This post will show you how to perform common scenarios using the Azure Blob service. The samples are written using the Ruby API. The scenarios covered include uploading, listing, downloading, and deleting blobs.

You can download final ruby script from here.

This post assumes you have already created a storage account and a container.

  • Type "gem install azure" in the command window to install the gem and dependencies.
  • Import installed package in to the script file.
require "azure"
view raw blobstorage1.rb hosted with ❤ by GitHub
  • Setup global parameters.
Azure.config.storage_account_name = "account"
Azure.config.storage_access_key = "xxxxxxxxxxxxxxx+xxxxxxxxxxxxxxxx/xxxx+xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=="
CONTAINER = "container"
AZURE_BLOB_SERVICE = Azure::BlobService.new
view raw blobstorage2.rb hosted with ❤ by GitHub
  • Uploading a Blob into a Container
def upload(input_path, blob_name)
content = File.open(input_path, "rb") { |file| file.read }
blob = AZURE_BLOB_SERVICE.create_block_blob(CONTAINER,
blob_name, content)
puts blob.name + " uploaded succesfully.."
end
view raw blobstorage3.rb hosted with ❤ by GitHub
  • List the Blobs in a Container
def list()
containers = AZURE_BLOB_SERVICE.list_containers()
containers.each do |container|
blobs = AZURE_BLOB_SERVICE.list_blobs(container.name)
blobs.each do |blob|
puts blob.name
end
end
end
view raw blobstorage4.rb hosted with ❤ by GitHub
  • Download Blobs
def download(blob_name, output_file)
blob, content = AZURE_BLOB_SERVICE.get_blob(CONTAINER,blob_name)
File.open(output_file,"wb") {|f| f.write(content)}
puts blob_name + " downloaded succesfully.."
end
view raw blobstorage5.rb hosted with ❤ by GitHub
  • Delete a Blob
def delete(blob_name)
AZURE_BLOB_SERVICE.delete_blob(CONTAINER, blob_name)
puts blob_name + " deleted succesfully.."
end
view raw blobstorage6.rb hosted with ❤ by GitHub

No comments:

Post a Comment