Starting and stopping Amazon EC2 instances from an IRB session

Starting the EC2 instance

require 'aws-sdk'

ec2 = Aws::EC2::Client.new(region: 'us-east-1', 
  credentials: Aws::Credentials.new('access_key_id_here', 'private_key_here'))
#=> #<Aws::EC2::Client>

ec2.start_instances instance_ids: ['i-b1e68c07']

To find out the public IP address:

ec2.describe_instances[:reservations][1][:instances][0].public_ip_address
#=> "52.23.214.17"

In my EC2 Management Console window I have 2 different EC2 instances, the 1st is stopped, and the 2nd instance is started. That 2nd instance is referenced from the :reservations parent key. There is only 1 instance of this image running which is why the 1st array item from the parent key :instances is selected.

Stopping the EC2 instance

require 'aws-sdk'

ec2 = Aws::EC2::Client.new(region: 'us-east-1', 
  credentials: Aws::Credentials.new('access_key_id_here', 'private_key_here'))
#=> #<Aws::EC2::Client>

ec2.stop_instances instance_ids: ['i-b1e68c07']

Resources