Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if AWS CLI SSO is logged in

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.

like image 213
Cristiano Araujo Avatar asked Sep 03 '25 03:09

Cristiano Araujo


2 Answers

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
like image 58
treyhakanson Avatar answered Sep 04 '25 20:09

treyhakanson


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

like image 36
Adiii Avatar answered Sep 04 '25 19:09

Adiii