Class: Rebi::EC2

Inherits:
Object
  • Object
show all
Includes:
Log
Defined in:
lib/rebi/ec2.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Log

#colorize, #colorize_prefix, #error, #error_label, #h1, #h2, #h3, #h4, #hstatus, #log

Constructor Details

#initialize(client) ⇒ EC2

Returns a new instance of EC2.



8
9
10
# File 'lib/rebi/ec2.rb', line 8

def initialize client
  @client = client
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



6
7
8
# File 'lib/rebi/ec2.rb', line 6

def client
  @client
end

Instance Method Details

#authorize_ssh(instance_id, &blk) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rebi/ec2.rb', line 21

def authorize_ssh instance_id, &blk
  group_id = describe_instance(instance_id).security_groups.map(&:group_id).sort.first

  my_ip = `dig +short myip.opendns.com @resolver1.opendns.com`.chomp
  cidr_ip = my_ip.present? ? "#{my_ip}/32" : "0.0.0.0/0"

  begin
    log "Attempting to open port 22."
    client.authorize_security_group_ingress({
      group_id: group_id,
      ip_protocol: "tcp",
      to_port: 22,
      from_port: 22,
      cidr_ip: cidr_ip
      })
    log "SSH port 22 open."

  rescue Aws::EC2::Errors::InvalidPermissionDuplicate
    log "Opened already"
  rescue Exception => e
    raise e
  end

  yield if block_given?

  ensure
    begin
      log "Attempting to close port 22."
      client.revoke_security_group_ingress({
        group_id: group_id,
        ip_protocol: "tcp",
        to_port: 22,
        from_port: 22,
        cidr_ip: cidr_ip
        })
    rescue Exception => e
      raise e
    end
end

#describe_instance(instance_id) ⇒ Object



16
17
18
19
# File 'lib/rebi/ec2.rb', line 16

def describe_instance instance_id
  res = client.describe_instances instance_ids: [instance_id]
  return res.reservations.first.instances.first
end

#log_labelObject



12
13
14
# File 'lib/rebi/ec2.rb', line 12

def log_label
  "EC2"
end