Class: Ec2ex::Core

Inherits:
Object
  • Object
show all
Defined in:
lib/ec2ex/core.rb

Instance Method Summary collapse

Constructor Details

#initializeCore

Returns a new instance of Core.



11
12
13
14
15
16
# File 'lib/ec2ex/core.rb', line 11

def initialize
  ENV['AWS_REGION'] = ENV['AWS_REGION'] || get_document['region']
  @ec2 = Aws::EC2::Client.new
  @elb = Aws::ElasticLoadBalancing::Client.new
  @logger = Logger.new(STDOUT);
end

Instance Method Details

#allocate_address_vpcObject



334
335
336
# File 'lib/ec2ex/core.rb', line 334

def allocate_address_vpc
  @ec2.allocate_address(domain: 'vpc').data
end

#associate_address(instance_id, public_ip_address) ⇒ Object



250
251
252
253
254
255
# File 'lib/ec2ex/core.rb', line 250

def associate_address(instance_id, public_ip_address)
  unless public_ip_address.nil?
    allocation_id = get_allocation(public_ip_address).allocation_id
    resp = @ec2.associate_address(instance_id: instance_id, allocation_id: allocation_id)
  end
end

#clientObject



18
19
20
# File 'lib/ec2ex/core.rb', line 18

def client
  @ec2
end

#create_image_with_instance(instance, region = nil) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/ec2ex/core.rb', line 146

def create_image_with_instance(instance, region = nil)
  tags = get_tag_hash(instance.tags)
  @logger.info "#{tags['Name']} image creating..."

  image_name = tags['Name'] + ".#{Time.now.strftime('%Y%m%d%H%M%S')}"
  image_response = @ec2.create_image(
    instance_id: instance.instance_id,
    name: image_name,
    no_reboot: true
  )
  sleep 10
  @ec2.wait_until(:image_available, image_ids: [image_response.image_id]) do |w|
    w.interval = 15
    w.max_attempts = 1440
  end
  @logger.info "image create complete #{tags['Name']}! image_id => [#{image_response.image_id}]"

  ami_tag = format_tag(get_ami_tag_hash(instance, tags))
  @ec2.create_tags(resources: [image_response.image_id], tags: ami_tag)

  if region
    @logger.info "copying another region... [#{ENV['AWS_REGION']}] => [#{region}]"
    dest_ec2 = Aws::EC2::Client.new(region: region)
    copy_image_response = dest_ec2.copy_image(
      source_region: ENV['AWS_REGION'],
      source_image_id: image_response.image_id,
      name: image_name
    )
    dest_ec2.create_tags(resources: [copy_image_response.image_id], tags: ami_tag)
  end

  image_response.image_id
end


303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/ec2ex/core.rb', line 303

def deregister_snapshot_no_related(owner_id)
  enable_snapshot_ids = []
  images('*').each do |image|
    image_id = image[:image_id]
    snapshot_ids = image[:block_device_mappings]
      .select{ |block_device_mapping| block_device_mapping[:ebs] != nil }
      .map{ |block_device_mapping| block_device_mapping[:ebs][:snapshot_id] }
    enable_snapshot_ids.concat(snapshot_ids)
  end
  filter = [{ name: 'owner-id', values: [owner_id] }]
  all_snapshot_ids = @ec2.describe_snapshots(
    filters: filter
  ).data.to_h[:snapshots].map{ |snapshot| snapshot[:snapshot_id] }
  disable_snapshot_ids = (all_snapshot_ids - enable_snapshot_ids)
  disable_snapshot_ids.each do |disable_snapshot_id|
    @ec2.delete_snapshot({snapshot_id: disable_snapshot_id})
    @logger.info "delete snapshot #{disable_snapshot_id}"
  end
end

#elb_clientObject



43
44
45
# File 'lib/ec2ex/core.rb', line 43

def elb_client
  @elb
end

#extract_fields(data, fields) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ec2ex/core.rb', line 47

def extract_fields(data, fields)
  results = []
  data.each do |row|
    row = Hashie::Mash.new(row) if row.class == Hash
    result = {}
    fields.map { |key|
      result[key] = eval("row.#{key}")
    }
    results << result
  end
  results
end

#format_tag(tag, preset_tag_hash = {}) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/ec2ex/core.rb', line 64

def format_tag(tag, preset_tag_hash = {})
  tags = []
  tag.each do |k, v|
    value = v ? ERB.new(v.gsub(/\$\{([^}]+)\}/, "<%=preset_tag_hash['" + '\1' + "'] %>")).result(binding) : ''
    tags << { key: k, value: value }
  end
  tags
end

#get_allocation(public_ip_address) ⇒ Object



211
212
213
# File 'lib/ec2ex/core.rb', line 211

def get_allocation(public_ip_address)
  @ec2.describe_addresses(public_ips: [public_ip_address]).addresses.first
end

#get_ami_tag_hash(instance, tags) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/ec2ex/core.rb', line 124

