Class: Awful::Ec2

Inherits:
Cli show all
Defined in:
lib/awful/ec2.rb

Constant Summary collapse

COLORS =
{
  running:    :green,
  stopped:    :yellow,
  terminated: :red,
}

Instance Method Summary collapse

Methods inherited from Cli

#initialize, #ll, #version

Constructor Details

This class inherits a constructor from Awful::Cli

Instance Method Details

#addressesObject



157
158
159
160
161
162
163
# File 'lib/awful/ec2.rb', line 157

def addresses
  ec2.describe_addresses.map(&:addresses).flatten.map do |ip|
    [ ip.allocation_id, ip.public_ip, ip.instance_id, ip.domain ]
  end.output do |list|
    print_table list
  end
end

#allocateObject



143
144
145
146
147
# File 'lib/awful/ec2.rb', line 143

def allocate
  ec2.allocate_address(domain: 'vpc').first.output do |eip|
    puts eip.allocation_id, eip.public_ip
  end
end

#associate(name, eip) ⇒ Object



150
151
152
153
154
# File 'lib/awful/ec2.rb', line 150

def associate(name, eip)
  ec2.associate_address(instance_id: find_instance(name), allocation_id: eip).map(&:association_id).output do |id|
    puts id
  end
end

#azObject



132
133
134
135
136
137
138
139
140
# File 'lib/awful/ec2.rb', line 132

def az
  ec2.describe_availability_zones.availability_zones.output do |zones|
    if options[:long]
      print_table zones.map { |z| [z.zone_name, z.state, z.messages.join(',')] }
    else
      puts zones.map(&:zone_name)
    end
  end
end

#create(name) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/awful/ec2.rb', line 80

def create(name)
  opt = load_cfg.merge(symbolize_keys(options))
  whitelist = %i[image_id min_count max_count key_name security_group_ids user_data instance_type kernel_id
                 ramdisk_id  monitoring subnet_id disable_api_termination instance_initiated_shutdown_behavior
                 additional_info iam_instance_profile ebs_optimized network_interfaces]

  opt[:min_count] ||= 1
  opt[:max_count] ||= 1
  opt[:monitoring] = {enabled: opt.fetch(:monitoring, {}).fetch(:state, '') == 'enabled'}

  ## set subnet from human-readable name, either for network interface, or instance-level
  if opt[:subnet]
    subnet = find_subnet(opt[:subnet])
    opt[:network_interfaces] ? (opt[:network_interfaces][0][:subnet_id] = subnet) : (opt[:subnet_id] = subnet)
  end

  (opt[:tags] = opt.fetch(:tags, [])).find_index { |t| t[:key] == 'Name' }.output do |index|
    opt[:tags][index || 0] = {key: 'Name', value: name}
  end

  ## TODO: block_device_mappings
  ## TODO: placement

  opt[:security_group_ids] = opt.fetch(:security_groups, []).map { |sg| sg[:group_id] }
  opt[:user_data] = Base64.strict_encode64(opt[:user_data]) if opt[:user_data]

  # scrub unwanted fields from a copied instance dump
  opt = remove_empty_strings(opt)

  ## start instance
  response = ec2.run_instances(only_keys_matching(opt, whitelist))
  ids = response.instances.map(&:instance_id)
  ec2.create_tags(resources: ids, tags: opt[:tags]) # tag instances
  puts ids # report new instance ids

  ## wait for instance to enter running state
  puts 'running instance ...'
  ec2.wait_until(:instance_running, instance_ids: ids)

  ## allocate and associate new elastic IPs
  ids.map { |id| associate(id, allocate.allocation_id) } if opt[:elastic_ip]

  ## report DNS or IP for instance
  ec2.describe_instances(instance_ids: ids).map(&:reservations).flatten.map(&:instances).flatten.map do |instance|
    instance.public_dns_name or instance.public_ip_address or instance.private_ip_address
  end.output do |list|
    puts list
  end
end

#delete(name) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/awful/ec2.rb', line 219

def delete(name)
  id =
    if name.match(/^i-[\d[a-f]]{8,17}$/)
      name
    else
      ec2.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.find do |instance|
        tag_name(instance) == name and not %w[terminated shutting-down].include?(instance.state.name)
      end.instance_id
    end
  if yes? "Really terminate instance #{name} (#{id})?", :yellow
    ec2.terminate_instances(instance_ids: Array(id))
  end
end

#dns(name) ⇒ Object



166
167
168
169
170
171
172
# File 'lib/awful/ec2.rb', line 166

def dns(name)
  ec2.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.find do |instance|
    instance.instance_id == name or (n = tag_name(instance) and n.match(name))
  end.public_dns_name.output do |dns|
    puts dns
  end
end

#dump(name) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/awful/ec2.rb', line 68

def dump(name)
  ec2.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.find do |instance|
    instance.instance_id == name or tag_name(instance) == name
  end.output do |instance|
    puts YAML.dump(stringify_keys(instance.to_hash))
  end
end

#ls(name = nil) ⇒ Object



19
20
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
60
61
62
63
64
65
# File 'lib/awful/ec2.rb', line 19

def ls(name = nil)
  params = {instance_ids: [], filters: []}

  ## filter by ids
  options[:ids].each do |id|
    params[:instance_ids] << id
  end

  ## filter by arbitrary tags
  options[:tags].each do |tag|
    key, value = tag.split(/[:=]/)
    params[:filters] << {name: "tag:#{key}", values: [value]}
  end

  ## filter shortcuts for stack, resource, autoscaling group
  params[:filters] << {name: 'tag:aws:cloudformation:stack-name', values: [options[:stack]]}       if options[:stack]
  params[:filters] << {name: 'tag:aws:cloudformation:logical-id', values: [options[:resource]]}    if options[:resource]
  params[:filters] << {name: 'tag:aws:autoscaling:groupName',     values: [options[:autoscaling]]} if options[:autoscaling]
  params[:filters] << {name: 'instance-state-name',               values: [options[:state]]}       if options[:state]

  ## get list of instances
  instances = ec2.describe_instances(params.reject{ |k,v| v.empty? }).reservations.map(&:instances).flatten

  ## filter by Name tag as a regex
  instances.select! { |i| tag_name(i, '').match(name) } if name

  ## output
  instances.output do |list|
    if options[:long]
      print_table list.map { |i|
        [
          tag_name(i, ''),
          i.instance_id,
          i.instance_type,
          i.image_id,
          i.placement.availability_zone,
          color(i.state.name),
          i.security_groups.map(&:group_name).join(',').slice(0..30),
          i.private_ip_address,
          i.public_ip_address
        ]
      }.sort_by(&:first)
    else
      puts list.map(&:instance_id)
    end
  end
end

#start(name) ⇒ Object



210
211
212
213
214
215
216
# File 'lib/awful/ec2.rb', line 210

def start(name)
  ec2.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.find do |instance|
    instance.instance_id == name or (n = tag_name(instance) and n == name)
  end.instance_id.output do |id|
    ec2.start_instances(instance_ids: Array(id))
  end
end

#stop(name) ⇒ Object



199
200
201
202
203
204
205
206
207
# File 'lib/awful/ec2.rb', line 199

def stop(name)
  ec2.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.find do |instance|
    instance.instance_id == name or (n = tag_name(instance) and n == name)
  end.instance_id.output do |id|
    if yes? "Really stop instance #{name} (#{id})?", :yellow
      ec2.stop_instances(instance_ids: Array(id))
    end
  end
end

#user_data(name) ⇒ Object



188
189
190
191
192
193
194
195
196
# File 'lib/awful/ec2.rb', line 188

def user_data(name)
  ec2.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.find do |instance|
    instance.instance_id == name or tag_name(instance) == name
  end.output do |instance|
    ec2.describe_instance_attribute(instance_id: instance.instance_id, attribute: 'userData').user_data.value.output do |user_data|
      puts Base64.strict_decode64(user_data)
    end
  end
end