How to check if AWS CLI SSO is logged in

Viewed 569

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.

1 Answers

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

Related