Late last year, Amazon announced v2 of AWS Ruby SDK. Among other features, Amazon added Resource and Client classes for each of their services. While being functionally equivalent, they present different paradigms.
The Client class serves as a proxy to the API calls, with 1-to-1 method mapping and the more interesting Resource class offers an object-oriented interface.
In this demo, we will solve a simple problem of:
- listing all EC2 instances along with some useful information
- rebooting all of them
We will accomplish this using the Client and Resource classes separately, to show the difference in approach.
- aws-sdk gem
- AWS account
Create a creds.json file, that looks like this:
The keys are account specific. You can get yours on the AWS portal in the Security Credentials tab.
Here’s the code to create the
Credentials object. We will use it in a bit.
We start with creating the
Client instance. Notice the use of previously created
Next, we list and reboot the instances:
First, we create the
Resource instance, in a similar fashion.
To list all instances, we use the
instances method, which returns a Collection of
Notice the difference from the Client approach here.
Once we have a collections of instances, we just iterate over them and output the properties.
As we iterate over
Instances, we can also invoke the
reboot method directly on the elements.
Client offers a more procedural approach, which is more intuitive for people accustomed
to the AWS Command Line Interface. It’s undeniable advantage is the ability to perform bulk operations
on many instances, which might be a factor when dealing with high number of instances.
Resource on the other hand, with it’s object oriented
angle, is easier for manipulation and results in higher code readability.
- AWS SDK for Ruby v2 Reference
- Complete code for Client implementation
- Complete code for Resource implementation