Lots of people use aws s3 ls
to check that they have valid credentials.
If it succeeds, they assume they are good to go.
Even AWS blog tutorials often use it.
They're all wrong.
There's multiple things wrong with using aws s3 ls
to check credential validity.
The first is that it has an IAM permission, s3:ListAllMyBuckets
, associated with it.
If you don't have that permission, the operation will fail.
The second thing is that it can tell you if the credentials are valid, but not that they are the credentials you intend to be using.
You might notice if the S3 buckets that are listed (presuming there are S3 buckets in the account to list) are not the ones you expect, and you're paying attention for that.
There's a better way.
There's an API, STS.GetCallerIdentity
, that exists specifically to tell you about the credentials you're using.
It's useful on the command line, aws sts get-caller-identity
, as well as within programs using the SDKs.
It checks credential validity, tells you what account and IAM principal you're using, and importantly doesn't have an IAM action associated with it, which means it will always work.
$ aws sts get-caller-identity
UserId: AIDASAMPLEUSERID"
Account: "123456789012"
Arn: arn:aws:iam::123456789012:user/DevAdmin
You can even set up a command alias for it to use it as aws whoami
.
For an even better experience, try aws-whoami
, which parses and formats the output of GetCallerIdentity
for easier reading, and retrieves the account name using IAM.ListAccountAliases
.
You can set aws whoami
as an alias for it too.
Old habits are hard to change.
So slap a Service Control Policy on your Organization that denies s3:ListAllMyBuckets
only when being invoked by the CLI as aws s3 ls
.
That's the IAM policy below.
Calls using SDKs will still work, and even with the CLI, aws s3api list-buckets
can be used where needed.