Hidden

AWS Credentials: Configuration, Security, and Best Practices

Learn how AWS credentials authenticate requests, how CLI and SDK credential providers work, and how to use IAM roles, temporary credentials, Identity Center, and secure rotation practices.

AWS credentials are authentication material used by a person, application, or workload to make requests to AWS. They help AWS identify the requester and evaluate whether the requested action is allowed.

Authentication and authorization

Authentication answers, “Who is making this request?” Credentials identify an IAM user, IAM role session, federated user, or another supported principal.

Authorization answers, “What may this identity do?” AWS evaluates identity-based IAM policies and, where applicable, resource policies, permissions boundaries, AWS Organizations service control policies, and session policies. A valid credential does not automatically grant permission.

  1. A client obtains credentials from a supported source.
  2. The client signs an AWS API request.
  3. AWS authenticates the request and identifies the principal.
  4. AWS evaluates applicable policies and either permits or denies the action.

AWS credential types

Credential typeTypical use caseLifetimeContains session tokenPreferred usePrimary risks
Long-term access keysLegacy scripts or exceptional external integrationsUntil rotated, disabled, or deletedNoAvoid when a role or federation is availableExposure can provide continuing access
Temporary security credentialsRole sessions, Identity Center, and workload identityLimited session durationYesPreferred for people and workloadsExpired sessions or incomplete credential sets
Console passwordInteractive AWS Management Console loginUntil changed or disabledNot applicableUse with MFA and federationPassword theft and reuse
MFAAdditional factor for interactive login or sensitive operationsCode-based or device-basedNot applicableProtect privileged access and the root userLost devices or weak recovery controls

A long-term programmatic key contains an access key ID, which identifies the key, and a secret access key, which is used to sign requests. The secret must remain private.

Temporary credentials contain an access key ID, secret access key, and session token. The session token is required in addition to the key pair. Temporary credentials are issued by AWS Security Token Service (STS), often through the AssumeRole operation.

IAM identities and least privilege

Users, roles, root, and federation

  • An IAM user is a long-lived AWS identity that can have console credentials, access keys, or both.
  • An IAM role is an assumable identity. A role session receives temporary credentials and uses the role’s permissions.
  • The root user represents the entire AWS account. Protect it with MFA, avoid using it for daily API or console work, and do not create root access keys.
  • A federated identity is a workforce or external identity that obtains AWS access through a federation system rather than a permanent IAM user.

For human access, prefer federation or IAM Identity Center. For applications, prefer IAM roles and workload identity. Avoid creating long-lived IAM user keys for software that runs on AWS.

Least privilege

Least privilege means granting only the actions and resources required for a task. Start with a narrow policy, use conditions where appropriate, separate development and production access, and review permissions regularly. Remove unused users, roles, groups, keys, and policy statements.

AWS CLI credential configuration

Shared files and profiles

The AWS CLI commonly uses two local files:

  • The shared credentials file is typically ~/.aws/credentials and commonly stores access keys under profiles.
  • The shared configuration file is typically ~/.aws/config and stores regions, output formats, role settings, SSO settings, and other profile configuration.

The default profile is used when no other profile is selected. A named profile is a separate labeled configuration context, such as development, staging, or production.

ItemTypical location or mechanismPurposeExample settings
Default credentials profile~/.aws/credentialsDefault access key source[default] with key fields
Named credentials profile~/.aws/credentialsSeparate access credentials[development]
Shared configuration~/.aws/configRegion, output, roles, and SSO[profile development], region = us-east-1
Environment selectionAWS_PROFILE, command flagsChoose a profile for a process or command--profile development

Configure a default profile

Run the interactive command and enter the requested values. Do not paste credentials into source code.

aws configure

For a named profile, use the profile option with the command or configure the corresponding profile explicitly. Select a profile for one command with:

aws s3 ls --profile development

Or select a profile for the current shell and its child processes:

export AWS_PROFILE='development'

Regions, output, and role profiles

Configuration can associate a region and output format with a profile. A role-based profile can use a source profile for its initial credentials:

[profile audit]
role_arn = arn:aws:iam::123456789012:role/AuditRole
source_profile = engineering
region = us-east-1

When this profile is selected, the CLI uses the source profile to request a session for the target role. The target role’s trust policy must allow the source principal, and the source identity must be allowed to call sts:AssumeRole.

Practical CLI provider selection

At a practical level, the CLI searches supported credential providers in an ordered process. Explicit command or application settings, environment variables, profile configuration, SSO or external-process providers, and AWS-hosted metadata providers can affect the result. The exact order can vary by provider and CLI version, so inspect the resolved configuration rather than guessing.

aws configure list
aws configure list-profiles

AWS SDK credential resolution

AWS SDKs generally use a default credential provider chain: an ordered set of sources from which the SDK tries to obtain usable credentials. Common sources include:

  • Explicit credentials or a credential provider supplied by application configuration.
  • Environment variables.
  • The shared credentials and shared configuration files.
  • Web identity tokens, commonly used by Kubernetes workloads.
  • Container credentials supplied to ECS tasks or other supported container environments.
  • EC2 instance metadata credentials.
  • External process providers, IAM Identity Center, or other SDK-supported federation providers.

Applications should normally let the SDK obtain credentials from the workload role when running on AWS. Embedding access keys in source code, configuration files, container images, or deployment manifests creates unnecessary exposure and makes rotation difficult.

Environment variable credentials

Common variables include:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN for temporary credentials
  • AWS_PROFILE to select a named profile
  • AWS_REGION to select a default region
export AWS_ACCESS_KEY_ID='…'
export AWS_SECRET_ACCESS_KEY='…'
export AWS_SESSION_TOKEN='…'
export AWS_REGION='us-east-1'

Environment variables are useful for a short-lived local shell and many CI jobs, especially when the values are injected temporarily by a trusted secret provider. They can leak through command logs, process inspection, inherited subprocess environments, debugging output, or unsafe shell history practices. Never print them for troubleshooting.

Temporary credentials and role assumption

AWS STS issues temporary security credentials for a limited session. A role assumption has two distinct policy concerns:

  • The role’s trust policy says which principals may assume the role and under what conditions.
  • The role’s permissions policies say what the role session may do after assumption.

A controlled command-line example is:

aws sts assume-role \
  --role-arn arn:aws:iam::123456789012:role/ReadOnlyRole \
  --role-session-name training-session

A session name helps identify activity in audit records. Sensitive cross-account roles may require MFA. Third-party role assumption may require an external ID to reduce confused-deputy risk. Role chaining occurs when temporary credentials are used to assume another role; chained sessions have additional duration constraints, so avoid unnecessary chains.

Temporary credentials expire. CLI and SDK providers may refresh them automatically when the provider supports refresh, but a manually exported credential set does not renew itself. Applications should use a provider that manages refresh rather than copying temporary values into long-lived configuration.

IAM Identity Center and SSO

IAM Identity Center provides workforce access to selected AWS accounts and roles. It is generally preferable to distributing long-lived IAM user keys to administrators and developers.

Configure an SSO profile, then sign in:

aws configure sso
aws sso login --profile engineering

The profile records the Identity Center session and the account and role selection. Use that profile for commands:

aws sts get-caller-identity --profile engineering

The CLI obtains short-lived credentials for the selected account and role. If the login session expires, sign in again. SDK support for Identity Center profiles depends on the SDK and version, so use a supported provider and avoid converting the session into permanent keys.

Credentials for AWS compute workloads

RuntimeRecommended identity mechanismHow credentials are deliveredAvoid
EC2IAM role attached through an instance profileTemporary credentials from the instance metadata serviceAccess keys in user data, images, or application files
ECSECS task roleTask-specific container credential endpointConfusing the task role with the execution role
LambdaLambda execution roleRuntime credential providerStatic keys in environment variables or deployment packages
EKSIAM roles for service accounts or EKS Pod IdentityWeb identity or pod identity provider and temporary credentialsKeys in Kubernetes Secrets or manifests when role identity is available

An EC2 instance profile associates a role with an instance. ECS distinguishes the task role, which grants the application permissions, from the task execution role, which lets the ECS agent perform actions such as pulling images or sending logs. Lambda uses an execution role for function calls. EKS workloads can obtain role credentials through a web identity token or EKS Pod Identity.