def get_ami_tag_hash(instance, tags)
  ami_tag_hash = {
    'created' => Time.now.strftime('%Y%m%d%H%M%S'),
    'tags' => instance.tags.map(&:to_hash).to_json,
    'Name' => tags['Name']
  }
  ami_tag_hash['security_groups'] = instance.security_groups.map(&:group_id).to_json
  ami_tag_hash['private_ip_address'] = instance.private_ip_address
  unless instance.public_ip_address.nil?
    ami_tag_hash['public_ip_address'] = instance.public_ip_address
  end
  ami_tag_hash['instance_type'] = instance.instance_type
  ami_tag_hash['placement'] = instance.placement.to_hash.to_json
  unless instance.iam_instance_profile.nil?
    ami_tag_hash['iam_instance_profile'] = instance.iam_instance_profile.arn.split('/').last
  end
  unless instance.key_name.nil?
    ami_tag_hash['key_name'] = instance.key_name
  end
  ami_tag_hash
end

#get_documentObject



26
27
28
# File 'lib/ec2ex/core.rb', line 26

def get_document
  JSON.parse(('/latest/dynamic/instance-identity/document/'))
end

#get_metadata(path) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ec2ex/core.rb', line 30

def (path)
  begin
    result = {}
    ::Timeout.timeout(TIME_OUT) {
      body = open('http://169.254.169.254' + path).read
      return body
    }
    return result
  rescue TimeoutError => e
    raise "not EC2 instance"
  end
end

#get_old_images(name, num = 10) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/ec2ex/core.rb', line 266

def get_old_images(name, num = 10)
  result = search_image_with_name(name)
  return [] if result.empty?
  map = Hash.new{|h,k| h[k] = []}
  result = result.each{ |image|
    tag_hash = get_tag_hash(image[:tags])
    next if tag_hash['Name'].nil? || tag_hash['created'].nil?
    map[tag_hash['Name']] << image
  }
  old_images = []
  map.each do |name, images|
    sorted_images = images.sort_by{ |image|
      tag_hash = get_tag_hash(image[:tags])
      Time.parse(tag_hash['created'])
    }
    newly_images = sorted_images.last(num)
    old_images = old_images + (sorted_images - newly_images)
  end
  old_images
end

#get_subnet(private_ip_address) ⇒ Object



215
216
217
218
219
220
221
# File 'lib/ec2ex/core.rb', line 215

def get_subnet(private_ip_address)
  subnets = @ec2.describe_subnets.subnets.select{ |subnet|
    ip = IPAddress(subnet.cidr_block)
    ip.to_a.map { |ipv4| ipv4.address }.include?(private_ip_address)
  }
  subnets.first
end

#get_tag_hash(tags) ⇒ Object



73
74
75
76
77
78
79
# File 'lib/ec2ex/core.rb', line 73

def get_tag_hash(tags)
  result = {}
  tags.each {|hash|
    result[hash['key'] || hash[:key]] = hash['value'] || hash[:value]
  }
  Hashie::Mash.new(result)
end

#get_tag_hash_from_id(instance_id) ⇒ Object



81
82
83
84
85
86
87
# File 'lib/ec2ex/core.rb', line 81

def get_tag_hash_from_id(instance_id)
  preset_tag = {}
  @ec2.describe_tags(filters: [{ name: 'resource-id', values: [instance_id] }]).tags.each do |tag|
    preset_tag[tag.key] = tag.value
  end
  preset_tag
end

#group_count(list) ⇒ Object



60
61
62
# File 'lib/ec2ex/core.rb', line 60

def group_count(list)
  Hash[list.group_by { |e| e }.map { |k, v| [k, v.length] }]
end

#images(name) ⇒ Object



287
288
289
290
291
292
293
# File 'lib/ec2ex/core.rb', line 287

def images(name)
  filter = [{ name: 'is-public', values: ['false'] }]
  filter << { name: 'name', values: [name] }
  @ec2.describe_images(
    filters: filter
  ).data.to_h[:images]
end

#instances_hash(condition, running_only = true) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/ec2ex/core.rb', line 89

def instances_hash(condition, running_only = true)
  filter = []
  condition.each do |key, value|
    filter << { name: "tag:#{key}", values: ["#{value}"] }
  end
  if running_only
    filter << { name: 'instance-state-name', values: ['running'] }
  else
    filter << { name: 'instance-state-name', values: %w(running stopped) }
  end
  @ec2.describe_instances(
    filters: filter
  ).data.to_h[:reservations].map { |instance| Hashie::Mash.new(instance[:instances].first) }
end

#instances_hash_first_result(condition, running_only = true) ⇒ Object



104
105
106
107
108
109
110
111
112
# File 'lib/ec2ex/core.rb', line 104

def instances_hash_first_result(condition, running_only = true)
  results = instances_hash(condition, running_only)
  instance = results.first
  unless instance
    @logger.warn("not match instance => #{condition}")
    exit 1
  end
  instance
