Class: VolumeSweeper::Providers::Aws

Inherits:
Base
  • Object
show all
Defined in:
lib/volume_sweeper/providers/aws.rb

Constant Summary collapse

DEFAULT_REGION =
'us-west-2'
DEFAULT_CONFIF_PATH =
'~/.aws/config'
DEFAULT_CREDS_PATH =
'~/.aws/credentials'
BASE_CONSOLE_URL =
"console.aws.amazon.com/ec2/home"
VOLUME_ATTRS =
%i{ volume_id displayName state size attachments create_time availability_zone tags }

Instance Attribute Summary

Attributes inherited from Base

#base_link

Instance Method Summary collapse

Methods inherited from Base

#delete_volumes, #scan_volumes

Constructor Details

#initialize(config_path: nil, region: nil, mode: :audit, **kwargs) ⇒ Aws

Returns a new instance of Aws.



18
19
20
21
22
23
24
# File 'lib/volume_sweeper/providers/aws.rb', line 18

def initialize config_path: nil, region: nil, mode: :audit, **kwargs
  super
  @region ||= DEFAULT_REGION
  set_console_base_url
  validate_attrs
  prepare_config config_path, kwargs[:creds_path]
end

Instance Method Details

#delete_block_volumes(ids_list) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/volume_sweeper/providers/aws.rb', line 51

def delete_block_volumes ids_list
  @log.msg "aws: #{ids_list&.count || 0} block volumes are eligible for cleanup."
  return if ids_list.blank?

  unless @run_mode == :delete
    @log.msg "aws: running in :#{@run_mode} mode, exiting without delete operations."
    return
  end

  @log.msg "aws: unused volume clean-up operation started."

  ids_list.each do |id|
    @log.msg "aws: deleting block volume #{id} .."
    run_api_call do |client|
      output = client.delete_volume({ volume_id: id.to_s })
      if output&.successful?
        @log.msg "aws: block volume #{id} is deleted successfully."
      else
        @log.msg "aws: block volume #{id} has failed."
      end
      sleep 2.5
    end
  end
end

#scan_block_volumesObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/volume_sweeper/providers/aws.rb', line 26

def scan_block_volumes
  volumes = Array.new
  next_token = nil
  opts = { max_results: 200 }

  run_api_call do |client|
    loop do
      response = client.describe_volumes opts.merge(next_token: next_token)
      response&.volumes&.map do |v|
        volumes << v.to_hash.compact.slice(*VOLUME_ATTRS).transform_keys(volume_id: :id)
      end
      break if response.nil? || response.next_token.nil?
      next_token = response.next_token
      sleep 2
    end
    @log.msg "aws: collected #{volumes.size} block volumes from the account."
  end

  @log.msg "aws: filtering out any block volume with an active attachment."
  result = volumes&.reject { |v| v[:state] != 'available' || v[:attachments]&.count > 0 } || []

  @log.msg "aws: found #{result.count} unattached block volumes."
  [volumes.size, result]
end