Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Get Temporary AWS Credentials with STS Step by Step

Lab time: create a role that only S3-reads one bucket, AssumeRole from the CLI, prove it works with the session token, then delete everything so nothing keeps costing or leaking.

In this chapter

  • Create a trust + S3 read role
  • AssumeRole with AWS CLI
  • Export temporary credentials
  • Prove allow and deny
  • Cleanup roles and bucket

Everyday example before the lab

Why this lab matters

In a fictional library, a visiting helper receives a pass to read one shelf for one shift. The librarian’s master access does not travel with that pass. This lab follows the same separation: the original identity obtains a short session, and the session reads one practice bucket. Check the session identity before interpreting a successful file read, because a read performed with the wrong identity proves the wrong thing.

1. Lab: click by click

Region ap-south-1 (Mumbai). You need an IAM principal that can create roles and call sts:AssumeRole (your student admin or Identity Center set). Replace ACCOUNT, BUCKET and names.

A. Bucket and policy

Use two harmless sample objects so the intended access can be checked directly. The test role should be allowed to read the object named by its policy. Keep another object under a different, out-of-scope key. Write down these keys, the role ARN and the expected Allowed or Denied result before assuming the role.

Make both calls after the assume-role and identity check below, with the same temporary session. Compare output with the two expected results. An empty read or a missing key cannot by itself establish a permissions boundary, so use two known existing test objects under the approved setup and interpret the precise error returned. If both reads succeed, review other attached access for that session before widening any policy or writing further objects.

  1. S3 → Create bucket yourname-sts-lab (ap-south-1), Block Public Access ON. Upload hello.txt with body ok.
  2. IAM → Policies → Create → JSON:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": "arn:aws:s3:::BUCKET"
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": "arn:aws:s3:::BUCKET/*"
    }
  ]
}
  1. Name: lab-sts-s3-read. Create.

B. Role with trust to your user

  1. IAM → Roles → Create role → Custom trust policy (or Another AWS account with your account id).
  2. Trust JSON (replace ACCOUNT and USER):
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::ACCOUNT:user/USER" },
    "Action": "sts:AssumeRole"
  }]
}
  1. Attach lab-sts-s3-read only. Role name: lab-sts-assumer. Max session 1 hour is fine.
  2. If you use Identity Center, Principal can be your permission-set role ARN instead of an IAM user — same idea.

C. AssumeRole and prove

Use a fresh lab shell for the temporary session so it has a clear beginning and end. First use the existing identity check to confirm the intended source account. Then make the AssumeRole request. The ARN names the target role and the session name helps identify this run in logs. Keep the returned credential values private and use all three together with the session token.

Call the existing identity check again from that shell before testing S3. Expect an assumed-role ARN for the intended lab role. If the identity is wrong, correct the credential selection before changing the bucket. Once it is right, try the allowed lab object and a harmless object you intentionally kept outside the approved scope. Expect success for the first and a denial for the second. This shows both the capability and its boundary.

  1. In CloudShell or your laptop CLI (as the trusted principal):
aws sts get-caller-identity
aws sts assume-role \
  --role-arn arn:aws:iam::ACCOUNT:role/lab-sts-assumer \
  --role-session-name ravi-lab \
  --duration-seconds 900
# Copy AccessKeyId, SecretAccessKey, SessionToken from Credentials
  1. Export (Linux/macOS), then test:
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_SESSION_TOKEN=...
aws sts get-caller-identity
# Arn should mention assumed-role/lab-sts-assumer/ravi-lab
aws s3 cp s3://BUCKET/hello.txt -
# expect: ok
# aws s3 ls s3://some-other-bucket   # should be AccessDenied
  1. Unset when done: unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN.

Cleanup

  1. Delete role lab-sts-assumer (detach policy first if the console asks).
  2. Delete policy lab-sts-s3-read.
  3. Empty and delete bucket yourname-sts-lab.
  4. Confirm your shell no longer exports the temp keys.

Ravindra Bagale's Tip

If AssumeRole fails with AccessDenied, check both sides: your user needs iam permission to assume, and the role trust Principal must match your ARN exactly.

Common errors: cause and safe next check

A previously working temporary session now fails

Compare its Expiration with the current time locally. Manually exported values do not renew themselves. Use a new authorized session through the approved source identity; never extend a leak window by replacing temporary access with a permanent admin key.

A requested long session is rejected

AssumeRole accepts at least 900 seconds and at most the role’s configured maximum. When one role assumes another, role chaining has a one-hour maximum even if the target role allows longer sessions. Check the caller type and requested duration rather than changing trust to everyone.

AssumeRole succeeded but S3 read is denied

Successful assumption proves that a session was issued, not that every S3 operation is allowed. Check the active role identity, exact object name and applicable permissions. A session policy can further restrict role permissions; adding it cannot grant rights missing from the role.

Practical questions and full answers

Will the original user’s wider rights follow me into this role?

No. Requests signed with the new role-session credentials use the role session’s effective permissions. The original identity is used to obtain that session, not as a second bundle of rights added to every S3 request.

Does an assumed-role ARN contain the secret key?

No. The ARN identifies the role session; it is not the secret access key or session token. Inspect it locally to confirm which role made the request, and keep all actual credential values out of screenshots and shared lab notes.

Does clearing exports in one terminal finish every session?

No. Removing those environment variables changes credential selection in that shell. Other shells or processes can still have their own credentials. It does not revoke an already issued session; keep local shell housekeeping separate from account-side incident handling.

2. Interview angles

Q. Why RoleSessionName?

Shows up in CloudTrail for audit.

Q. Why DurationSeconds 900?

Short lab sessions reduce leak window.

Q. Missing SessionToken?

Calls fail — STS creds need all three.

Q. Trust Principal wrong?

AssumeRole AccessDenied even if permissions policy is perfect.

Try at home

  1. Add an ExternalId condition to trust and pass --external-id on AssumeRole.
  2. Next: Identity Center (SSO) for humans instead of long-lived users.

In short

  1. Create role with trust + tight permissions.
  2. AssumeRole → export three values → call APIs.
  3. Prove allow on lab bucket and deny elsewhere.
  4. Delete role, policy and bucket after the lab.

Keep the lab session isolated from your normal profile

First check caller identity with the source profile, then use named role/profile configuration or a short-lived child shell for the credentials. Check again after assuming and at cleanup. Keep credentials out of shell history, stdout captures and screenshots.

Interview check What if an explicit --profile still seems to select the wrong session?

Inspect credential source and caller identity, and clear stale environment exports in an isolated shell. A profile name by itself is not evidence of which credentials signed the last request.

Reference documentation

Practise this chapter

Interview questions and answers

Why isn’t AssumeRole success enough to finish the lab?

It shows the caller can obtain a session, but it does not prove the session can read the lab object. I would verify the session ARN in a separate shell and check the expected allowed and denied objects under that exact identity.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which check belongs immediately after loading the temporary credentials?

Answer and explanation

B. Run get-caller-identity and confirm the assumed role

Verify the role session actually signs the next request before testing the access it should have.

2. Why use a dedicated shell for the temporary exports?

Answer and explanation

B. To keep the temporary credentials from changing actions in your usual shell

Scope the exports to a lab environment and close it when the test ends.

3. Which pair demonstrates the role policy’s scope?

Answer and explanation

C. An allowed sample read and a denied out-of-scope read

A positive and a negative check show both the intended capability and its limit.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Jakarta Batik is a handicrafts business in Jakarta. Siti Rahmawati looks after its IT and cloud work. They count money in IDR and run their AWS resources in the ap-southeast-3 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 10

Easy Check who you are logged in as

Always confirm the account and identity before running changes.

Show the account ID and ARN of the identity your CLI is using.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy How many addresses in a /16?

Picking a VPC size needs this count.

Jakarta Batik plans the VPC 10.115.0.0/16. How many IP addresses does it hold in total?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Assume a role

AssumeRole gives you short-lived keys for another role, often in another account.

Assume role arn:aws:iam::129471578432:role/Auditor with session name siti-audit.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Decode an "access denied" message

Some errors come encoded; decoding shows exactly which policy blocked you.

Decode the authorization message stored in the shell variable $MSG.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Trust policy for an EC2 role

The trust policy says WHO may take the role.

Write a trust policy that lets ec2.amazonaws.com assume the role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Trust policy for an ECS task role

The trust policy says WHO may take the role.

Write a trust policy that lets ecs-tasks.amazonaws.com assume the role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Trust policy for a Lambda role

The trust policy says WHO may take the role.

Write a trust policy that lets lambda.amazonaws.com assume the role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Let another account assume a role

Cross-account roles are safer than sharing access keys.

Write a trust policy that lets account 111122223333 assume this role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Assume a role for 15 minutes

Shorter sessions lower the risk if keys leak.

Assume arn:aws:iam::129471578432:role/Deployer with session name deploy-job for 900 seconds.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Get a session token with MFA

Some actions need MFA. get-session-token returns keys that carry MFA proof.

Get a session token using MFA device arn:aws:iam::129471578432:mfa/siti and the code 123456.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Lab: role with tight trust. A permissions policy that looks perfect still fails AssumeRole if trust Principal is wrong. Create a customer-managed S3-read policy for one lab bucket, a role whose trust Principal is your IAM user (or role), then attach the policy. IAM → create policy → create role (custom trust) → attach policy → note the role ARN. aws sts assume-role --role-arn … succeeds; a wrong account Principal returns AccessDenied.
Revision card: Lab: role with tight trust · Download PNG · Open card page
Revision card: AssumeRole and prove access. Without a prove step, you do not know if the session is the role or still your admin user. Export the three STS values, call get-caller-identity, list the lab bucket (allow), then try a bucket outside the policy (deny). eval or export the credentials JSON fields, then aws s3 ls on the lab bucket and on an unrelated bucket. Caller identity ARN contains assumed-role; lab bucket lists; other bucket is AccessDenied.
Revision card: AssumeRole and prove access · Download PNG · Open card page
Revision card: Clean up the STS lab. Forgotten roles and buckets clutter the account and confuse the next lab. Unset the temporary env vars, detach/delete the lab role and customer policy, empty and delete the lab bucket the same day. unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN; delete role; delete policy; delete bucket. get-caller-identity is your normal user again; IAM Roles list no longer shows the lab role.
Revision card: Clean up the STS lab · Download PNG · Open card page
Interview card: Why set RoleSessionName and short duration?. RoleSessionName shows up in CloudTrail so you can audit which lab or person assumed the role. Short DurationSeconds (e.g. 900) shrinks the leak window. A vague name like “temp” and a 12-hour duration make incidents harder to trace and worse when a laptop is stolen. aws sts assume-role --role-session-name ravindra-lab1 --duration-seconds 900 …
Interview card: Why set RoleSessionName and short duration? · Download PNG · Open card page
Interview card: AssumeRole AccessDenied but policy looks fine?. Check the role trust policy Principal and Conditions first. Permissions policy is evaluated after a successful assume. Also confirm your caller identity is allowed sts:AssumeRole and that ExternalId/MFA conditions match what you pass on the CLI. Fix Principal to your user/role ARN, retry assume-role, then test S3 with the session token.
Interview card: AssumeRole AccessDenied but policy looks fine? · Download PNG · Open card page

More cards: Ravi Sir's Cards.