'Why does `aws sts assume-role` only work on second try?

Any idea why would assuming role, via AWS STS, only work on a 2nd try? (3rd call etc. also succeed.) Maybe a better question would be: how can one have STS automatically refresh the AWS_SESSION_TOKEN without having to call assume-role the 2nd time? (Related: How to renew token in sts)

My workflow: open a new Zsh terminal and call Oh-My-Zsh AWS plugin's asp <my_profile> function which sets AWS_PROFILE to <my_profile>.

Then do the 1st STS call:

aws sts assume-role --duration-seconds 43200 --role-arn "arn:aws:iam::${ACCOUNT_ID}:role/${ROLE_NAME}" --role-session-name abc

which errors:

An error occurred (ExpiredToken) when calling the AssumeRole operation: The security token included in the request is expired

Then repeat the same call, verbatim, which always succeeds.

Occasionally, I also see it error out as if the maximum allowed duration is 1 hour, but then a 2nd call again succeeds. Even though AWS Session Manager does have allowed maximum token duration set to 12 h (or 43200 s).

I'm using

> aws --version
aws-cli/2.2.43 Python/3.8.8 Darwin/20.6.0 exe/x86_64 prompt/off
> zsh --version
zsh 5.8 (x86_64-apple-darwin20.0)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source