Public

AWS Credentials: Configuring and Managing Authentication for the AWS CLI and SDKs

Learn how AWS credentials, profiles, shared files, temporary roles, IAM Identity Center, and provider chains authenticate the AWS CLI and SDKs securely.

AWS credentials are authentication material or session information used to make signed requests to AWS APIs. They identify an IAM principal—such as a user, role, federated identity, or service—and allow AWS to evaluate what that principal is authorized to do.

Authentication answers “Who is making this request?” Authorization answers “What may that identity do?” Valid credentials prove an identity, but they do not automatically grant permission to every AWS service or resource.

Credential components

A long-term access key normally contains an access key ID and a secret access key. The access key ID is an identifier; the secret access key is confidential and must be protected like a password.

Temporary credentials issued by AWS STS commonly contain those two values plus a session token. The session token must accompany the access key ID and secret access key. Temporary credentials also have an expiration time. Expiration is provider metadata and is not normally stored as a standard field in the shared credentials file.

Credential mechanisms and recommended choices

Prefer short-lived, role-based credentials whenever possible. Long-lived IAM user keys are difficult to protect, can be copied, and remain usable until rotated or deactivated.

MechanismTypical environmentCredential lifetimeRecommended usePrimary security consideration
IAM user access keysLegacy local tools or systems that cannot use rolesLong-lived until rotated or deactivatedOnly when a temporary or federated option is unavailableSecret keys can be leaked and are not automatically short-lived
Assumed IAM role credentialsCross-account access, automation, and local role profilesTemporaryPreferred for delegated accessSource identity needs permission and the role trust policy must allow assumption
IAM Identity Center credentialsWorkforce users using browser-based sign-inShort-lived and refreshed through sign-inPreferred for human CLI and SDK accessProtect the local session and use appropriate permission sets
EC2 instance-profile credentialsApplications running on EC2Temporary and provider-managedPreferred for EC2 workloadsRestrict the attached role and prevent unintended metadata access
ECS/container task-role credentialsApplications running in supported container servicesTemporary and provider-managedPreferred for container workloadsAssign only the permissions required by each task
Web identity federationKubernetes, mobile, and external identity workflowsTemporaryUse an external identity token to assume a roleValidate token subjects, audiences, and role trust conditions

Do not create or use root-account access keys for routine work. Protect the root account with strong authentication and reserve it for tasks that specifically require root access.

Local credential and configuration files

The shared credentials file normally stores access-key fields at ~/.aws/credentials. The config file normally stores regions, output preferences, and advanced profile settings at ~/.aws/config. The tilde represents the current user’s home directory. On Windows, the home directory is resolved from the user profile, commonly resulting in a path under %USERPROFILE%\.aws\.

The AWS CLI uses these conventions, and many SDKs support them, but file support and provider precedence can vary by SDK and version. Check the documentation for the exact tool in use.

You can select alternate locations with AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE:

export AWS_SHARED_CREDENTIALS_FILE="$HOME/.config/aws/credentials"
export AWS_CONFIG_FILE="$HOME/.config/aws/config"
FileDefault locationTypical settingsProfile section syntaxSecret-storage guidance
Shared credentials file~/.aws/credentialsaws_access_key_id, aws_secret_access_key, and sometimes aws_session_token[default] or [development]Keep private, restrict permissions, and never commit it
Config file~/.aws/configregion, output, role settings, SSO settings, and provider instructions[default] or [profile development] for non-default profilesIt may contain non-secret settings, but protect it if it contains sensitive metadata

Credentials file format

Both files use INI-style sections. The default profile is named default; other sections are named profiles.

[default]
aws_access_key_id = EXAMPLEACCESSKEY
aws_secret_access_key = EXAMPLESECRETKEY

[development]
aws_access_key_id = EXAMPLEDEVACCESSKEY
aws_secret_access_key = EXAMPLEDEVSECRETKEY

[temporary-session]
aws_access_key_id = EXAMPLETEMPACCESSKEY
aws_secret_access_key = EXAMPLETEMPSECRETKEY
aws_session_token = EXAMPLESESSIONTOKEN

The final profile illustrates temporary credentials. Its session token must match the access key and secret key issued for the same session. Do not add real secrets to examples, tickets, screenshots, logs, or shared locations. Avoid placing comments or unrelated data beside secrets where the file could be copied or exposed.

Configuration file and profile settings

A profile can combine credentials from the credentials file with settings from the config file. The config file uses [default] for the default profile and [profile NAME] for named profiles.

