AWS CLI v2 with SSO profiles
Configure the AWS CLI v2 to sign in through IAM Identity Center, use named profiles safely, shape output with --query, page through results and prove that no long-lived access keys exist on your PC.
Assumes: AWS CLI v2 (2.32 or later) ยท Windows PowerShell 5.1 / PowerShell 7 ยท AWS Toolkit for Visual Studio ยท Region us-east-1. Verified against official sources on 2026-11-17.
Learning objectives
By the end of this lesson you can:
- Create an IAM Identity Center (SSO) profile with
aws configure sso, and read every line of thesso-sessionandprofilesections it writes to%USERPROFILE%\.aws\config. - Sign in and out with
aws sso login/aws sso logout, and explain where the CLI caches tokens and why that cache is sensitive. - Predict which credentials the CLI will use when several sources exist (command-line options, environment variables, SSO, credentials file and so on).
- Shape output with
--output(json, yaml, yaml-stream, text, table, off) and filter it with JMESPath--queryexpressions. - Control server-side pagination (
--max-items,--page-size,--starting-token) and the client-side pager (--no-cli-pager). - Prove, with a PowerShell script, that no long-lived access keys exist on your machine (Lab 1.2).
Prerequisites
- The Management Console and IAM fundamentals
- The Module 0 setup: an IAM Identity Center user with MFA and a
SandboxAdminpermission set on your sandbox account โ see Secure your AWS account - AWS CLI v2 installed (see Module 0). Check with
aws --version; this lesson assumes 2.32.0 or later, because that is the minimum foraws login
Why this matters in banking
Picture a Harbourline Bank developer who, years ago, created an IAM user called ci-deploy and pasted its access key into %USERPROFILE%\.aws\credentials "just to get the CLI working". The key never expires. It is copied into a backup, then into a laptop image, then into a screenshot attached to a support ticket. Eighteen months later someone finds it in a public repository and starts creating resources in the bank's account.
Every bank security standard you will meet says the same thing: no long-lived credentials for humans. The AWS CLI v2 makes that easy. You sign in through IAM Identity Center in a browser (with MFA), the CLI receives a short-lived token, and every command uses temporary role credentials that expire within hours. If a laptop is stolen, the attacker gets, at worst, a few hours of access through a cache that you can wipe with one command. Auditors can also tie every API call back to a named person rather than to a shared key.
The idea in plain language
The AWS CLI (command-line interface) is a program called aws that turns commands such as aws s3api list-buckets into signed HTTPS calls to AWS APIs. It needs two things for every call:
- Credentials โ proof of who you are. Ideally temporary: an access key ID, a secret key and a session token that expire.
- Configuration โ which Region to call, what output format you want, and which credentials to use.
Both live in profiles: named sections in the file %USERPROFILE%\.aws\config. A profile called learn-sandbox says "use the IAM Identity Center sign-in called cea, then take the SandboxAdmin role in account 111122223333, and default to us-east-1". You pick a profile with --profile learn-sandbox or the AWS_PROFILE environment variable.
An SSO session (the [sso-session cea] section) describes how to sign in: the URL of your AWS access portal and the Region where IAM Identity Center lives. Several profiles can share one SSO session, so you sign in once and then use a sandbox profile, a billing profile and a management profile without signing in three times.
Analogy: The SSO session is your bank staff pass, issued at reception after you show ID (password plus MFA). Each profile is a door you are allowed through โ "training branch, as administrator" or "finance office, read-only". The pass expires at the end of the day; the doors re-check it every time. An IAM access key, by contrast, is a metal key cut years ago that opens the door forever, for anyone who holds it.
What problem the AWS service solves
| Piece | What it is | Why it exists | Limitations and sharp edges |
|---|---|---|---|
| AWS CLI v2 | A single aws executable with commands for almost every AWS API | Scripting, automation, quick checks, and seeing the raw API without the console's opinions | Command names mirror API names, which are not always intuitive. Quoting rules differ between PowerShell, cmd and bash |
IAM Identity Center sign-in (aws sso login) | A browser-based OAuth 2.0 flow that returns an access token, cached locally | Removes long-lived keys; enforces MFA; ties actions to named users | The token expires (you sign in again daily); the cache folder is sensitive while it is valid |
| Named profiles | Sections in config that bundle account, role, Region and output | Switching between accounts and roles safely | A typo in a profile name silently falls back to nothing and fails; a stray [default] profile can surprise you |
aws login | Browser sign-in for the root user, IAM users or IAM federation, available from CLI 2.32.0 | Gives the Free plan path (no Identity Center access to accounts) short-lived credentials too | Not for Identity Center users โ use aws sso login instead. The IAM identity needs the SignInLocalDevelopmentAccess managed policy; credentials refresh for up to 12 hours |
--query (JMESPath) | A filter language applied to the JSON response before printing | Get exactly the fields you need, without jq | Filters client-side after download; it does not reduce what AWS returns or the API calls made |
Since CLI 2.22.0, aws sso login uses the PKCE (Proof Key for Code Exchange) authorization flow by default: the CLI opens a browser on the same machine and receives the result directly. If you work over SSH or on a machine without a browser, add --use-device-code to use the older device-code flow, where you type a short code into a browser on any device.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
az login (browser sign-in to Entra ID) | aws sso login --profile learn-sandbox | az login gives you a tenant-wide token; an AWS profile pins one account and one role. You switch account by switching profile |
az account set --subscription | --profile / $env:AWS_PROFILE | There is no "current subscription" stored globally; the profile is chosen per command or per shell |
~/.azure token cache | %USERPROFILE%\.aws\sso\cache (and \.aws\login\cache for aws login) | Same sensitivity: treat the folder like a password while tokens are valid |
az ... --query (JMESPath) and -o table | aws ... --query and --output table | Same JMESPath language. AWS adds yaml-stream and off, and applies --query per page in text output |
Azure PowerShell Connect-AzAccount | AWS Tools for PowerShell with the same profiles | Both AWS tools read %USERPROFILE%\.aws\config |
| Service principal secret in an environment variable | AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY | Equally dangerous. For pipelines AWS uses OIDC role assumption (Module 9) |
| Visual Studio "Azure Service Authentication" account | AWS Toolkit for Visual Studio credential profile | The Toolkit reads the same shared config file as the CLI |
Architecture
What happens between aws sso login and a successful aws s3api list-buckets:
Security-boundary view. Three things on your PC matter:
configโ no secrets, just URLs, account IDs and role names. Safe to show a colleague (but account IDs are still mildly sensitive; mask them in public).sso\cacheandcli\cacheโ tokens and temporary credentials. Sensitive until they expire.aws sso logoutdeletes them.credentialsโ should not exist in this course. If it does and containsaws_access_key_id, you have long-lived keys on disk.
Step-by-step implementation
Collect your Identity Center details
Sign in to your AWS access portal (the URL from Module 0, shaped like https://d-1234567890.awsapps.com/start). Note:
- the start URL;
- the Identity Center Region โ
us-east-1in this course; - your sandbox account ID (fictional in this lesson:
111122223333) and the role nameSandboxAdmin.
In the portal you can also expand an account and choose Access keys. The dialog shows "IAM Identity Center credentials" with the start URL and Region. Do not copy the temporary keys it offers โ you do not need them.
Run the wizard
aws configure ssoAnswer the prompts:
SSO session name (Recommended): cea
SSO start URL [None]: https://d-1234567890.awsapps.com/start
SSO region [None]: us-east-1
SSO registration scopes [None]: sso:account:accessThe browser opens. Sign in with your Identity Center user, complete MFA and allow the request (the client name starts with botocore-client-, which is the CLI's underlying Python library). Back in the terminal, choose the cea-sandbox account and the SandboxAdmin role, then:
Default client Region [None]: us-east-1
CLI default output format (json if not specified) [None]: json
Profile name [SandboxAdmin-111122223333]: learn-sandboxRead what it wrote
Open %USERPROFILE%\.aws\config in VS Code (code $env:USERPROFILE\.aws\config). You should see this shape; we have also added two more profiles by hand that reuse the same session:
[sso-session cea]
sso_start_url = https://d-1234567890.awsapps.com/start
sso_region = us-east-1
sso_registration_scopes = sso:account:access
[profile learn-sandbox]
sso_session = cea
sso_account_id = 111122223333
sso_role_name = SandboxAdmin
region = us-east-1
output = json
[profile learn-billing]
sso_session = cea
sso_account_id = 444455556666
sso_role_name = BillingViewer
region = us-east-1
output = table
[profile learn-management]
sso_session = cea
sso_account_id = 444455556666
sso_role_name = ManagementAdmin
region = us-east-1
output = jsonlearn-billing and learn-management point at the management account through the BillingViewer and ManagementAdmin permission sets you created in Module 0. If you named them differently there, use your names. We use learn-billing in Free Tier and billing.
Sign in and test
aws sso login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandboxExpected output (fictional IDs):
{
"UserId": "AROAEXAMPLEID123456789:alex.learner",
"Account": "111122223333",
"Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_SandboxAdmin_0123456789abcdef/alex.learner"
}The ARN tells you three things: it is an assumed role (temporary), the role was created by Identity Center (AWSReservedSSO_ prefix), and the session name is your user name, so CloudTrail records you, not a shared identity.
Because all three profiles share the cea session, aws sts get-caller-identity --profile learn-billing now works too, without another browser prompt.
Make the profile your shell default
# For this PowerShell window only
$env:AWS_PROFILE = 'learn-sandbox'
aws s3api list-buckets --query "Buckets[].Name"
# Show which profile, credentials and Region the CLI resolved, and from where
aws configure list
aws configure list-profilesAvoid setting AWS_PROFILE permanently with setx: a forgotten machine-wide default is how people run commands against the wrong account. Prefer an explicit --profile in scripts.
Connect the AWS Toolkit for Visual Studio
The Toolkit reads the same shared config file, so profiles created by the CLI appear in its credential list. In Visual Studio open View โ AWS Explorer, choose learn-sandbox in the Credentials drop-down and US East (N. Virginia) as the Region. The Toolkit opens the browser for Identity Center sign-in when it needs a fresh token. Profiles that use Identity Center cannot be edited inside the Toolkit's profile editor โ edit config in a text editor instead. Recognition of the newer sso_session profile style by your Toolkit version is โ VERIFY: if learn-sandbox does not appear, update the Toolkit, and check the Toolkit's IAM Identity Center credentials page.
Sign out when you finish
aws sso logoutThis deletes the cached Identity Center tokens and temporary credentials for all SSO profiles. The next command will fail until you run aws sso login again. That is the point.
AWS Console instructions
The CLI is configured on your PC, but two console pages help:
- AWS access portal โ your account โ Access keys: shows the start URL and the Identity Center Region you need for
aws configure sso. Ignore the temporary keys offered there. - IAM Identity Center โ Dashboard (management account): shows the AWS access portal URL and, under Settings โ Identity source, the Issuer URL. CLI 2.22.0 and later accept the issuer URL instead of the start URL.
- IAM Identity Center โ Permission sets โ SandboxAdmin: the session duration (4 hours in Module 0) caps how long each set of role credentials lasts. The CLI automatically fetches new role credentials while your Identity Center sign-in is still valid; when that expires you must sign in again.
You can also open CloudShell (the terminal icon in the console's top bar). It has the AWS CLI pre-installed and already signed in as your console identity โ handy when your PC is locked down, but its home directory persists, so do not store anything sensitive there.
AWS CLI
Which credentials win?
The CLI looks for settings in this order and uses the first source that provides them:
- Command-line options:
--profile,--region,--output - Environment variables:
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN,AWS_PROFILE,AWS_REGION, โฆ - Assume-role settings in the profile (
role_arn+source_profile) - Assume role with web identity (used in CI/CD and Kubernetes)
- IAM Identity Center settings in
config(sso_sessionโฆ) - The shared
credentialsfile - A custom
credential_process - The
configfile - Container credentials (ECS tasks)
- EC2 instance profile credentials
The trap in the middle box: if static keys sit in your environment, they can beat an AWS_PROFILE you set, while an explicit --profile on the command line takes precedence over environment keys (current CLI v2 behaviour โ VERIFY on your version โ aws configure list shows the winner in its TYPE column).
Inspecting configuration
# Which profile, keys (masked) and Region would be used, and where each came from
aws configure list --profile learn-sandbox
# All profile names in config and credentials
aws configure list-profiles
# Read one setting from a profile
aws configure get region --profile learn-sandbox
aws configure get sso_session --profile learn-sandbox
# Change one setting without editing the file
aws configure set output table --profile learn-billingFor an SSO profile after sign-in, aws configure list looks like this (the exact column layout varies by CLI version โ VERIFY; the important part is the TYPE sso):
NAME : VALUE : TYPE : LOCATION
profile : learn-sandbox : manual : --profile
access_key : ****************WXYZ : sso :
secret_key : ****************abcd : sso :
region : us-east-1 : config-file : ~/.aws/configIf TYPE says env or shared-credentials-file, something other than SSO is supplying credentials โ fix that before going further.
Signing in
# Sign in for every profile that shares the 'cea' session
aws sso login --sso-session cea
# Same, chosen through a profile
aws sso login --profile learn-sandbox
# No browser on this machine (SSH, locked-down VM): device-code flow
aws sso login --profile learn-sandbox --use-device-code
# Sign out of all SSO sessions and delete cached tokens and role credentials
aws sso logoutFree plan path (no Identity Center): with an IAM user that has a console password and MFA, use aws login instead (CLI 2.32.0+). It writes a profile with a login_session line and caches credentials in %USERPROFILE%\.aws\login\cache:
aws login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandbox
aws logout --profile learn-sandboxOutput formats
# json (default): best for scripts and ConvertFrom-Json
aws sts get-caller-identity --output json
# yaml: readable; yaml-stream: starts printing before a large list finishes
aws s3api list-buckets --output yaml
# text: tab-separated; always pair it with --query for stable columns
aws s3api list-buckets --query "Buckets[].[Name,CreationDate]" --output text
# table: for humans only
aws s3api list-buckets --query "Buckets[].{Name:Name,Created:CreationDate}" --output table
# off: no stdout at all; just check the exit code ($LASTEXITCODE)
aws s3api head-bucket --bucket hl-m01-hello-111122223333-a1b2c3 --output offJMESPath --query recipes
# Names only
aws s3api list-buckets --query "Buckets[].Name"
# Only this course's lab buckets (client-side filter)
aws s3api list-buckets --query "Buckets[?starts_with(Name, 'hl-')].Name" --output text
# Same result, but filtered by S3 on the server (fewer bytes over the wire)
aws s3api list-buckets --prefix hl- --query "Buckets[].Name" --output text
# Project and rename fields; sort by creation date
aws s3api list-buckets --query "sort_by(Buckets, &CreationDate)[].{Bucket:Name,Created:CreationDate}" --output table
# Count
aws s3api list-buckets --query "length(Buckets)"
# The account ID alone, ready for a variable
$account = aws sts get-caller-identity --query Account --output textPowerShell quoting tip: wrap the whole query in double quotes and use single quotes for JMESPath string literals, as above. Avoid JMESPath backtick literals in PowerShell, because the backtick is PowerShell's escape character.
Pagination and the pager
# The CLI follows pagination tokens automatically and prints everything.
# --max-items limits what is printed and returns a NextToken to continue.
aws s3api list-buckets --max-items 5
# Continue from where you stopped (paste the NextToken value)
aws s3api list-buckets --max-items 5 --starting-token eyJDb250aW51YXRpb25Ub2tlbiI6IG51bGx9
# --page-size changes how many items each API call fetches, not what you see.
# Use it when large calls time out.
aws s3api list-objects-v2 --bucket hl-m01-hello-111122223333-a1b2c3 --page-size 100
# Only the first page, one API call
aws s3api list-objects-v2 --bucket hl-m01-hello-111122223333-a1b2c3 --no-paginate
# Disable the 'more' pager on Windows for one command, or permanently in config
aws s3api list-buckets --no-cli-pager
aws configure set cli_pager "" --profile learn-sandboxHelpers that prevent mistakes
# Interactive prompting: fill in a command with suggestions (F3 shows help)
aws s3api --cli-auto-prompt
# Prompt only when a command is incomplete
aws configure set cli_auto_prompt on-partial --profile learn-sandbox
# See the request JSON a command accepts, without calling AWS
aws s3api put-bucket-tagging --generate-cli-skeleton
# Preview high-level S3 operations without performing them
aws s3 rm s3://hl-m01-hello-111122223333-a1b2c3/statements/ --recursive --dryrun
# EC2 can check permissions without acting: success shows as a DryRunOperation error
aws ec2 describe-instances --dry-runexport-credentials: useful, and dangerous
# Prints the CURRENT temporary credentials as PowerShell variable assignments
aws configure export-credentials --profile learn-sandbox --format powershellSome older tools only understand environment-variable keys. export-credentials resolves your SSO profile and prints the temporary keys in a format you choose (process, env, env-no-export, powershell, windows-cmd, fish). Those keys are real and valid until they expire: do not paste them into chat, tickets, screenshots or the AI assistant. A safer pattern is a profile that calls the CLI only when needed:
[profile legacy-tool]
credential_process = aws configure export-credentials --profile learn-sandbox --format process
region = us-east-1Infrastructure as Code
Not applicable: this lesson creates no AWS resources. Your "infrastructure" is the config file. A good team habit is to keep a template of it (start URL, session name, profile names, no secrets) in your learning repository so you can rebuild a new PC in minutes. Never commit anything from sso\cache, cli\cache, login\cache or a credentials file โ the lab's .gitignore already excludes .aws/ and credentials.
Complete code
This is Lab 1.2's proof script. It works in Windows PowerShell 5.1 and PowerShell 7. Save it as Test-NoStaticKeys.ps1 in your learning repository.
<#
.SYNOPSIS
Proves that no long-lived AWS access keys exist on this PC and that a profile uses short-lived sign-in.
.EXAMPLE
.\Test-NoStaticKeys.ps1 -ProfileName learn-sandbox
#>
[CmdletBinding()]
param(
[string]$ProfileName = 'learn-sandbox'
)
$problems = New-Object System.Collections.Generic.List[string]
$awsDir = Join-Path $env:USERPROFILE '.aws'
# 1. The shared credentials file must not contain static keys.
$credFile = $env:AWS_SHARED_CREDENTIALS_FILE
if (-not $credFile) { $credFile = Join-Path $awsDir 'credentials' }
if (Test-Path $credFile) {
$hits = Select-String -Path $credFile -Pattern '^\s*aws_access_key_id\s*='
if ($hits) {
$problems.Add("Static access key(s) in $credFile on line(s) $(($hits | ForEach-Object LineNumber) -join ', ')")
}
}
# 2. The config file can hold keys too; it must not.
$configFile = $env:AWS_CONFIG_FILE
if (-not $configFile) { $configFile = Join-Path $awsDir 'config' }
if (-not (Test-Path $configFile)) {
$problems.Add("No config file at $configFile. Run: aws configure sso")
} else {
$hits = Select-String -Path $configFile -Pattern '^\s*aws_(access_key_id|secret_access_key|session_token)\s*='
if ($hits) {
$problems.Add("Key material in $configFile on line(s) $(($hits | ForEach-Object LineNumber) -join ', ')")
}
}
# 3. No keys in environment variables, at any scope.
foreach ($name in 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN') {
foreach ($scope in 'Process', 'User', 'Machine') {
if ([Environment]::GetEnvironmentVariable($name, $scope)) {
$problems.Add("$name is set at $scope scope")
}
}
}
# 4. The profile must use Identity Center (sso_session) or console sign-in (login_session).
$ssoSession = aws configure get sso_session --profile $ProfileName 2>$null
$loginSession = aws configure get login_session --profile $ProfileName 2>$null
if (-not $ssoSession -and -not $loginSession) {
$problems.Add("Profile '$ProfileName' has neither sso_session nor login_session")
}
# 5. The credentials must work and must be a temporary role session for SSO profiles.
$arn = aws sts get-caller-identity --profile $ProfileName --query Arn --output text 2>$null
if ($LASTEXITCODE -ne 0 -or -not $arn) {
$problems.Add("STS call failed for '$ProfileName'. Run: aws sso login --profile $ProfileName")
} elseif ($ssoSession -and $arn -notmatch ':assumed-role/AWSReservedSSO_') {
$problems.Add("Caller $arn is not an IAM Identity Center role session")
}
# Report
Write-Host "Profile : $ProfileName"
Write-Host "Caller ARN : $arn"
if ($problems.Count -eq 0) {
Write-Host 'Result : PASS - no long-lived keys found; short-lived sign-in works' -ForegroundColor Green
exit 0
}
Write-Host 'Result : FAIL' -ForegroundColor Red
$problems | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
exit 1Run it:
aws sso login --profile learn-sandbox
powershell -ExecutionPolicy Bypass -File .\Test-NoStaticKeys.ps1 -ProfileName learn-sandboxCode explained line by line
[CmdletBinding()] param([string]$ProfileName = 'learn-sandbox')โ a script parameter with the course default. We avoid the name$Profilebecause PowerShell already uses$PROFILE(variable names are case-insensitive).New-Object System.Collections.Generic.List[string]โ a growable list of problems; works in PowerShell 5.1, unlike some newer syntax.$env:AWS_SHARED_CREDENTIALS_FILEfallback โ the CLI honours this variable, so the script checks the file the CLI would actually read.Select-String -Pattern '^\s*aws_access_key_id\s*='โ finds key lines, including indented ones, without printing the secret itself (we only report line numbers).- The second
Select-Stringchecksconfigforaws_access_key_id,aws_secret_access_keyandaws_session_token, because the CLI accepts keys in either file. [Environment]::GetEnvironmentVariable($name, $scope)โ checks the current process and the persistent user and machine scopes; asetxfrom two years ago would show up here.aws configure get sso_session --profile $ProfileName 2>$nullโ reads a single setting;2>$nullhides the "not set" message.login_sessioncovers the Free plan path withaws login.aws sts get-caller-identity ... --query Arn --output textโ proves the credentials work.GetCallerIdentityneeds no IAM permission, so failure means a sign-in or configuration problem, not a policy problem.$LASTEXITCODEโ the exit code of the last native command; non-zero means the CLI failed.-notmatch ':assumed-role/AWSReservedSSO_'โ Identity Center sessions always appear as assumed roles whose names start withAWSReservedSSO_.exit 0/exit 1โ lets you use the script in a pre-commit hook or CI check.
Security considerations
- No long-lived keys for humans. Use
aws sso login(oraws loginon the Free plan path). If you discover keys, deactivate and delete them in IAM, then delete the lines from disk. - The caches are secrets while valid.
%USERPROFILE%\.aws\sso\cache,\.aws\cli\cacheand\.aws\login\cachecontain tokens and temporary credentials. Exclude.awsfrom cloud-synced folders and backups you do not control; runaws sso logouton shared machines. - Pin profiles in scripts.
--profile learn-sandboxin every script line avoids "ran it against the wrong account". - Never paste
export-credentialsoutput into tickets, chat or AI tools. - MFA every sign-in, as configured in Module 0.
โ Learning shortcut โ not for production
Your learn-sandbox profile maps to SandboxAdmin (AdministratorAccess) with a 4-hour session. At a bank, developer profiles map to narrow permission sets per environment, production profiles are read-only by default, write access to production goes through a pipeline rather than a human CLI, and elevation is time-bound and approved. Also, on a corporate network the CLI usually needs the bank's proxy and custom CA bundle (HTTPS_PROXY, AWS_CA_BUNDLE) โ never "fix" TLS errors with --no-verify-ssl.
โ Learning shortcut โ not for production
One person here signs in to sandbox, billing and management profiles from the same laptop. In production, management-account access is restricted to a few named administrators, ideally from hardened admin workstations, and every session is logged and reviewed.
Banking use case
Harbourline Bank's platform team publishes a standard config template on its internal wiki. It contains one sso-session (harbourline) pointing at the bank's IAM Identity Center, which is federated to Entra ID, and a set of profiles: payments-dev (developer permission set), payments-test-ro (read-only), payments-prod-ro (read-only, 1-hour session) and data-dev. Nobody has a write profile for production; deployments run from pipelines using OIDC roles (Module 9). A pre-commit hook based on Test-NoStaticKeys.ps1 plus a secret scanner rejects commits that contain key-shaped strings. When an engineer leaves, HR disables the Entra ID account, and their CLI access ends at the next token refresh โ no key rotation exercise required. Whether this meets a particular regulatory expectation (for example access-review evidence for auditors) is for the bank's security and compliance teams to confirm.
Common mistakes
- Copying the temporary keys from the access portal into
credentialsโ it "works" for an hour โ then fails mysteriously, and the keys leak into backups. Useaws configure ssoonce. - Old keys in environment variables โ set years ago for another tool โ they override
AWS_PROFILEand you act as a different identity. Checkaws configure listandGet-ChildItem Env:AWS*. - A
[default]profile with keys โ older tutorials create one โ any command without--profileuses it. Delete it or make the default an SSO profile. - Wrong SSO Region โ entering your workload Region (
eu-west-2) instead of the Identity Center Region (us-east-1) โ sign-in fails.sso_regionis where Identity Center lives;regionis where your commands go. - Using
textoutput without--queryโ column order is alphabetical and can change โ scripts break. Always project the fields you need. - Trusting
--max-itemsto reduce cost or load โ it only limits what is printed; the CLI still pages through the API. Use server-side filters such as--prefixwhere they exist. - Leaving the pager on in scripts โ a script hangs waiting at
-- More --. Use--no-cli-pageror setcli_pagerto empty.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Error when retrieving token from sso: Token has expired and refresh failed | Identity Center sign-in expired | aws sso login --profile learn-sandbox |
The config profile (learn-sandbx) could not be found | Typo in --profile or AWS_PROFILE | aws configure list-profiles; fix the name |
Unable to locate credentials | No profile chosen and no default | Add --profile, or set $env:AWS_PROFILE |
InvalidClientTokenId or SignatureDoesNotMatch | Stale static keys in env vars or credentials override SSO | Remove-Item Env:AWS_ACCESS_KEY_ID, Env:AWS_SECRET_ACCESS_KEY, Env:AWS_SESSION_TOKEN; clean the files |
| Browser opens but shows an error about the request | Wrong sso_region or start URL | Compare with the access portal's Access keys dialog |
| Login hangs over SSH / remote desktop without a browser | PKCE needs a browser on the same machine | aws sso login --use-device-code |
AccessDenied ... explicit deny in a service control policy | Region guardrail from Module 0 | Use us-east-1 or eu-west-2 |
SSL: CERTIFICATE_VERIFY_FAILED on a corporate network | TLS-inspecting proxy with a private CA | Set AWS_CA_BUNDLE to the corporate CA file (ask IT); never use --no-verify-ssl |
Output stops at -- More -- | Windows more pager | --no-cli-pager or cli_pager = in config |
aws: error: argument --query: Bad value in PowerShell | Quoting: backticks or nested double quotes | Outer double quotes, inner single quotes |
aws login is "not a valid choice" | CLI older than 2.32.0 | Update the CLI (msiexec the latest MSI) |
Cost and cleanup
Cost: $0. IAM Identity Center, STS GetCallerIdentity and listing buckets are free; the CLI itself is free.
Cleanup at the end of each study session:
# Delete cached SSO tokens and role credentials for all SSO profiles
aws sso logout
# If you used the Free plan path
aws logout --all
# Clear any profile variable you set in this window
Remove-Item Env:AWS_PROFILE -ErrorAction SilentlyContinue
# Confirm nothing tagged Project=cea-lab exists (this lesson created nothing; the habit matters)
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --query "ResourceTagMappingList[].ResourceARN" --profile learn-sandboxExercises
- ๐ข Guided (Lab 1.2): Configure the
ceaSSO session and thelearn-sandboxprofile withaws configure sso. Addlearn-billingby hand. Connect the AWS Toolkit for Visual Studio tolearn-sandboxand open the S3 node in AWS Explorer. Then runTest-NoStaticKeys.ps1and getResult : PASS. - ๐ก Challenge: Write one CLI command (no PowerShell filtering) that prints a table of buckets whose names start with
hl-, with columnsBucketandCreated, sorted newest first. Then write a second command that prints only the count of such buckets as plain text. - ๐ด Live problem: A colleague says: "I ran
aws s3 lswithAWS_PROFILE=learn-sandboxand it listed buckets I've never seen, includingharbourline-legacy-reports.aws sts get-caller-identityshowsarn:aws:iam::999988887777:user/ci-deploy." Work out what happened, what risk it exposes, and what you would do in the next 30 minutes.
Assignment
Add a docs/cli-setup.md to your learning repository containing: your config template with fictional account IDs, a table of profiles and what each is for, the output of aws configure list --profile learn-sandbox with the keys masked, the Test-NoStaticKeys.ps1 script and a screenshot-free description of how you connected the Visual Studio Toolkit. Add .aws/ and credentials to .gitignore.
Solutions
aws configure sso writes the [sso-session cea] and [profile learn-sandbox] sections; adding learn-billing means copying the profile block and changing sso_account_id and sso_role_name. In Visual Studio, AWS Explorer lists learn-sandbox; if the Toolkit asks you to sign in, it opens the same Identity Center page. The script passes when credentials is absent or contains no aws_access_key_id, no AWS_* key variables exist at any scope, the profile has sso_session, and STS returns an assumed-role/AWSReservedSSO_... ARN. Why: each check closes one way that a long-lived key could silently be used instead of your SSO session.
aws s3api list-buckets --prefix hl- --query "reverse(sort_by(Buckets, &CreationDate))[].{Bucket:Name,Created:CreationDate}" --output table --profile learn-sandbox
aws s3api list-buckets --prefix hl- --query "length(Buckets)" --output text --profile learn-sandboxsort_by with &CreationDate sorts ascending; reverse flips it. The hash syntax {Bucket:Name,...} names the columns. --prefix makes S3 filter on the server. Why: server-side filtering returns less data, and naming fields makes the table self-explanatory. If --prefix returns nothing in your CLI version, use the client-side filter Buckets[?starts_with(Name, 'hl-')]. If no bucket matches, Buckets may be missing from the response โ the length call then errors; that is a reminder to handle empty results in scripts.
The ARN is an IAM user in a different account, so a long-lived access key is overriding the profile. The most likely cause is AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY in the environment (they beat AWS_PROFILE), or a [default] entry in credentials combined with a misspelt profile. Steps: run aws configure list (TYPE will show env or shared-credentials-file); Get-ChildItem Env:AWS*; check user and machine scopes. Remove the variables and the file entries. Then treat the key as exposed: report it to the owning team, which should deactivate it, review CloudTrail for its recent use, rotate whatever depended on it and replace it with a role. Do not delete it yourself in someone else's account. Why: a key you did not know about on your machine is a credential-leak incident until proven otherwise.
Knowledge check
Answer: sso_region (in the sso-session section) is the Region where IAM Identity Center is enabled and where sign-in happens. region (in the profile) is the default Region your AWS commands are sent to. They are often both us-east-1 in this course, but at a UK bank the workload Region might be eu-west-2 while Identity Center stays in its home Region.
Answer: Several profiles can share one sign-in, so one aws sso login serves them all, and the CLI can refresh the token automatically. The legacy style (start URL in every profile) cannot refresh tokens and duplicates settings.
Answer: Not necessarily. It limits how many items are printed and gives you a NextToken. --page-size controls items per API call, and --no-paginate stops after one call. Server-side filters such as --prefix reduce what AWS returns.
Answer: The credentials came from environment variables, not from your SSO profile. Unless you set them on purpose a moment ago, remove them.
Answer: It deletes cached Identity Center tokens and the temporary role credentials cached for SSO profiles. It does not change your config file, does not delete static keys in credentials, and does not sign out aws login sessions (use aws logout).
Interview questions
- "How do your developers authenticate to AWS from their laptops?" โ Through IAM Identity Center, federated to the corporate IdP, with MFA. The CLI uses
sso-sessionprofiles; each profile maps to one account and permission set; credentials are temporary and cached locally. No IAM users or access keys for humans; CI/CD uses OIDC roles. - "A script works on your machine but fails in the pipeline with 'Unable to locate credentials'. Why?" โ Locally it uses your SSO profile; the pipeline has no profile and no role configured. The fix is to give the pipeline a role (OIDC web identity or an instance/task role), not to copy keys into pipeline variables.
- "How would you get a list of the IDs of all running EC2 instances tagged Environment=prod with the CLI?" โ Use a server-side
--filterson state and tag, then--query "Reservations[].Instances[].InstanceId" --output text, explaining that--filtersreduces data returned while--queryshapes it client-side. - "What is the risk of
aws configure export-credentials?" โ It prints valid temporary keys; anyone who copies them can act as you until expiry. Usecredential_processinstead of pasting them anywhere.
Certification practice
A developer wants to automate the creation of S3 buckets from scripts on a Windows workstation without using the web console. Which tool is the most direct choice?
A. AWS Management Console B. AWS CLI C. AWS Trusted Advisor D. AWS Artifact
Answer: B. The AWS CLI calls AWS APIs from scripts. A is interactive and not scriptable. C gives best-practice recommendations. D provides compliance reports.
A company wants employees to use the AWS CLI with their existing corporate identities and MFA, without creating long-term access keys. What should it use?
A. IAM users with access keys rotated every 90 days
B. AWS IAM Identity Center with CLI profiles that use aws sso login
C. The root user's access keys stored in a password manager
D. Amazon Cognito user pools
Answer: B. Identity Center federates corporate identities, enforces MFA and issues temporary credentials to the CLI. A still uses long-term keys. C violates root user best practice. D is for customers of your applications, not workforce access to AWS accounts.
A developer has AWS_PROFILE=dev set and also has AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set from an old project. Running aws s3 ls uses the old project's identity. What is the best fix?
A. Add region to the dev profile
B. Remove the access key environment variables and rely on the dev SSO profile
C. Run aws configure to store the keys in the credentials file
D. Set AWS_DEFAULT_OUTPUT=json
Answer: B. Environment-variable credentials are checked before profile-based credentials, so they win over AWS_PROFILE. A and D are unrelated settings. C makes the problem permanent by writing long-lived keys to disk.
An auditor asks a bank to prove that engineers' CLI sessions expire and can be traced to individuals. Which design satisfies both requirements with the least operational effort?
A. One shared IAM user per team with MFA B. IAM users per engineer with access keys rotated weekly by a Lambda function C. IAM Identity Center permission sets with a defined session duration, with CloudTrail recording the role session name D. EC2 bastion hosts with instance profiles shared by all engineers
Answer: C. Permission sets produce temporary role sessions whose names identify the user, and the session duration limits lifetime. A loses individual traceability. B still issues long-term keys and adds custom code. D shares one identity among many people.
Completion checklist
-
%USERPROFILE%\.aws\confighas a[sso-session cea]section andlearn-sandbox/learn-billingprofiles -
aws sts get-caller-identity --profile learn-sandboxshows anAWSReservedSSO_SandboxAdmin_...assumed-role ARN -
aws configure list --profile learn-sandboxshows TYPEsso - The Visual Studio Toolkit lists my
learn-sandboxprofile -
Test-NoStaticKeys.ps1printsResult : PASS - I can write a
--querythat filters, projects and sorts - I ran
aws sso logoutat the end of the session
Key takeaways
- A profile = one account + one role + defaults; an
sso-session= how you sign in. Many profiles can share one session. aws sso logingives temporary credentials after browser sign-in with MFA;aws sso logoutwipes the cache.aws loginis the equivalent for IAM users and the Free plan path.- Environment-variable keys beat
AWS_PROFILE;aws configure listshows which source won. --queryshapes output client-side; server-side filters and pagination options control what AWS returns.- A long-lived key on disk is an incident waiting to happen โ prove there are none, and keep proving it.
Further reading
- Configuring IAM Identity Center authentication with the AWS CLI
- Login for AWS local development using console credentials (
aws login) - Configuring settings for the AWS CLI (precedence)
- Setting the output format
- Using the pagination options
- Enabling and using command prompts
aws configure export-credentialsreferenceaws s3api list-bucketsreference- AWS IAM Identity Center credentials in the AWS Toolkit for Visual Studio
Independent learning resource โ not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
The AWS Management Console
Sign in through IAM Identity Center, find your way around the console, use CloudShell, and build habits that stop wrong-Region and wrong-account mistakes.
AWS SDK for .NET: first contact
Call AWS from C# with the AWS SDK for .NET v4: how the SDK finds credentials and a Region, how SSO profiles work from code, how to register clients with dependency injection, and how to read the errors you will meet on day one.