Skip to content

Instantly share code, notes, and snippets.

@cwgem
Last active December 11, 2015 16:49
Show Gist options
  • Select an option

  • Save cwgem/4630490 to your computer and use it in GitHub Desktop.

Select an option

Save cwgem/4630490 to your computer and use it in GitHub Desktop.
A really REALLY basic look at the AWS SDK Ruby gem

Requirements

Ruby

I used Rubinius 1.9 for this but MRI and others that support the AWS gem will probably work.

Gem

You'll need to install the gem from here

gem install aws-sdk

Also can pick it up from the AWS SDK Ruby Repository over on GitHub.

Setup

I create a YAML file to store AWS creds. You can visit the AWS SDK for Ruby Getting Started page for information on how to create/access these credentials. I store them in a file called aws_config.yml which looks like this:

access_key_id: KEY
secret_access_key: SECRET

Then the basic code to setup is as follows:

require 'aws-sdk'

# Load the auth information 
config_file = File.join(File.dirname(__FILE__), "aws_config.yml")
AWS.config(YAML.load(File.read(config_file)))

# Create a new EC2 instance
ec2 = AWS::EC2.new()

# You can also create it with a specific availability zone
ec2 = AWS::EC2.new(:ec2_endpoint => 'ec2.us-west-1.amazonaws.com')

Basic Use

This creates an instance, polls it until it is out of pending status, shows all the instances available, then shuts down the recently started instance. I use a t1.micro so that people who copy and paste this code won't get charged some ridiculous amount.

instance = ec2.instances.create( :image_id => 'ami-id-goes-here', :instance_type => 't1.micro', :count => 1, :security_groups => 'YourGroup', :key_name => 'YourKey')

sleep 1 until instance.status != :pending

ec2.instances.each do | i |
  puts "#{i.id} #{i.status}"
end

instance.terminate

Additional Resources

You'll want to take a look at the AWS::EC2 docs for a basic overview. Of particular interest to most will be the AWS::EC2::Instance class which holds various properties of an instance and methods you can run on them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment