Skip to content

Instantly share code, notes, and snippets.

@JoeZ99
Last active April 12, 2021 12:51
Show Gist options
  • Save JoeZ99/ecbfd8720114232ec4382dd3a787bfaa to your computer and use it in GitHub Desktop.
Save JoeZ99/ecbfd8720114232ec4382dd3a787bfaa to your computer and use it in GitHub Desktop.
to get region an instance is running at
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