end

#instances_hash_with_id(instance_id) ⇒ Object



114
115
116
117
118
# File 'lib/ec2ex/core.rb', line 114

def instances_hash_with_id(instance_id)
  @ec2.describe_instances(
    instance_ids: [instance_id]
  ).data.to_h[:reservations].map { |instance| Hashie::Mash.new(instance[:instances].first) }.first
end

#latest_image_with_name(name) ⇒ Object



257
258
259
260
261
262
263
264
# File 'lib/ec2ex/core.rb', line 257

def latest_image_with_name(name)
  result = search_image_with_name(name)
  result = result.sort_by{ |image|
    tag_hash = get_tag_hash(image[:tags])
    tag_hash['created'].nil? ? '' : tag_hash['created']
  }
  result.empty? ? {} : result.last
end

#loggerObject



22
23
24
# File 'lib/ec2ex/core.rb', line 22

def logger
  @logger
end

#own_tagObject



120
121
122
# File 'lib/ec2ex/core.rb', line 120

def own_tag
  get_tag_hash(instances_hash_with_id(('/latest/meta-data/instance-id')).tags)
end

#ping?(private_ip_address) ⇒ Boolean

Returns:

  • (Boolean)


323
324
325
326
327
328
329
330
331
332
# File 'lib/ec2ex/core.rb', line 323

def ping?(private_ip_address)
  if private_ip_address
    pinger = Net::Ping::External.new(private_ip_address)
    if pinger.ping?
      @logger.info "already exists private_ip_address => #{private_ip_address}"
      return true
    end
  end
  return false
end

#search_image_with_name(name) ⇒ Object



295
296
297
298
299
300
301
# File 'lib/ec2ex/core.rb', line 295

def search_image_with_name(name)
  filter = [{ name: 'is-public', values: ['false'] }]
  filter << { name: 'tag:Name', values: [name] }
  @ec2.describe_images(
    filters: filter
  ).data.to_h[:images]
end

#set_delete_on_termination(instance) ⇒ Object



200
201
202
203
204
205
206
207
208
209
# File 'lib/ec2ex/core.rb', line 200

def set_delete_on_termination(instance)
  block_device_mappings = instance.block_device_mappings.map{ |block_device_mapping|
    ebs = block_device_mapping.ebs
    {
      device_name: block_device_mapping.device_name,
      ebs: { volume_id: block_device_mapping.ebs.volume_id, delete_on_termination: true }
    }
  }
  @ec2.modify_instance_attribute({instance_id: instance.instance_id, block_device_mappings: block_device_mappings})
end

#start_instance(instance_id) ⇒ Object



233
234
235
236
237
238
239
240
# File 'lib/ec2ex/core.rb', line 233

def start_instance(instance_id)
  @logger.info 'starting...'
  @ec2.start_instances(
    instance_ids: [instance_id]
  )
  @ec2.wait_until(:instance_running, instance_ids: [instance_id])
  @logger.info "start instance complete! instance_id => [#{instance_id}]"
end

#stop_instance(instance_id) ⇒ Object



223
224
225
226
227
228
229
230
231
# File 'lib/ec2ex/core.rb', line 223

def stop_instance(instance_id)
  @logger.info 'stopping...'
  @ec2.stop_instances(
    instance_ids: [instance_id],
    force: true
  )
  @ec2.wait_until(:instance_stopped, instance_ids: [instance_id])
  @logger.info "stop instance complete! instance_id => [#{instance_id}]"
end

#terminate_instance(instance) ⇒ Object



242
243
244
245
246
247
248
# File 'lib/ec2ex/core.rb', line 242

def terminate_instance(instance)
  instance_id = instance.instance_id
  @logger.info 'terminating...'
  @ec2.terminate_instances(instance_ids: [instance_id])
  @ec2.wait_until(:instance_terminated, instance_ids: [instance_id])
  @logger.info "terminate instance complete! instance_id => [#{instance_id}]"
end

#wait_spot_running(spot_instance_request_id) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/ec2ex/core.rb', line 180

def wait_spot_running(spot_instance_request_id)
  @logger.info 'spot instance creating...'
  instance_id = nil
  while true
    spot_instance_request = @ec2.describe_spot_instance_requests(spot_instance_request_ids: [spot_instance_request_id]).spot_instance_requests.first
    if spot_instance_request.state == 'active'
      instance_id = spot_instance_request.instance_id
      break
    elsif spot_instance_request.state == 'failed'
      @logger.info spot_instance_request.fault.code
      @ec2.cancel_spot_instance_requests({ spot_instance_request_ids: [spot_instance_request_id] })
      raise spot_instance_request.fault.message
    end
    sleep 10
  end
  @ec2.wait_until(:instance_running, instance_ids: [instance_id])
  @logger.info "spot instance create complete! instance_id => [#{instance_id}]"
  instance_id
end