Thursday, 28 March 2019

MFA CLI AWS Profile based

#!/bin/bash

KEY_PROFILE="main"
EXPIRATION=$(aws configure get expiration --profile $KEY_PROFILE)

RELOAD="true"
if [ -n "$EXPIRATION" ];
then
      # get current time and expiry time in seconds since 1-1-1970
      NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

      # if tokens are set and have not expired yet
      if [[ "$EXPIRATION" > "$NOW" ]];
      then
              echo "Will not fetch new credentials. They expire at (UTC) $EXPIRATION"
              RELOAD="false"
      fi
fi

if [ "$RELOAD" = "true" ];
then
      echo "Need to fetch new STS credentials"
      MFA_SERIAL=$(aws configure get mfa_serial --profile $KEY_PROFILE)
      DURATION=$(aws configure get get_session_token_duration_seconds --profile $KEY_PROFILE)
      read -p "Token for MFA Device ($MFA_SERIAL): " TOKEN_CODE

      read -r AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN EXPIRATION < <(aws sts get-session-token --output text --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]' --serial-number $MFA_SERIAL --token-code $TOKEN_CODE --duration-seconds $DURATION --profile $KEY_PROFILE)

      aws configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY"
      aws configure set aws_session_token "$AWS_SESSION_TOKEN"
      aws configure set aws_access_key_id "$AWS_ACCESS_KEY_ID"
      aws configure set expiration "$EXPIRATION" --profile $KEY_PROFILE
fi

No comments:

Post a Comment