Thu Nov 28 2024

How to Verify AWS CLI Credentials and Identify the User

When working with AWS Command Line Interface (CLI), it’s crucial to ensure that your credentials are valid and correctly pointing to the intended AWS account. Whether you’re deploying applications or performing routine administrative tasks, knowing which credentials you’re using and verifying their validity can prevent unexpected errors. Thankfully, AWS provides a straightforward solution for this.

Verifying Credentials Using AWS CLI

The aws sts get-caller-identity command is your best friend for checking the validity of your AWS credentials. This command doesn’t require specific IAM permissions and will work as long as the credentials are correct.

Here’s a command you can run to verify your credentials:

aws sts get-caller-identity

When you execute this command, it returns a JSON object that details the AWS Account ID, the User ID, and the ARN (Amazon Resource Name) associated with the credentials. Here’s what a successful response looks like:

{
  "Account": "123456789012",
  "UserId": "AR#####:#####",
  "Arn": "arn:aws:sts::123456789012:assumed-role/role-name/role-session-name"
}

The ARN format will vary depending on the type of credentials you are using, such as an IAM user or an assumed role. For more details on ARN formats, you can refer to the AWS ARN documentation.

Handling Errors with AWS CLI

The AWS CLI uses standard error codes to indicate the outcome of a command. A success response will have a 0 exit code, while an error such as invalid credentials will return a 255 code. If you encounter errors like:

An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid.

This might indicate that the default region for your AWS configuration is not enabled in your account. In such cases, you can specify a default region that is generally available, like us-east-1:

aws sts get-caller-identity --region us-east-1

This workaround usually resolves issues related to region-specific configurations.

Additional Resources

With this command, you can effectively perform a sanity check on your AWS credentials, ensuring that your deployments and operations proceed without credential-related interruptions.