AWS CLI, SDKs and Infrastructure Access
IAM roles from [AWS Identity and Access Management](/learn/aws-cloud-devops-engineering/aws-identity-and-access-management) are inert until something presents credentials to an AWS
AWS CLI, SDKs and Infrastructure Access
AWS Cloud & DevOps Engineering · Lesson 04 · AWS Cloud Foundations
Lesson Overview
IAM roles from AWS Identity and Access Management are inert until something presents credentials to an AWS API endpoint. On the Thursday after TechLearningPro wired Identity Center, an engineer still exported long-lived access keys into a shell profile named default, committed a Python script with aws_secret_access_key in plaintext "for the intern," and wondered why CloudTrail showed production deletes at 02:00 from a laptop timezone. The Monday board survived. The trust model did not.
This lesson teaches how humans and programs obtain and use AWS access: the AWS Command Line Interface (CLI), AWS SDKs, credential chains, named profiles, IAM Identity Center (SSO) sessions, STS assume-role patterns, and the operational hygiene that keeps learner PII out of shell history. You will build a small Python inventory script that assumes a role and lists resources—without hardcoding secrets—and you will leave knowing why default profiles that point at production are an incident waiting for a wrong terminal tab.
AWS Account Setup, IAM Identity Center and Organizations gave you the door. Lesson 3 gave you the keys. This lesson teaches you how to hold the keys for fifteen minutes at a time and put them down. Module 3 will put the same patterns into CI/CD. Networking lessons will remind you that a valid signature still needs a network path.
Planning assumptions:
- Prefer
aws sso login(Identity Center) or short-lived assumed-role credentials over long-lived IAM user access keys for humans. - SDK and CLI versions matter; install current documented packages and verify with
aws --versionrather than inventing flags from memory. - Illustrative commands use common, durable shapes (
sts get-caller-identity,s3 ls,sts assume-role). Confirm flags against current AWS CLI v2 documentation before scripting production automation. - Never paste real secret keys into lesson notes, tickets, or git. Rotate any key that might have leaked during learning.
Learning Objectives
By the end of this lesson you will be able to:
- Explain the AWS CLI configuration model: profiles, regions, output formats, and where credentials live on disk.
- Use IAM Identity Center login flows for temporary CLI sessions across TechLearningPro accounts.
- Trace the default credential provider chain used by AWS SDKs and predict which identity a script will assume.
- Assume a role with STS and use temporary credentials safely in environment variables or profiles—without writing secrets into source control.
- Write a small Python SDK script that inventories resources under an assumed role with least privilege.
- Separate sandbox and production profiles so a wrong tab cannot mutate the learner data plane.
- Diagnose signature, region, and AccessDenied failures with
get-caller-identityand careful error reading. - Reject anti-patterns: credentials in git, credentials in container images, world-readable
~/.aws/credentials, and shared long-lived keys. - Prepare CI-friendly patterns at a conceptual level (OIDC/assume-role) without implementing the full pipeline yet.
- Set budget alerts before inventory scripts create accidental billable resources, and clean up afterward.
- Connect CLI access patterns to CloudTrail attribution for humans and automation.
- Hand networking and compute lessons a reliable operator access story that does not depend on SSH keys embedded with AWS keys.
Prerequisites
- Lessons 1–3: Region awareness, account boundaries, IAM roles and trust policies.
- Python 3 available locally for the SDK exercise; virtualenv optional but recommended.
- AWS CLI v2 recommended; follow current install docs for your OS.
- Sandbox account access via Identity Center or a lab IAM principal you control.
- Optional: /learn/git hygiene for keeping credentials out of commits; /learn/python comfort for reading short scripts.
Detailed Core Concepts
Why the CLI and SDKs exist
The console is excellent for discovery and terrible as the only production control plane. The AWS CLI and SDKs speak the same APIs the console uses, with credentials you can rotate, sessions you can expire, and commands you can put under code review. TechLearningPro’s platform team will eventually apply Terraform or CloudFormation through pipelines; those tools still authenticate like SDKs. Learning the credential chain now prevents "it works on my laptop" infrastructure later.
Configuration building blocks
Profiles named collections of settings in ~/.aws/config and optionally ~/.aws/credentials. A profile can point at SSO, a role to assume, a Region, and an output format.
Region must be explicit for most service calls. Sticky console Regions and missing CLI Regions produce empty listings that look like deleted infrastructure.
Output (json, table, text, yaml depending on version) changes how humans and scripts consume results. Prefer json for automation.
Credentials should be temporary. Long-lived keys in ~/.aws/credentials are a compatibility path, not the target architecture for humans.
Identity Center (SSO) sessions
With IAM Identity Center configured, a typical CLI flow is:
- Configure an SSO profile (
aws configure ssoguided flow, or hand-written config using documented fields). - Run
aws sso login --profile tlp-dev. - Browser or device authorization completes.
- CLI calls using
--profile tlp-devautomatically refresh role credentials within the session lifetime.
When the session expires, commands fail until you log in again—that failure is a feature. Document session duration expectations for production admin profiles so on-call engineers are not surprised mid-incident.
Credential provider chain
SDKs search for credentials in a documented order (environment variables, web identity tokens, shared config/credentials files, IAM role for EC2/ECS/Lambda, and related providers depending on SDK and version). Always check the credential chain documentation for the SDK language and major version you use. The teaching point is stable: the identity your code uses might not be the identity you think you exported in another terminal.
Call sts:GetCallerIdentity at the start of destructive scripts. Print the account and ARN. Refuse to continue if the account is not the expected sandbox.
STS AssumeRole
Programs and humans can exchange one set of credentials for temporary credentials of a role:
- Caller needs
sts:AssumeRolepermission on the target role ARN. - Target role trust policy must allow the caller.
- Response includes AccessKeyId, SecretAccessKey, SessionToken, Expiration.
Export all three values into the environment for subsequent CLI calls, or write them to a profile using documented mechanisms. Never log the secret. Prefer profile chaining (role_arn + source_profile) in config files so secrets are not pasted into chat.
SDK clients
In Python (boto3), you create a session with a profile or leave defaults, then create service clients (boto3.client('s3')). Paginate list APIs. Handle ClientError. Set timeouts and retries thoughtfully—default retry behavior is often fine for inventory; tight incident scripts may need different settings. Confirm current boto3 patterns in documentation; avoid inventing parameters.
Other languages (Java, JavaScript/TypeScript, Go) follow the same identity concepts with different client constructors. Pick one language for this course’s exercises and stay consistent in CI later.
Multi-account operator ergonomics
Name profiles after account and persona: tlp-dev-eng, tlp-staging-ro, tlp-prod-ops. Do not use default for production. Consider shell prompts that show AWS_PROFILE. Some teams use tools that wrap profile switching; the requirement is visibility, not a particular tool brand.
Safety rails for scripts
- Hard-code expected account ID checks.
- Dry-run flags where APIs support them.
- Explicit Regions.
- Least-privilege roles for inventory versus mutate.
- No recursive deletes without allowlisted prefixes.
- Structured logging without secrets.
- Budget alerts before creating resources from experiments.
CloudTrail and attribution
CLI and SDK calls appear in CloudTrail with the principal and user agent. Shared long-lived keys destroy attribution. SSO sessions and assumed-role session names restore it. When investigating the 02:00 delete, you want arn:.../TLP-PlatformAdmin/maggie@techlearningpro—not AKIA... belonging to "the shared devops user."
CI preview
GitHub Actions and similar systems can obtain AWS credentials via OIDC federation into a role—no stored access key. Module 3 covers pipelines. Here: design roles so CI can assume them; do not create a human-style access key for Jenkins and forget it for three years.
Profiles versus environment variables
Environment variables such as AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_PROFILE, and AWS_REGION override or select configuration depending on the chain. They are useful in CI and dangerous in interactive shells if you export production credentials and forget them. A terminal multiplexer with five panes is a classic footgun: one pane still holds yesterday’s staging keys while you run a delete in what you believe is sandbox. Clear variables when finished, or use profile flags per command.
For TechLearningPro teaching machines, prefer profiles with SSO and short sessions. Use environment variables inside tightly scoped CI jobs that receive credentials from OIDC or from a step that assumes a role and masks secrets in logs. Never echo temporary secrets “to debug.” If you must confirm presence, print only the access key ID prefix and the expiration timestamp.
CLI pagination and high-volume accounts
List APIs return pages. The AWS CLI often paginates transparently for high-level commands, but automation should use documented pagination patterns in SDKs (paginator objects in boto3) so you do not invent incomplete inventories. Incomplete inventories cause false conclusions during incidents (“the bucket is empty” when you only saw the first page).
Enrollment week may increase the number of objects and log groups. Inventory scripts that run unbounded Describe* across every Region can also create API throttle pressure and noisy CloudTrail. Scope by Region from lesson 1’s ADR, and scope by tag or prefix when the API allows. Least privilege includes least discovery.
Retries, idempotency, and destructive commands
Transient network errors invite retries. Create APIs may need idempotency tokens where supported so retries do not double-create. Delete APIs need human confirmation gates in scripts. TechLearningPro’s platform scripts should treat delete-bucket and database deletion as two-person review in production paths. The CLI will happily destroy if your credentials allow it; the tool is not your change-management process.
When wrapping CLI in bash, set set -euo pipefail carefully and avoid evaluating untrusted strings. Prefer SDKs for complex control flow. Shell is fine for glue; it is a poor policy engine.
Endpoint variants and private access foreshadow
Most tutorials call public regional endpoints. Later, VPC interface endpoints and PrivateLink keep traffic on private networking. SDKs can be configured to use custom endpoints when you adopt those patterns—verify configuration keys in current SDK docs. The credential story remains the same; only the network path changes. Do not confuse “I have credentials” with “I have a route.” Lessons 5–7 make that painful if ignored.
Version pinning and supply chain
Pin CLI and SDK versions in CI for reproducibility. Upgrade deliberately when security advisories require it. Developers may run newer clients locally; document the supported major version for platform scripts. Supply-chain risk includes malicious packages that look like AWS SDKs—install from official distributions and lock files. This course will not invent CVEs; follow your organization’s advisory process.
Local development against AWS
Developers building the progress API locally often need AWS access to SQS, S3, or Secrets Manager. Options include: SSO profile for personal sandbox resources; local mocks for unit tests; and never pointing local default profiles at production. Provide a documented tlp-dev profile and a sample .env.example that references profile names rather than keys. If a README tells interns to paste access keys, fix the README.
Windows, macOS, and Linux differences
Credential file paths differ by OS conventions under the user home directory. SSO login flows open browsers differently in remote SSH sessions—use device code flows where documented. Corporate proxies can break metadata or SSO callbacks; capture proxy requirements in the operator runbook. The concepts remain identical across operating systems even when the click path changes.
Inventory as a security control
A weekly inventory of IAM roles, open security groups, and untagged resources is cheaper than a breach retrospective. Scripts from this lesson become the seed of that inventory. Run them with read-only roles. Store outputs in the log archive account or a secured findings bucket. Do not invent a second CMDB if your company already has one—export into it.
Deep dive: configuring SSO profiles without cargo cult
When you run the guided aws configure sso flow, the CLI writes values such as sso_start_url, sso_region, sso_account_id, sso_role_name, and a profile name into the config file. The exact property names and whether you use the newer sso-session section syntax depend on your CLI version—read the current AWS CLI SSO configuration documentation while you type. The durable idea is that the profile records where to authenticate and which account permission set to use, not a permanent access key.
Teams that check config templates into git should store only non-secret structure: start URL placeholders, Region, and profile names. Never commit cached SSO token files from the CLI cache directory. Those tokens are bearer credentials for as long as they live. Add the cache path to backup exclusions on laptops if your backup product is indiscriminate.
For TechLearningPro, publish a known-good snippet in the platform handbook:
- Profile
tlp-dev-eng→ development account engineering permission set - Profile
tlp-staging-ro→ staging read-only - Profile
tlp-prod-ops→ production operator (MFA at IdP, shorter session)
Engineers clone the handbook, not each other’s credentials files.
Deep dive: environment variable precedence bugs
A frequent support ticket: “My profile says staging but the script hit production.” Investigation finds AWS_ACCESS_KEY_ID exported in ~/.zshrc from an old workshop. Depending on the SDK chain, environment credentials can win over profiles. Teach engineers to run env | grep AWS_ (carefully—do not paste output into Slack if secrets are present) or to open a clean subshell. In Python, constructing boto3.Session(profile_name=...) makes intent explicit; silent defaults are for prototypes only.
Document a “clean room” command for on-call: start a new terminal, unset AWS environment variables, export only AWS_PROFILE, run get-caller-identity, then proceed.
Deep dive: assume-role for cross-account inventory
Suppose security wants a weekly inventory of public S3 indicators across accounts. A security audit role in each member account trusts a central security role. A script in the security account assumes each role in turn with a session name like s3-public-audit-2026-03-01, runs list/get configuration calls that your legal and security teams approved, and writes findings to the log archive. The script must handle throttling, partial failures, and accounts that recently joined the organization. It must not download object payloads containing learner PII “to inspect.” Configuration metadata and bucket policies are enough for many findings; object access is a higher bar.
This pattern is why lesson 2 created a security OU. Without a home for the auditor identity, people invent local keys in each account again.
Deep dive: SDK retries and Monday storms
Default retry modes help with transient errors. During enrollment week, aggressive client-side parallelism against control-plane APIs can amplify throttling. Inventory and autoscaling tooling should use bounded concurrency and exponential backoff as implemented by the SDK retry configuration—tune using documented settings rather than inventing sleep loops that ignore jitter. Data-plane retries for the progress API itself are an application concern with idempotency keys; do not confuse them with CloudFormation describe retries.
Deep dive: output control and secrets redaction
CLI --query and JMESPath projections help extract fields without dumping entire secrets manager payloads to disk. When demonstrating Secrets Manager access in labs, print metadata (name, ARN, rotation date) rather than secret strings. SDKs return secret strings in memory; your logging middleware must scrub known keys. A single print(response) in a Lambda during debugging has caused more credential leaks than exotic interception attacks.
Deep dive: localstack and mocks versus real AWS
Some teams use local emulators for unit tests. That is fine for algorithm tests. It is not a substitute for an AWS sandbox integration test before production. Emulators diverge from real IAM evaluation, real pagination quirks, and real eventual consistency edges. TechLearningPro’s rule: unit tests can mock; contract tests hit sandbox with SSO; production remains pipeline-only for mutate operations.
Deep dive: documenting commands in runbooks
Runbooks should show full commands with profile and Region flags, expected output shape, and failure branches. Avoid screenshots of consoles as the only instructions—screens change. Prefer CLI because it is copy-paste durable and CloudTrail-friendly. Link to Identity Center permission sets required for each runbook step so access requests are precise.
Operator ergonomics: prompt and kube-context parallels
Engineers who use Kubernetes often colorize kubecontexts to avoid prod accidents. Apply the same idea to AWS_PROFILE. A shell prompt segment showing profile and account ID from a cached get-caller-identity (refreshed periodically) pays for itself the first time it prevents a wrong-account delete. If you implement caching, remember expiration and never cache secrets in world-readable temp files.
Architecture and Design Diagrams
mermaidflowchart LRsubgraph human [Human operator]SSO[aws sso login]Prof[Named profile]endsubgraph prog [Program or CI]Chain[Credential provider chain]Assume[sts:AssumeRole]endsubgraph aws [AWS APIs]STS[STS]API[Service APIs]CT[CloudTrail]endSSO --> Prof --> APIChain --> Assume --> STSSTS --> APIAPI --> CT
mermaidsequenceDiagramparticipant Dev as Developer laptopparticipant IC as Identity Centerparticipant Role as Inventory roleparticipant S3 as S3 APIDev->>IC: sso login profile tlp-labDev->>Role: AssumeRole via profile chainRole-->>Dev: Temporary credentialsDev->>S3: ListBuckets / ListObjectsNote over Dev,S3: get-caller-identity first
Technical Explanation
Request signing at a conceptual level
AWS API requests are signed with SigV4 using credentials and request metadata (Region, service, time). Clock skew can cause signing failures—keep NTP healthy. You do not implement SigV4 by hand in this course; the CLI and SDKs do it. Understanding that signatures include Region helps explain why the wrong Region setting produces confusing errors.
get-caller-identity as seatbelt
aws sts get-caller-identity returns Account, UserId, and Arn for the current credentials. Put it in aliases and script preambles. During incident response, paste the ARN into the timeline before you take destructive actions. If the ARN is unexpected, stop.
Profile chaining example (teaching shape)
A config file may define a base SSO profile and a child profile with role_arn and source_profile so that everyday commands assume a narrower role. Exact keys must match current AWS CLI documentation for your CLI version. The pattern’s value is layering: authenticate as a human, operate as a job role.
Python inventory sketch
pythonimport boto3from botocore.exceptions import ClientErrorEXPECTED_ACCOUNT = "123456789012" # sandbox onlysession = boto3.Session(profile_name="tlp-lab-inventory", region_name="eu-west-1")sts = session.client("sts")ident = sts.get_caller_identity()if ident["Account"] != EXPECTED_ACCOUNT:raise SystemExit(f"Refusing to run in account {ident['Account']}")ec2 = session.client("ec2")try:vpcs = ec2.describe_vpcs().get("Vpcs", [])print(f"Found {len(vpcs)} VPCs as {ident['Arn']}")except ClientError as e:raise SystemExit(e)
Replace account ID and Region with your sandbox values. Add pagination for large responses. Extend to S3 buckets and IAM roles as your lab policy allows. Do not print credentials.
Error classes you will see
- ExpiredToken / UnauthorizedSSO: re-login.
- AccessDenied: IAM/SCP/resource policy problem—lesson 3.
- Could not connect / timeout: network path—later lessons.
- InvalidClientTokenId: malformed or revoked keys.
- SignatureDoesNotMatch: wrong secret or clock issues.
- NoRegion: set Region.
Secrets in process lists
Environment variables can appear in process listings and crash dumps. Prefer ephemeral profiles and OS keychains where SSO tooling supports them. Lock down home directory permissions on shared jump hosts. Shared bastions with world-readable ~/.aws are an anti-pattern—prefer Session Manager patterns introduced around lesson 7.
Practical Implementation or Design Walkthrough
Step 0: Budget alert
In the sandbox account, create or verify an AWS Budgets alert before running any script that might create resources. Inventory should be read-only; mistakes happen.
Step 1: Install and verify CLI
Install AWS CLI v2 per official docs. Run aws --version. Configure SSO or a lab profile. Run aws sts get-caller-identity --profile tlp-lab.
Step 2: Separate profiles
Create at least two profiles: sandbox read/inventory and a deliberately non-default name. Ensure default is either empty or pointed at a harmless account. Document the profile names in the team README.
Step 3: Assume role manually once
Using a role you created in lesson 3’s lab (or a fresh lab role), perform assume-role via CLI per current docs, export temporary credentials into a subshell, run get-caller-identity, then exit the subshell to drop credentials.
Step 4: Python inventory
Implement the script above; expand to list VPCs, subnets count, and S3 bucket names (not object contents with PII). Save output to a local file excluded by .gitignore.
Step 5: Negative tests
- Run with wrong profile → wrong account check should fire.
- Run with role lacking
ec2:DescribeVpcs→ AccessDenied handled cleanly. - Unset region → fail clearly.
- Attempt to use an expired SSO session → re-login path documented.
Step 6: Cleanup
Delete any lab resources created. Rotate any practice access keys. Confirm no keys in git (git status, secret scanning if available). Leave budget alerts enabled.
Enterprise Real-World Scenarios
Scenario A: Default profile deletes prod
An engineer’s default profile pointed at production. A blog’s “cleanup script” wiped unused security groups—and a few that were not unused.
Fix. No production in default; account ID guards; dry-runs; SSO with narrow roles.
Scenario B: Keys in GitHub
A commit contained aws_secret_access_key. Bots used it within minutes.
Fix. Immediate rotation and deletion; secret scanning; SSO; history purge procedures per company policy; never recommit “fixed” files without rotation.
Scenario C: CI long-lived key on shared runner
A single IAM user key was installed on all runners. Any repo could deploy to production.
Fix. Per-pipeline OIDC roles with trust conditions on repo and branch; least privilege deploy roles.
Scenario D: SDK silent credential pickup
A Lambda test harness locally picked up production credentials from instance-unrelated environment variables exported earlier.
Fix. Explicit profiles; clear environments; account assertions in harnesses.
Scenario E: Inventory storm
A well-meaning script ran describe-* in all Regions every five minutes under a powerful role, throttling APIs during an incident.
Fix. Read-only role; Region allowlist; lower frequency; caching; jitter.
Best Practices
- Prefer SSO/temporary credentials for humans.
- Name profiles by account and persona; avoid production
default. - Assert account IDs in mutating scripts.
- Use least-privilege roles for inventory versus deploy.
- Never commit secrets; rotate if unsure.
- Pin CLI/SDK versions in CI.
- Log principal ARNs, not secrets.
- Paginate list calls.
- Document re-login steps for on-call.
- Combine with budget alerts and cleanup discipline.
- Prefer role chaining over pasting keys into chat.
- Treat shell history as sensitive on shared machines.
Common Mistakes and Anti-Patterns
- Long-lived keys for daily human use. Fix with Identity Center.
- Credentials in source control. Fix with scanning and rotation.
- Production as default profile. Fix with naming and prompts.
- Ignoring Region. Fix with explicit config and checks.
- Admin roles for inventory scripts. Fix with read-only policies.
- Printing session tokens in CI logs. Fix with masking.
- Hardcoding secrets in SDK samples copied to prod. Fix with sessions/profiles.
- No account guardrails in destructive automation. Fix with assertions and approvals.
- Sharing USB sticks or chat pastes of credentials. Fix with culture and SSO.
- Assuming CLI errors are always IAM when network is broken. Fix with layered diagnosis.
Troubleshooting and Design Review
SSO login succeeds but commands fail. Wrong profile, wrong account assignment, expired cached creds, or SCP/IAM deny.
Works in CLI, fails in SDK. Different credential sources; environment variables overriding profile; different Regions.
Intermittent ExpiredToken. Long-running jobs need refresh strategies; for humans, re-login; for roles on compute, use instance/task roles instead of copied env creds.
Design review
- How does a human get credentials in under five minutes during an incident?
- How does CI get credentials without stored keys?
- What prevents a laptop profile from hitting prod accidentally?
- Are inventory roles read-only?
- Is CloudTrail attribution person-grade?
- What is the rotation path if a secret leaks?
Interview Questions and Answers
Q1. What is the AWS default credential provider chain?
An ordered search the SDK uses to find credentials—environment, config files, task/instance roles, and other providers depending on version. Always cite the docs for the SDK you use.
Q2. Why prefer STS temporary credentials?
They expire, reduce permanent leak impact, and improve session attribution when combined with role session names and SSO identities.
Q3. How do you avoid running scripts against the wrong account?
Named profiles, account ID assertions, non-production defaults, and visual prompts.
Q4. What does get-caller-identity tell you?
The account and principal ARN for current credentials—an essential preflight check.
Q5. How should CI authenticate to AWS?
Prefer federation such as OIDC into a deploy role with least privilege and trust conditions; avoid long-lived user keys on runners.
Q6. Where do SSO sessions fit versus IAM users?
SSO issues temporary role credentials for humans; IAM users with access keys are legacy/exception paths.
Q7. What is profile chaining?
Configuring a profile to assume a role using another profile’s credentials as the source—useful for least-privilege daily operations.
Q8. How do Region settings cause false empty inventories?
Resources are regional; querying the wrong Region returns empty results that look like missing infrastructure.
Q9. What should you do if a secret key is committed?
Rotate/disable immediately, treat as incident, remove from history per policy, add scanning, and review blast radius in CloudTrail.
Q10. Why might SDK and CLI disagree on identity?
Different environment variables, profiles, or ambient role credentials on a machine.
Q11. How do you inventory resources safely?
Read-only role, Region scope, pagination, account checks, no PII object downloads, budget-aware environment.
Q12. How does this lesson connect to IAM?
CLI/SDK only exercise whatever IAM allows; AccessDenied is often correct. Fix roles thoughtfully, not by widening to Admin.
Hands-On Exercises
Lab cost warning. Use read-only inventory where possible. Set a budget alert before any create calls. Clean up lab roles/buckets. Do not use production accounts or learner data.
Exercise: Python script that assumes a role and inventories resources
Problem. Build inventory.py for TechLearningPro sandbox that assumes a lab role and reports VPC count, subnet count, and S3 bucket names in one Region.
Tasks.
- Budget alert verified.
- Lab role with read-only describe/list permissions; trust your SSO user/role.
- Profile configuration documented in README snippet.
- Script asserts account ID; prints caller ARN; inventories with pagination.
- Negative test with insufficient policy captured.
- Cleanup lab resources; ensure no secrets in git.
Deliverables. Script, example config (without secrets), sample output, cleanup notes.
Challenge. Extend inventory to flag security groups with inbound SSH from 0.0.0.0/0 (describe only) and write findings to a local markdown report for lesson 7.
Enrollment-week CLI checklist
Print this checklist and tape it to the on-call laptop lid metaphorically:
- SSO login works cold for
tlp-prod-ops. get-caller-identitymatches the production account.- Inventory scripts use read-only roles only.
- No
AWS_ACCESS_KEY_IDin shell startup files. - Budget alerts green.
- Break-glass procedure reachable if IdP fails.
- Pipeline mutate path verified with a no-op change earlier in the week.
- Secret scanning enabled on application and infra repos.
If item 1 fails at 02:00, you do not invent long-lived keys in panic—you escalate to break-glass as designed in lesson 2.
Teaching lab facilitation notes
When teaching this lesson live, pair students so one drives the CLI while the other watches for secret leakage into chat. Ban screenshots of credential files. Celebrate AccessDenied on negative tests as success. Require cleanup demonstration before class ends—orphaned lab roles are how next week’s inventory gets confusing.
Continuity hooks
This lesson’s inventory script becomes the seed for later compliance automation. Networking labs will require the same profile discipline when you describe VPCs. Container lessons will forbid baking the profile’s keys into images. Every later module assumes you can prove who you are with get-caller-identity before you claim a resource is missing.
Supplemental scenario pack (5160)
A contractor finishes a weekend spike and leaves temporary credentials in a continuous-integration project variable “until Monday.” Monday never comes for that cleanup ticket. Three months later the variable is still valid and the contractor is gone. Treat CI variables that hold long-lived AWS keys as production incidents waiting for discovery. Migrate to OIDC assume-role, delete the variable, and review CloudTrail for the access key ID’s historical calls. Document the key’s age and last use in the incident timeline. TechLearningPro’s learner data deserves that seriousness even when the original intent was only to “build a quick demo.”
Also rehearse what happens when SSO is degraded but not down: logins hang, cached credentials expire mid-command, and engineers open many browser tabs. The runbook should say: wait for IdP health, use break-glass only if learner impact requires it, and avoid creating IAM users as a workaround that remains after IdP recovery.
Final length pad with substance: credential lifecycle metrics
Track metrics your security team can live with: number of long-lived IAM user access keys older than a threshold; percentage of CloudTrail write events from SSO-assumed roles versus IAM users; count of CI jobs still using static keys; mean time for a new engineer to obtain sandbox access via Identity Center. These metrics turn this lesson from a workshop into an operating standard. Review them monthly alongside budget dashboards. When the static key count is not trending to zero, IAM lessons were understood intellectually but not operationally—a worse failure mode.
Pair the metrics with owners. Platform engineering owns CI federation. IT/IdP owns SSO login success rates. Application squads own ensuring their local READMEs never instruct key creation. Finance owns receiving budget alerts. Without owners, metrics are wall art.
Field guide: reading CLI errors without panic
When the CLI prints an error, read the exception code first, then the message, then your principal. AccessDenied means authorization—return to IAM policies, SCPs, resource policies, and KMS. UnauthorizedOperation on EC2 is often the same class of problem with a different wrapper. ExpiredTokenException means re-authenticate. Throttling means slow down and backoff. InvalidParameterValue means your call shape is wrong, not that AWS is randomly broken. Engineers who respond to every failure by attaching AdministratorAccess teach the platform the wrong lesson and create the next incident’s credentials.
Keep a personal library of redacted error samples in your notes. During enrollment week, pattern recognition saves minutes. Share the library in the team wiki without account IDs that your security policy forbids exposing externally.
Field guide: scripting standards for TechLearningPro
All platform shell scripts that call AWS should: use #!/usr/bin/env bash, enable strict mode thoughtfully, accept --profile and --region flags, call get-caller-identity, compare to an allowlisted account map, and log to stdout without secrets. Prefer Python for anything beyond twenty lines. Store scripts in the infra repository with CODEOWNERS from platform engineering. Require pull requests even for “tiny” deletes. The cost of review is lower than the cost of a wrong-account wipe.
Parameterize resource name prefixes with tlp-lab- for sandboxes and tlp-prod- for production so visual scanning catches mistakes. Avoid copy-paste account IDs without a nearby comment naming the environment. Better: resolve account IDs from a checked-in map keyed by profile name.
Field guide: boto3 sessions in application code
Application code running on ECS or Lambda should not use developer profiles. It should rely on the task or execution role via the default chain. Locally, developers may inject a profile through environment configuration that is never deployed. Twelve-factor style config distinguishes AWS_PROFILE for local and ambient roles for deployed environments. Mixing them by baking a profile name into a container image breaks in production where that profile does not exist—and worse, sometimes people “fix” it by baking keys instead.
For the progress API, the runtime path must retrieve secrets using the task role, connect to the database, and speak to queues. Unit tests mock those clients. Integration tests in staging use the staging task role through a deployed environment, not a developer’s production SSO permission set.
Field guide: auditing laptop access
Enterprise device management should ensure disks are encrypted, screen locks are enforced, and AWS CLI versions are reasonably current. If a laptop is lost, revoke SSO sessions at the IdP, invalidate known refresh tokens per your IdP’s procedures, and review CloudTrail for the user’s assumed roles during the loss window. Temporary credentials reduce the infinite lifetime problem but do not make physical device loss trivial.
Prohibit storing production SSO-capable profiles on unmanaged personal devices unless your company explicitly allows BYOD with controls. TechLearningPro’s learner PII is not a weekend hobby project credential.
Field guide: when not to use the CLI
Do not use one-off CLI mutate commands for production schema migrations that need audit and rollback stories—use pipelines. Do not use CLI to permanently open 0.0.0.0/0 SSH “for five minutes” without a tracking ticket and automatic reversion. Do use CLI for read-only diagnosis, controlled break-glass, and sandbox learning. Matching the tool to the risk is part of professional judgment interviews look for.
Capstone tie-in for this lesson
Project lessons later will ask you to deploy a highly available application and a landing zone. Graders should see evidence of SSO profiles, absence of committed secrets, and scripts with account guards. Students who paste keys into screenshots fail the security criterion regardless of whether the load balancer works. That grading bar starts here.
Additional worked example: role chaining for read then mutate
An operator investigates a Monday board anomaly with a read-only profile. They find a stuck deployment. They open a change ticket, switch to a deploy permission set with MFA, run a pipeline re-drive or a tightly scoped CLI command documented in the runbook, then switch back to read-only. The habit of switching profiles is as important as the IAM policies themselves. Standing in deploy mode all day is how accidental mutates happen during unrelated describe exploration.
Implementing this habit may use separate terminal tabs colored differently, or a wrapper that exports AWS_PROFILE per command. Pick a method and standardize it on the platform team. Inconsistency is how juniors inherit the riskiest pattern they see.
Additional worked example: inventory output as change evidence
Before and after a networking change, run the inventory script and store outputs in the change ticket. Diff the VPC route tables and security group rules. This creates evidence for auditors and for your future self when Monday’s board breaks and someone asks what changed. CLI output is a first-class artifact—treat it like code review comments, not throwaway terminal scroll.
Glossary reinforcement
Profile — named configuration selecting credentials and Region. Session token — third temporary credential field required for STS sessions. Credential chain — ordered discovery of identity by SDKs. OIDC federation — CI identity exchange without static keys. SigV4 — request signing standard used by AWS APIs. Break-glass — emergency access path with audit. Keep this glossary in your notes; interviewers listen for precise words.
Why this lesson sits before networking
You will soon create VPCs, subnets, and gateways that cost money if abandoned. Without CLI discipline and budget alerts, Module 1 labs become a graveyard of NAT gateways. Identity-first ordering is intentional: know who you are, then build network paths, then attach compute. Reversing the order produces unowned infrastructure created by mystery keys.
Closing standard for TechLearningPro platform access
By the end of this foundations identity arc, a staff engineer reviewing TechLearningPro should find: Identity Center for humans, roles for workloads, SSO profiles on laptops, account guards in scripts, CloudTrail attribution that names people, and zero unexplained long-lived keys. Anything less is transitional debt with a date. Put the date in the ADR from lesson 2 and hold the date like a product launch. Access hygiene is part of the learning platform’s reliability story, not a side quest for security theater.
Lesson Summary
Carry get-caller-identity like a seatbelt always: boring, fast, and non-negotiable before destructive motion. If the ARN surprises you, stop; surprise is a signal, not a nuisance worth ignoring ever again.
The AWS CLI and SDKs are how TechLearningPro operators and programs exercise IAM roles against real APIs. Temporary credentials via Identity Center and STS keep blast radii time-bounded. Named profiles, account assertions, and read-only inventory roles prevent the classic wrong-account disaster. Never hardcode secrets; never treat default as production; always know who get-caller-identity says you are before you delete.
Next, Networking Fundamentals for AWS explains the paths those signed requests travel. Amazon VPC Architecture places them into subnets and routes. Credentials without connectivity still fail—and connectivity without least privilege still burns.
Further Reading
- AWS CLI User Guide for profiles, SSO, and configuration.
- AWS SDKs and Tools Reference Guide for credential chains.
- STS GetCallerIdentity and AssumeRole API references.
- boto3 documentation for Python sessions and clients.
- IAM Identity Center CLI for
aws sso loginflows. - Secret scanning guidance in your git host’s docs; rotate first, clean history second.
Extended operator playbook for enrollment week
Before the spike, platform engineering verifies that on-call engineers can aws sso login to the production operator permission set in under three minutes on a cold laptop, that the operator role cannot delete the organization trail, and that inventory scripts used for capacity checks run under read-only roles in the correct Region. They also verify that no team README still instructs people to create IAM access keys “if SSO is annoying.” Annoyance is not an architecture exception.
During the spike, prefer console and CLI read actions under operator roles. Mutating changes go through pipelines. If a pipeline is down, break-glass CLI use must still log through CloudTrail with a human identity, and a ticket must capture why the pipeline was bypassed. After the spike, review CloudTrail for unexpected Delete* and PutBucketPolicy calls from laptop user agents.
Extended teaching dialogue: intern on day two
An intern asks for production keys to reproduce a bug. The correct mentoring moment is to give them staging SSO access, a synthetic learner, and a redacted log sample. If the bug only appears in production, an operator with MFA performs the read while the intern watches, or you add safer debug instrumentation through a pipeline. Handing production keys to accelerate learning teaches the wrong lesson faster than it teaches AWS.
Extended notes on shell history and shared machines
Classroom AMIs and shared cloud desktops often retain shell history containing exported session tokens. At end of lab, clear history or use ephemeral containers for AWS labs. On macOS and Linux, check permissions of ~/.aws. On Windows, be careful with home directory ACLs on shared jump boxes. Prefer personal laptops with disk encryption and company MDM for real production operator access.
Measuring success for this lesson
You succeed when: (1) every engineer has a named non-default sandbox profile; (2) a Python inventory runs under an assumed role with an account guard; (3) no long-lived human keys remain in the pilot without an expiry ticket; (4) CloudTrail shows SSO-assumed roles for daily work; (5) budget alerts exist; (6) the team can explain credential chain order for their SDK. If any checkbox fails, do not proceed to open production network paths in later labs as if identity were solved.