These mechanisms provide workload-specific, temporary credentials that the platform can refresh. Remove local environment variables and mounted credential files that could override the intended workload provider.

Credential storage and file permissions

Typical local locations are ~/.aws/credentials and ~/.aws/config. On a multi-user machine, restrict the credentials file so only the intended operating-system user can read it. Also protect backups, shell profiles, terminal recordings, and editor history.

  • Never commit credentials to source control.
  • Do not place secrets in documentation, tickets, container images, build artifacts, or logs.
  • Use a CI/CD secret store for unavoidable external secrets and limit which jobs can read them.
  • Use a managed service such as Secrets Manager or Systems Manager Parameter Store when an application genuinely needs a stored secret.
  • Prefer roles, federation, and short-lived credentials over storing access keys at all.

Rotation, revocation, and incident response

For a key that is still needed, create a replacement, update every consumer, test it, deactivate the old key, monitor for failures, and delete the old key after confirming it is unused. Deactivation before deletion provides a safer rollback point.

If a key is exposed:

  1. Immediately deactivate or revoke it.
  2. Determine which identity and permissions were associated with it.
  3. Investigate CloudTrail and relevant detection findings for unexpected activity.
  4. Replace credentials only where they are still required, preferably with a role or managed secret.
  5. Remove the exposed value from repositories, logs, artifacts, tickets, and local files. Remember that editing the latest commit does not erase every copy from repository history or caches.
  6. Review and tighten permissions, trust policies, network controls, and monitoring.

Rotating a key does not remove permissions granted to its IAM user or role. Permissions must be changed separately. Useful controls include CloudTrail, IAM Access Analyzer, IAM credential reports, and appropriate AWS security detection services.

Verification and diagnostics

Before a sensitive operation, verify the active principal:

aws sts get-caller-identity

With a named profile:

aws sts get-caller-identity --profile development

Inspect which configuration sources the CLI resolved:

aws configure list
aws configure list-profiles

Use verbose debugging only when necessary:

aws sts get-caller-identity --debug
Symptom or errorLikely causeHow to verifyResolution
Unable to locate credentialsNo provider has credentials, the wrong profile is selected, or a workload role is unavailableRun aws configure list and verify caller identitySelect the intended profile, fix the provider, or attach and enable the workload role
Invalid security tokenMismatched keys, missing session token, or disabled/replaced credentialsCheck that all three temporary values came from one sessionRemove stale variables and obtain a complete valid credential set
ExpiredToken or expired SSO sessionTemporary credentials or Identity Center login expiredCheck the session source and expirationLog in again or use a provider that refreshes automatically
AccessDeniedMissing allow, explicit deny, SCP, boundary, session policy, resource policy, or wrong principalConfirm caller identity and evaluate all policy layersGrant only the narrowly required permission or remove the applicable block
AssumeRole authorization or trust errorMissing sts:AssumeRole, failed trust policy, external ID, MFA, or session conditionReview source permissions and target trust policyCorrect both sides of the role relationship and required conditions
Wrong region or endpointConflicting profile and environment region settingsInspect resolved configurationSet the intended region explicitly and correct endpoint settings
Local keys override a workload roleEnvironment variables or mounted shared files take precedenceInspect the process environment and mounted files without printing secretsRemove unnecessary static sources and verify the workload identity
Key exposed in a repository or logStatic secret stored in source, output, or debug dataReview access-key usage and audit eventsDeactivate or revoke, investigate, replace if necessary, purge exposure, and adopt role-based access

Security best-practices checklist

  • Protect the root user with MFA and do not use it for everyday API access.
  • Prefer federation, IAM Identity Center, and IAM roles over IAM users with long-lived access keys.
  • Use short-lived credentials and automatic refresh whenever possible.
  • Grant least privilege and review permissions regularly.
  • Separate human access from workload access and separate environments.
  • Never place secrets in repositories, images, documentation, tickets, logs, or build artifacts.
  • Use secret managers and CI/CD secret stores when external storage is unavoidable.
  • Monitor usage with CloudTrail and relevant IAM and security analysis tools.
  • Remove unused credentials and deactivate keys before deleting them.
  • Verify the caller identity and region before sensitive operations.

For a focused reference to the local credentials profile, see AWS shared credentials file.