Skip to content

Instantly share code, notes, and snippets.

@adrobisch
Created January 17, 2019 15:20
Show Gist options
  • Save adrobisch/f5286e77ffec92b83e656b31c61de279 to your computer and use it in GitHub Desktop.
Save adrobisch/f5286e77ffec92b83e656b31c61de279 to your computer and use it in GitHub Desktop.
Scala Ammonite Script to update AWS session token in awscli profile via 2FA
import $ivy.`io.circe::circe-core:0.10.0`;import $ivy.`io.circe::circe-generic:0.10.0`;import $ivy.`io.circe::circe-parser:0.10.0`
import sys.process._
import io.circe._
@doc("This script updates the awscli profile with the keys and the session token from AWS")
@main def authenticate(mfaArn: String @doc("// you can find the mfa arn in https://console.aws.amazon.com/iam/home#/users/<your aws console login username>?section=security_credentials"),
token: String @doc("the token code from you authenticator app e.g. Google Authenticator or Authy"),
@doc("the profile to use to get the session token, you can configure it with `aws configure --profile <profile name>`") stsProfile: String = "mfa",
@doc("the profile to store the session keys and session token") sessionProfile: String = "mfa-session") = {
assert(!stsProfile.equals(sessionProfile), "sts profile and session profile must not be the same")
val sessionCommand = s"aws sts get-session-token --serial-number $mfaArn --token-code $token --profile $stsProfile --output json"
val sessionProperties = parser.decode[Json](sessionCommand.!!).right.get.asObject.get("Credentials").get.asObject.get
val accessKey = sessionProperties("AccessKeyId").get.asString.get
val secretKey = sessionProperties("SecretAccessKey").get.asString.get
val sessionToken = sessionProperties("SessionToken").get.asString.get
s"aws configure set aws_access_key_id $accessKey --profile $sessionProfile".!
s"aws configure set aws_secret_access_key $secretKey --profile $sessionProfile".!
s"aws configure set aws_session_token $sessionToken --profile $sessionProfile".!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment