Last active
April 12, 2021 12:51
-
-
Save JoeZ99/ecbfd8720114232ec4382dd3a787bfaa to your computer and use it in GitHub Desktop.
to get region an instance is running at
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyAws.Metadata | |
# AWS InstanceMetaData URL | |
@meta_path_region "http://169.254.169.254/latest/meta-data/placement/availability-zone" | |
@region_regexp ~r/(?<continent>eu|us)-(?<zone>[^-]+)-(?<number>[\d]+)/i | |
@doc """ | |
Get aws region. | |
First, it tries with :some_app, :aws_region variable stablished in config (hopefuly using env vars), and if no | |
it assumes the code is running in an ec2 instance, so it tries to get the region from instance metadata. | |
""" | |
@spec get_region() :: binary() | |
def get_region, do: Application.get_env(:some_app,:aws_region, get_region_from_instance_metadata()) | |
@spec get_region_from_instance_metadata() :: binary() | |
defp get_region_from_instance_metadata do | |
%{"continent" => continent, "zone" => zone, "number" => number} = | |
Regex.named_captures( | |
@region_regexp, | |
ExAws.InstanceMeta.request(ExAws.Config.new(:s3), @meta_path_region) | |
) | |
continent <> "-" <> zone <> "-" <> number | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment