Module: Lono::CurrentRegion

Included in:
Param::Generator, Template::Template
Defined in:
lib/lono/current_region.rb

Instance Method Summary collapse

Instance Method Details

#current_regionObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lono/current_region.rb', line 4

def current_region
  region = Aws.config[:region]
  region ||= ENV['AWS_REGION']
  return region if region

  if ENV['AWS_PROFILE']
    path = "#{ENV['HOME']}/.aws/config"
    if File.exist?(path)
      lines = IO.readlines(path)
      capture_default, capture_current = false, false
      lines.each do | line|
        if line.include?('[default]')
          capture_default = true # next line
          next
        end
        if capture_default && line.match(/region = /)
          default_region = line.split(' = ').last.strip
          capture_default = false
        end

        md = line.match(/\[profile (.*)\]/)
        if md && md[1] == ENV['AWS_PROFILE']
          capture_current = true
          next
        end
        if capture_current && line.match(/region = /)
          region = line.split(' = ').last.strip
          capture_current = false
        end
      end
    end

    region ||= default_region
    return region if region
  end

  'us-east-1' # default
end