Skip to content

Instantly share code, notes, and snippets.

@Donnie
Last active August 3, 2022 08:52
Show Gist options
  • Save Donnie/be8c5ea7487b3c817b4fc0069ae7075e to your computer and use it in GitHub Desktop.
Save Donnie/be8c5ea7487b3c817b4fc0069ae7075e to your computer and use it in GitHub Desktop.
AWS MFA Automation through 1Password

Requirements

  1. 1password OP CLI
  2. AWS CLI
  3. JQ

Setup

  1. Setup your AWS account on 1password with TOTP 1password
  2. Configure AWS locally awsprofile
  3. Note caltechprod matches both the AWS profile and the 1password item name above
  4. Add this function to the end of your .bashrc file
# Custom AWS Login

awsmfa() {
    op vault ls &> /dev/null
    if ! [ $? -eq 0 ]; then
        eval $(op signin)
    fi
    unset "${!AWS@}"
    export AWS_PROFILE=$1
    export AWS_OP_ITEM_ID=$(op item ls --format json | jq --arg AWS_PROFILE "$AWS_PROFILE" '.[] | select(.title | match($AWS_PROFILE)) | .id' -r | head -n 1)
    export AWS_USERNAME=$(op item get $AWS_OP_ITEM_ID --fields label="username")
    export AWS_ACCOUNT=$(op item get $AWS_OP_ITEM_ID --fields label="AWS Account")
    export AWS_ROLE_ARN=arn:aws:iam::$AWS_ACCOUNT:mfa/$AWS_USERNAME
    export AWS_TOTP=$(op item get $AWS_OP_ITEM_ID --otp)

    aws sts get-session-token --serial-number $AWS_ROLE_ARN --token-code $AWS_TOTP > /tmp/irp-cred.txt
    if ! [ $? -eq 0 ]; then
        echo "Error during AWS Login"
        return
    fi
    export AWS_ACCESS_KEY_ID="$(cat /tmp/irp-cred.txt | jq -r ".Credentials.AccessKeyId")"
    export AWS_SECRET_ACCESS_KEY="$(cat /tmp/irp-cred.txt | jq -r ".Credentials.SecretAccessKey")"
    export AWS_SESSION_TOKEN="$(cat /tmp/irp-cred.txt | jq -r ".Credentials.SessionToken")"
    echo "Logged into AWS with MFA"
    aws sts get-caller-identity
    rm /tmp/irp-cred.txt
}

Usage

Run awsmfa <YOUR_PROFILE> to get logged in with MFA

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