[default]
region = us-east-1
output = json

[profile development]
region = us-west-2
output = json

[profile audit]
role_arn = arn:aws:iam::123456789012:role/AuditReadOnly
source_profile = development
role_session_name = local-audit

region supplies a default AWS Region and output controls common CLI formats such as json, text, or table. A role profile uses role_arn to identify the target role and source_profile to identify credentials used to call AWS STS. credential_source can instead tell a tool to use credentials supplied by an environment such as EC2 instance metadata or a container. role_session_name gives the temporary session a recognizable name.

Web identity profiles exchange a web identity token for temporary role credentials. IAM Identity Center profiles describe an organization’s start URL, Region, account, role or permission-set selection, and cached sign-in session. These mechanisms avoid embedding long-lived keys in application code.

Credential provider chain

A credential provider chain is the ordered set of sources a CLI or SDK checks for usable credentials. Common inputs include explicit application settings, command options, environment credential variables, shared files, IAM Identity Center sessions, role assumption, container credentials, and EC2 instance metadata. Exact precedence differs between tools and SDK versions, so verify it for your environment.

SourceRelevant variable or settingWhen it is usefulFrequent issue
Command-line profile selection--profile NAMEOne command needs a specific identityA misspelled or nonexistent profile
Profile environment selectionAWS_PROFILELocal shell sessions and scriptsIt silently selects an unexpected profile
Environment credentialsAWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKENCI systems and controlled processesStale values override file-based credentials
Shared credentials fileAWS_SHARED_CREDENTIALS_FILELocal static or temporary profile valuesWrong path or missing session token
Config fileAWS_CONFIG_FILE, profile settingsRegions, roles, SSO, and provider instructionsIncorrect non-default profile syntax
IAM Identity Center cached sessionSSO profile and local login cacheWorkforce accessSession expired or wrong account and permission set selected
Container credential endpointProvider-managed container environmentECS and supported container workloadsTask role or endpoint is unavailable
EC2 instance metadataInstance profile roleApplications running on EC2No role is attached or metadata access is blocked

Configure the AWS CLI

When long-term keys are genuinely necessary, configure a least-privilege, non-production identity interactively:

aws configure

The CLI prompts for an access key ID, secret access key, default Region, and output format. For a named profile, use:

aws configure --profile development

For organization-managed human access, prefer IAM Identity Center:

aws configure sso --profile workforce
aws sso login --profile workforce

The CLI stores or uses a cached short-lived session and can request a renewed sign-in when the session is no longer valid. Do not put credentials directly in source code merely to set a Region; configure the Region in a profile or through an environment variable.

Select profiles and Regions

Without an explicit selection, tools generally use the default profile. Select a profile for one CLI invocation with:

aws sts get-caller-identity --profile development

Select a profile for a shell session with:

export AWS_PROFILE=development
export AWS_DEFAULT_REGION=us-west-2

A command-specific Region can take precedence over profile defaults:

aws ec2 describe-instances --profile development --region us-west-2

Separate profiles help prevent accidental work in the wrong account. Useful names distinguish personal, development, test, production, audit, and cross-account access.

Assume a role across accounts

Role assumption connects four elements: a source identity, permission to call sts:AssumeRole, a target role trust policy that permits that source, and the target role’s permissions policy. AWS STS then issues a temporary session.

[profile audit]
role_arn = arn:aws:iam::123456789012:role/AuditReadOnly
source_profile = development
role_session_name = local-audit

The source profile supplies the initial credentials. The target role’s trust policy must trust that source principal, and the source identity must be allowed to call AssumeRole. The resulting permissions are those granted to the target role, subject to applicable boundaries, session policies, resource policies, and organization controls.

aws sts get-caller-identity --profile audit

Temporary credentials expire by design. Role-capable providers can refresh them when supported. For local sessions, renew the source login or rerun the approved authentication workflow. Long-running processes may need restarting if they retained stale credentials.

Use IAM Identity Center locally

  1. Run aws configure sso --profile workforce and provide the organization’s requested sign-in details.
  2. Run aws sso login --profile workforce and complete browser authentication.
  3. Use the named profile for commands and SDK processes.
aws sts get-caller-identity --profile workforce

The selected account and permission set determine the resulting principal and permissions. A renewed sign-in may be required after the cached session expires.

Use credentials in applications without hardcoding

