Class: Awshark::Ec2::SecurityGroup

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/awshark/ec2/security_group.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#logger

Constructor Details

#initialize(id:, username:) ⇒ SecurityGroup

Returns a new instance of SecurityGroup.



10
11
12
13
14
15
16
# File 'lib/awshark/ec2/security_group.rb', line 10

def initialize(id:, username:)
  validate!(:id, id)
  validate!(:username, username)

  @security_group_id = id
  @username = username
end

Instance Attribute Details

#security_group_idObject (readonly)

Returns the value of attribute security_group_id.



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

def security_group_id
  @security_group_id
end

#usernameObject (readonly)

Returns the value of attribute username.



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

def username
  @username
end

Instance Method Details

#authorize(ip:, ports:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/awshark/ec2/security_group.rb', line 18

def authorize(ip:, ports:)
  ports.each do |port|
    ip_rule = SecurityRule.new(
      ip: ip,
      from_port: port,
      to_port: port,
      description: username
    )
    client.authorize_security_group_ingress(
      group_id: security_group_id,
      ip_permissions: [ip_rule.to_hash]
    )
    logger.info "Created ingress rule in for #{ip_rule.cidr_ip}, port #{port}."
  rescue Aws::EC2::Errors::InvalidPermissionDuplicate
    logger.warn "An ingress rule for #{ip} and port #{port} exists."
  end
end

#my_ingress_rulesObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/awshark/ec2/security_group.rb', line 46

def my_ingress_rules
  return @my_ingress_rules if defined?(@my_ingress_rules)

  response = client.describe_security_groups(group_ids: [security_group_id])
  return [] if response.security_groups.empty?

  security_group = response.security_groups.first
  security_rules = security_group.ip_permissions.map do |ip_permission|
    SecurityRule.new(ip_permission)
  end

  @my_ingress_rules = security_rules.map do |rule|
    rule.ip_ranges.keep_if { |ip_range| ip_range.description == username }
    rule.ip_ranges.any? ? rule.to_hash : nil
  end

  @my_ingress_rules.compact!
end

#unauthorizeObject



36
37
38
39
40
41
42
43
44
# File 'lib/awshark/ec2/security_group.rb', line 36

def unauthorize
  return if my_ingress_rules.empty?

  client.revoke_security_group_ingress(
    group_id: security_group_id,
    ip_permissions: my_ingress_rules
  )
  logger.info "Removed all ingress rules for #{username}."
end