skip to Main Content

I’m using aws sso login, but I can’t found out how to discover if I’m already logged in or if I need to login again, the only way I found to do that is to run a command I know I have permission and check that no errors happen.

aws sso logout
aws sqs list-queues # error
aws sso login # brower accept
aws sqs list-queues # success

My goal with that is to automate some scripts and only ask for login if needed.

2

Answers


  1. You can check for the sts caller identity call

    Returns details about the IAM user or role whose credentials are used to call the operation.

    https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html

    #!/bin/bash
    
    SSO_ACCOUNT=$(aws sts get-caller-identity --query "Account" --profile sso)
    #you can add a better check, but this is just an idea for quick check
    if [ ${#SSO_ACCOUNT} -eq 14 ];  then 
    echo "session still valid" ;
    else 
    echo "Seems like session expired"
    # performed login here
    fi
    

    If the session is still valid, it will return

    {
        "UserId": "AIDASAMPLEUSERID",
        "Account": "123456789012",
        "Arn": "arn:aws:iam::123456789012:user/DevAdmin"
    }
    

    If the session is not valid, it will return

    
    The SSO session associated with this profile has expired or is otherwise invalid. To refresh this SSO session run aws sso login with the corresponding profile.
    

    Or you can use this utility which is designed for this purpose

    https://github.com/benkehoe/aws-sso-util

    Login or Signup to reply.
  2. I ran into the same issue recently, but opted for a solution using exit codes:

    aws sts get-caller-identity &> /dev/null
    EXIT_CODE="$?"  # $? is the exit code of the last statement
    if [ $EXIT_CODE == 0 ]; then
        # auth is valid
    else
        # auth needs refresh
    fi
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search