Skip to Content
Cloud Engineering Academy
1. Cloud Computing & AWS Fundamentals

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.

beginnerโฑ 1 h 15 min๐ŸŸข FreeCLF-C02DVA-C03SAA-C03

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 the sso-session and profile sections 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 --query expressions.
  • 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

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:

  1. Credentials โ€” proof of who you are. Ideally temporary: an access key ID, a secret key and a session token that expire.
  2. 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

PieceWhat it isWhy it existsLimitations and sharp edges
AWS CLI v2A single aws executable with commands for almost every AWS APIScripting, automation, quick checks, and seeing the raw API without the console's opinionsCommand 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 locallyRemoves long-lived keys; enforces MFA; ties actions to named usersThe token expires (you sign in again daily); the cache folder is sensitive while it is valid
Named profilesSections in config that bundle account, role, Region and outputSwitching between accounts and roles safelyA typo in a profile name silently falls back to nothing and fails; a stray [default] profile can surprise you
aws loginBrowser sign-in for the root user, IAM users or IAM federation, available from CLI 2.32.0Gives the Free plan path (no Identity Center access to accounts) short-lived credentials tooNot 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 printingGet exactly the fields you need, without jqFilters 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 equivalentWhat's different
az login (browser sign-in to Entra ID)aws sso login --profile learn-sandboxaz 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_PROFILEThere 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 tableaws ... --query and --output tableSame JMESPath language. AWS adds yaml-stream and off, and applies --query per page in text output
Azure PowerShell Connect-AzAccountAWS Tools for PowerShell with the same profilesBoth AWS tools read %USERPROFILE%\.aws\config
Service principal secret in an environment variableAWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEYEqually dangerous. For pipelines AWS uses OIDC role assumption (Module 9)
Visual Studio "Azure Service Authentication" accountAWS Toolkit for Visual Studio credential profileThe 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\cache and cli\cache โ€” tokens and temporary credentials. Sensitive until they expire. aws sso logout deletes them.
  • credentials โ€” should not exist in this course. If it does and contains aws_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-1 in this course;
  • your sandbox account ID (fictional in this lesson: 111122223333) and the role name SandboxAdmin.

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 sso

Answer 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:access

The 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-sandbox

Read 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:

