Skip to content

Instantly share code, notes, and snippets.

@pranavraja
Created May 6, 2022 00:15
Show Gist options
  • Save pranavraja/f3585456d02216eba40dfc2605570935 to your computer and use it in GitHub Desktop.
Save pranavraja/f3585456d02216eba40dfc2605570935 to your computer and use it in GitHub Desktop.
Utility to fetch AWS credentials for use with aws-beam/aws-elixir, the same way the AWS CLI does it (including support for roles)
defmodule AWSUtil do
def profile(name) do
{:ok, config} = ConfigParser.parse_file(Path.expand("~/.aws/credentials"))
case ConfigParser.get(config, name, "source_profile") do
nil ->
AWS.Client.create(
ConfigParser.get(config, name, "aws_access_key_id"),
ConfigParser.get(config, name, "aws_secret_access_key"),
ConfigParser.get(config, name, "region")
)
source ->
profile(source)
|> assume(
ConfigParser.get(config, name, "role_arn"),
ConfigParser.get(config, name, "region")
)
end
end
defp assume(client, role_arn, region) do
AWS.STS.assume_role(client, %{
"RoleArn" => role_arn,
"RoleSessionName" => "session"
})
|> response("AssumeRoleResponse")
|> client_from_assume_role_response(region)
end
defp client_from_assume_role_response(res, region) do
%{"AssumeRoleResult" => %{"Credentials" => creds}} = res
AWS.Client.create(
creds["AccessKeyId"],
creds["SecretAccessKey"],
creds["SessionToken"],
region
)
end
def response({:ok, res, _}, key) do
res[key]
end
def response({:error, err}, _key) do
err
end
end
@pranavraja
Copy link
Author

Requires Mix.install([:configparser_ex, :aws, :hackney]) before using.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment