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

Thursday 14 March 2019

Auto host file generator

#!/bin/bash
set -xv
> /etc/ansible/file
echo '[server]' >/etc/ansible/file
serverlist=$(aws ec2 describe-instances --query "Reservations[*].Instances[*].Tags[?Key=='Name'].Value[]" --output text)
for server in $serverlist
do
s="${server}.srv.fish"
echo $s >> /etc/ansible/file
done

Tuesday 5 March 2019

AWS MFA Cli enabler

#!/bin/bash

read -e -p "Enter your MFA code...: " mfa

aws sts get-session-token --serial-number arn:aws:iam::018771201686:mfa/naveed --token-code $mfa --output table > todaysession

export AWS_ACCESS_KEY_ID=$(grep "AccessKeyId" todaysession | awk '{print $4}')
export AWS_SECRET_ACCESS_KEY=$(grep "SecretAccessKey" todaysession | awk '{print $3}')
export AWS_SESSION_TOKEN=$(grep "SessionToken" todaysession | awk '{print $4}' | sed 1d)

echo $AWS_ACCESS_KEY_ID
echo $AWS_SECRET_ACCESS_KEY
echo $AWS_SESSION_TOKEN