%USERPROFILE%.aws\config
[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 = json

learn-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-sandbox

Expected 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-profiles

Avoid 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 logout

This 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:

  1. Command-line options: --profile, --region, --output
  2. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_PROFILE, AWS_REGION, โ€ฆ
  3. Assume-role settings in the profile (role_arn + source_profile)
  4. Assume role with web identity (used in CI/CD and Kubernetes)
  5. IAM Identity Center settings in config (sso_session โ€ฆ)
  6. The shared credentials file
  7. A custom credential_process
  8. The config file
  9. Container credentials (ECS tasks)
  10. 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-billing

For 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/config

If 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 logout

Free 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-sandbox

Output 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 off

JMESPath --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 text

PowerShell 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-sandbox

Helpers 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-run

export-credentials: useful, and dangerous

# Prints the CURRENT temporary credentials as PowerShell variable assignments
aws configure export-credentials --profile learn-sandbox --format powershell

Some 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-1

Infrastructure 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.

Test-NoStaticKeys.ps1
<#
.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 1

Run it:

aws sso login --profile learn-sandbox
powershell -ExecutionPolicy Bypass -File .\Test-NoStaticKeys.ps1 -ProfileName learn-sandbox

Code explained line by line

  1. [CmdletBinding()] param([string]$ProfileName = 'learn-sandbox') โ€” a script parameter with the course default. We avoid the name $Profile because PowerShell already uses $PROFILE (variable names are case-insensitive).
  2. New-Object System.Collections.Generic.List[string] โ€” a growable list of problems; works in PowerShell 5.1, unlike some newer syntax.
  3. $env:AWS_SHARED_CREDENTIALS_FILE fallback โ€” the CLI honours this variable, so the script checks the file the CLI would actually read.
  4. 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).
  5. The second Select-String checks config for aws_access_key_id, aws_secret_access_key and aws_session_token, because the CLI accepts keys in either file.
  6. [Environment]::GetEnvironmentVariable($name, $scope) โ€” checks the current process and the persistent user and machine scopes; a setx from two years ago would show up here.
  7. aws configure get sso_session --profile $ProfileName 2>$null โ€” reads a single setting; 2>$null hides the "not set" message. login_session covers the Free plan path with aws login.
  8. aws sts get-caller-identity ... --query Arn --output text โ€” proves the credentials work. GetCallerIdentity needs no IAM permission, so failure means a sign-in or configuration problem, not a policy problem.
  9. $LASTEXITCODE โ€” the exit code of the last native command; non-zero means the CLI failed.
  10. -notmatch ':assumed-role/AWSReservedSSO_' โ€” Identity Center sessions always appear as assumed roles whose names start with AWSReservedSSO_.
  11. 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 (or aws login on 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\cache and \.aws\login\cache contain tokens and temporary credentials. Exclude .aws from cloud-synced folders and backups you do not control; run aws sso logout on shared machines.
  • Pin profiles in scripts. --profile learn-sandbox in every script line avoids "ran it against the wrong account".
  • Never paste export-credentials output 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. Use aws configure sso once.
  • Old keys in environment variables โ†’ set years ago for another tool โ†’ they override AWS_PROFILE and you act as a different identity. Check aws configure list and Get-ChildItem Env:AWS*.
  • A [default] profile with keys โ†’ older tutorials create one โ†’ any command without --profile uses 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_region is where Identity Center lives; region is where your commands go.
  • Using text output without --query โ†’ column order is alphabetical and can change โ†’ scripts break. Always project the fields you need.
  • Trusting --max-items to reduce cost or load โ†’ it only limits what is printed; the CLI still pages through the API. Use server-side filters such as --prefix where they exist.
  • Leaving the pager on in scripts โ†’ a script hangs waiting at -- More --. Use --no-cli-pager or set cli_pager to empty.

Troubleshooting

SymptomLikely causeFix
Error when retrieving token from sso: Token has expired and refresh failedIdentity Center sign-in expiredaws sso login --profile learn-sandbox
The config profile (learn-sandbx) could not be foundTypo in --profile or AWS_PROFILEaws configure list-profiles; fix the name
Unable to locate credentialsNo profile chosen and no defaultAdd --profile, or set $env:AWS_PROFILE
InvalidClientTokenId or SignatureDoesNotMatchStale static keys in env vars or credentials override SSORemove-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 requestWrong sso_region or start URLCompare with the access portal's Access keys dialog
Login hangs over SSH / remote desktop without a browserPKCE needs a browser on the same machineaws sso login --use-device-code
AccessDenied ... explicit deny in a service control policyRegion guardrail from Module 0Use us-east-1 or eu-west-2
SSL: CERTIFICATE_VERIFY_FAILED on a corporate networkTLS-inspecting proxy with a private CASet 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 PowerShellQuoting: backticks or nested double quotesOuter double quotes, inner single quotes
aws login is "not a valid choice"CLI older than 2.32.0Update 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-sandbox

Exercises

  • ๐ŸŸข Guided (Lab 1.2): Configure the cea SSO session and the learn-sandbox profile with aws configure sso. Add learn-billing by hand. Connect the AWS Toolkit for Visual Studio to learn-sandbox and open the S3 node in AWS Explorer. Then run Test-NoStaticKeys.ps1 and get Result : PASS.
  • ๐ŸŸก Challenge: Write one CLI command (no PowerShell filtering) that prints a table of buckets whose names start with hl-, with columns Bucket and Created, 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 ls with AWS_PROFILE=learn-sandbox and it listed buckets I've never seen, including harbourline-legacy-reports. aws sts get-caller-identity shows arn: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

Knowledge check

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-session profiles; 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 --filters on state and tag, then --query "Reservations[].Instances[].InstanceId" --output text, explaining that --filters reduces data returned while --query shapes 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. Use credential_process instead of pasting them anywhere.

Certification practice

Completion checklist

  • %USERPROFILE%\.aws\config has a [sso-session cea] section and learn-sandbox / learn-billing profiles
  • aws sts get-caller-identity --profile learn-sandbox shows an AWSReservedSSO_SandboxAdmin_... assumed-role ARN
  • aws configure list --profile learn-sandbox shows TYPE sso
  • The Visual Studio Toolkit lists my learn-sandbox profile
  • Test-NoStaticKeys.ps1 prints Result : PASS
  • I can write a --query that filters, projects and sorts
  • I ran aws sso logout at 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 login gives temporary credentials after browser sign-in with MFA; aws sso logout wipes the cache. aws login is the equivalent for IAM users and the Free plan path.
  • Environment-variable keys beat AWS_PROFILE; aws configure list shows which source won.
  • --query shapes 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

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.

On this page