class Switcher

Attributes

aws[RW]
credentials[RW]
ec2[RW]
region[RW]

Public Class Methods

new(id) click to toggle source
# File lib/ec2_switcher.rb, line 11
def initialize(id)
  @region = set_region
  @credentials = set_credentials
  @aws = aws_connection
  @ec2 = ec2_client_connect(id)
  puts 'connected to ec2 server' if @ec2
end

Public Instance Methods

auto() click to toggle source
# File lib/ec2_switcher.rb, line 45
def auto
  self.running? ? self.off : self.on
end
ec2_client_connect(id) click to toggle source
# File lib/ec2_switcher.rb, line 19
def ec2_client_connect(id)
  @id ||= id
  Aws::EC2::Instance.new(credentials: @credentials, id: id)
end
off() click to toggle source
# File lib/ec2_switcher.rb, line 33
def off
  @ec2.stop
  puts 'instance stopping'
  self.reload
end
on() click to toggle source
# File lib/ec2_switcher.rb, line 39
def on
  @ec2.start
  puts 'instance starting'
  self.reload
end
reload() click to toggle source
# File lib/ec2_switcher.rb, line 24
def reload
  @ec2 = self.ec2_client_connect(@id)
end
running?() click to toggle source
# File lib/ec2_switcher.rb, line 28
def running?
  self.reload
  @ec2.state.to_s.include?("name=\"running\"")
end

Private Instance Methods

aws_connection() click to toggle source
# File lib/ec2_switcher.rb, line 69
def aws_connection
  Aws.config.update({
    region: @region,
    credentials: @credentials
  })
end
constants_not_defined?() click to toggle source
# File lib/ec2_switcher.rb, line 51
def constants_not_defined?
  defined?(EC2_AMAZON_ACCESS_KEY).nil? || defined?(EC2_AMAZON_SECRET_ACCESS).nil?
end
set_credentials() click to toggle source
# File lib/ec2_switcher.rb, line 59
def set_credentials
  if constants_not_defined?
    puts 'profile connection'
    Aws::SharedCredentials.new(profile_name: 'ec2')
  else
    puts 'global variables connection'
    Aws::Credentials.new(EC2_AMAZON_ACCESS_KEY, EC2_AMAZON_SECRET_ACCESS)
  end
end
set_region() click to toggle source
# File lib/ec2_switcher.rb, line 55
def set_region
  defined?(EC2_AMAZON_REGION).nil? ? EC2_AMAZON_REGION : 'eu-west-1'
end