Class: CapEC2::EC2Handler

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/cap-ec2/ec2-handler.rb

Instance Method Summary collapse

Methods included from Utils

contact_point, contact_point_mapping, #get_regions, #load_config, #project_tag, #roles_tag, #stages_tag

Constructor Details

#initializeEC2Handler



5
6
7
8
9
10
11
12
# File 'lib/cap-ec2/ec2-handler.rb', line 5

def initialize
  load_config
  configured_regions = get_regions(fetch(:ec2_region))
  @ec2 = {}
  configured_regions.each do |region|
    @ec2[region] = ec2_connect(region)
  end
end

Instance Method Details

#applicationObject



52
53
54
# File 'lib/cap-ec2/ec2-handler.rb', line 52

def application
  Capistrano::Configuration.env.fetch(:application).to_s
end

#defined_rolesObject



44
45
46
# File 'lib/cap-ec2/ec2-handler.rb', line 44

def defined_roles
  Capistrano::Configuration.env.send(:servers).send(:available_roles).sort
end

#ec2_connect(region = nil) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/cap-ec2/ec2-handler.rb', line 14

def ec2_connect(region=nil)
  AWS::EC2.new(
    access_key_id: fetch(:ec2_access_key_id),
    secret_access_key: fetch(:ec2_secret_access_key),
    region: region
  )
end

#get_servers_for_role(role) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/cap-ec2/ec2-handler.rb', line 60

def get_servers_for_role(role)
  servers = []
  @ec2.each do |_, ec2|
    instances = ec2.instances
      .filter(tag(project_tag), "*#{application}*")
      .filter('instance-state-name', 'running')
    servers << instances.select do |i|
      instance_has_tag?(i, roles_tag, role) &&
        instance_has_tag?(i, stages_tag, stage) &&
        instance_has_tag?(i, project_tag, application)
    end
  end
  servers.flatten.sort_by {|s| s.tags["Name"]}
end

#instance_idsObject



36
37
38
39
40
41
42
# File 'lib/cap-ec2/ec2-handler.rb', line 36

def instance_ids
  puts defined_roles.map {|r| get_servers_for_role(r)}
               .flatten
               .uniq {|i| i.instance_id}
               .map {|i| i.instance_id}
               .join("\n")
end

#server_namesObject



28
29
30
31
32
33
34
# File 'lib/cap-ec2/ec2-handler.rb', line 28

def server_names
  puts defined_roles.map {|r| get_servers_for_role(r)}
               .flatten
               .uniq {|i| i.instance_id}
               .map {|i| i.tags["Name"]}
               .join("\n")
end

#stageObject



48
49
50
# File 'lib/cap-ec2/ec2-handler.rb', line 48

def stage
  Capistrano::Configuration.env.fetch(:stage).to_s
end

#status_tableObject



22
23
24
25
26
# File 'lib/cap-ec2/ec2-handler.rb', line 22

def status_table
  CapEC2::StatusTable.new(
    defined_roles.map {|r| get_servers_for_role(r)}.flatten.uniq {|i| i.instance_id}
  )
end

#tag(tag_name) ⇒ Object



56
57
58
# File 'lib/cap-ec2/ec2-handler.rb', line 56

def tag(tag_name)
  "tag:#{tag_name}"
end