Method: Jets::AwsInfo#region

Defined in:
lib/jets/aws_info.rb

#regionObject



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
42
43
44
45
46
# File 'lib/jets/aws_info.rb', line 7

def region
  return 'us-east-1' if test?

  return ENV['JETS_AWS_REGION'] if ENV['JETS_AWS_REGION'] # highest precedence
  return ENV['AWS_REGION'] if ENV['AWS_REGION']

  region = nil

  # First if aws binary is available
  # try to get it from the ~/.aws/config
  if which('aws')
    region = `aws configure get region 2>&1`.strip rescue nil
    exit_code = $?.exitstatus
    if exit_code != 0
      exception_message = region.split("\n").grep(/botocore\.exceptions/).first
      if exception_message
        puts "WARN: #{exception_message}".colorize(:yellow)
      else
        # show full message as warning
        puts region.colorize(:yellow)
      end
      puts "You can also get rid of this message by setting AWS_REGION or configuring ~/.aws/config with the region"
      region = nil
    end
    region = nil if region == ''
    return region if region
  end

  # Second try the metadata endpoint, should be available on AWS Lambda environment
  # https://stackoverflow.com/questions/4249488/find-region-from-within-an-ec2-instance
  begin
    az = `curl -s --max-time 3 --connect-timeout 5 http://169.254.169.254/latest/meta-data/placement/availability-zone`
    region = az.strip.chop # remove last char
    region = nil if region == ''
  rescue
  end
  return region if region

  'us-east-1' # default if all else fails
end