SDKs commonly provide a default credential provider chain. The following Python example uses Boto3’s standard session behavior; it does not assign key values in application code.

import boto3

session = boto3.Session()
sts = session.client("sts")
identity = sts.get_caller_identity()
print(identity["Account"], identity["Arn"])

During local development, choose the intended profile without changing the program:

export AWS_PROFILE=development
python verify_identity.py

After deployment, attach an IAM role to the workload—such as an EC2 instance profile or container task role—and let the SDK obtain temporary credentials from its environment. Use a secret-management mechanism for application secrets that are not identity credentials; do not embed access keys in source, client-side applications, or packaged binaries.

Validate the active identity

Always confirm the account and principal before destructive or production operations:

$ aws sts get-caller-identity --profile audit
{
    "UserId": "AROAEXAMPLE:local-audit",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/AuditReadOnly/local-audit"
}

$ aws configure list --profile audit
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                    audit              manual  --profile
access_key     ****************EXAMPLE shared-credentials-file
    region                us-west-2              config-file

Account identifies the AWS account. An ARN containing assumed-role identifies a temporary role session; a user ARN identifies an IAM user. Expiration details may be available from the relevant provider or SDK, but are not normally a standard field in the shared credentials file. Configuration inspection should reveal sources and masked values, never secret key contents.

Security practices

  • Never commit credential files, access keys, session tokens, or generated secret-containing configuration to version control.
  • Use least privilege: grant only the permissions required for a defined task.
  • Separate identities for development, testing, production, auditing, and automation.
  • Rotate, deactivate, and remove unused long-term access keys through the approved access process.
  • Protect local files with operating-system permissions and keep backups from exposing secrets.
  • Do not place secrets in shell history, screenshots, support tickets, logs, or chat messages.
  • Use workload identity and secret-management services for deployed applications.
  • If a key may have leaked, stop using it, deactivate or revoke it, investigate use, and replace it through your organization’s incident process.

Troubleshooting workflow

Use this order: identify the selected profile, inspect effective configuration and source locations, check credential-related environment variables, verify the caller identity, then review permissions, role trust, and Region settings. Never print or share secret values.

SymptomLikely causeSafe verification stepTypical resolution
Unable to locate credentialsNo usable profile, wrong home or alternate file path, missing profile, or no workload roleCheck the profile name and run aws configure list; confirm effective file locations without reading secrets aloudConfigure the intended profile, sign in with Identity Center, correct alternate-path variables, or attach a workload role
Invalid security tokenMismatched key pair, missing session token, revoked values, or environment overrideInspect the selected source, check credential-related environment variables, and run caller identityReplace credentials through the approved process, include the matching session token, or remove unintended overrides
ExpiredToken or token-expiration errorSTS, assumed-role, federated, or Identity Center session expiredConfirm the identity is temporary and inspect provider expiration information where availableRenew the login or credential workflow; use an auto-refreshing role provider; restart stale processes
AccessDeniedMissing permission, explicit deny, boundary, session policy, SCP, resource policy, or failed role trustRun caller identity and identify the action, resource, and target account; review policy layers and trustGrant the minimum required permission or correct the trust relationship
Wrong account or roleUnexpected AWS_PROFILE, environment credentials, or accidental default-profile useRun caller identity, configure-list, and inspect profile and credential environment variablesUse an explicit profile, unset unintended variables, and adopt clear account-specific names
Failure in one Region onlyIncorrect profile Region, resource exists elsewhere, or endpoint mismatchCheck command Region, AWS_REGION, AWS_DEFAULT_REGION, and profile RegionSet the correct Region explicitly or update the appropriate profile

Authentication versus authorization errors

A missing-credentials, invalid-token, or expired-token error usually means AWS cannot authenticate the request. An AccessDenied response usually means authentication succeeded, but the principal is not authorized for the requested action or resource. Confirm the exact principal first; otherwise, it is easy to grant permissions to the wrong identity.

Exam-relevant notes

  • Access key IDs identify keys; secret access keys sign requests and must remain confidential.
  • Temporary credentials require a session token and expire.
  • IAM roles provide temporary credentials and are preferred over long-lived keys for workloads and delegated access.
  • An instance profile supplies a role to EC2; a task role supplies credentials to supported containers.
  • source_profile identifies credentials used to assume a role; role_arn identifies the target role.
  • Authentication proves identity; authorization evaluates permissions.
  • The exact provider-chain order depends on the CLI or SDK and its version.

For continued study, see AWS credentials and profiles.