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

#project_tag, #roles_tag, #stages_tag

Constructor Details

#initialize(ec2_config = "config/ec2.yml") ⇒ EC2Handler

Returns a new instance of EC2Handler.



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

def initialize(ec2_config = "config/ec2.yml")
  @ec2_config = YAML.load_file ec2_config
  @ec2 = {}
  @ec2_config["regions"].each do |region|
    @ec2[region] = AWS::EC2.new(
    access_key_id: @ec2_config["access_key_id"],
    secret_access_key: @ec2_config["secret_access_key"],
    region: region
  )
  end
end

Instance Method Details

#applicationObject



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

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

#defined_rolesObject



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

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

#each_regionObject



69
70
71
72
73
# File 'lib/cap-ec2/ec2-handler.rb', line 69

def each_region
  @ec2.keys.each do |region|
    yield @ec2[region]
  end
end

#get_servers_for_role(role) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/cap-ec2/ec2-handler.rb', line 56

def get_servers_for_role(role)
  servers = []
  each_region do |ec2|
    instances = ec2.instances
      .filter(tag(project_tag), application)
      .filter('instance-state-code', '16')
    servers << instances.select do |i| 
      i.tags[roles_tag] =~ /,{0,1}#{role}(,|$)/ && i.tags[stages_tag] =~ /,{0,1}#{stage}(,|$)/
    end
  end
  servers.flatten
end

#instance_idsObject



32
33
34
35
36
37
38
# File 'lib/cap-ec2/ec2-handler.rb', line 32

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



24
25
26
27
28
29
30
# File 'lib/cap-ec2/ec2-handler.rb', line 24

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



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

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

#status_tableObject



17
18
19
20
21
22
# File 'lib/cap-ec2/ec2-handler.rb', line 17

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

#tag(tag_name) ⇒ Object



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

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