Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 20 min · revision 3

Identities, roles and least-privilege policies

A worked example: give a worker on a VM and a GitHub Actions deployment exactly the AWS access they need, through roles and short-lived credentials instead of access keys. Write the permissions policy, the two trust policies and the OIDC conditions, then check who you are actually running as.

Contentsand lesson path

What you will learn

  • Grant access through identity roles and short-lived credentials following least privilege, instead of long-lived access keys.

Prerequisites: Networking Basics

01. The problem

An invoice worker runs on an EC2 instance. It reads and writes objects in one bucket, acme-invoices-2026, and does nothing else in AWS. Its code is deployed by a GitHub Actions workflow in the repository acme/app, but only from the main branch. Today both use the same access key, created for an IAM user with broad S3 rights and stored in a .env file and in a repository secret.

The goal: each workload gets its own identity, with only the permissions it uses and credentials that expire on their own, and you can prove which identity a process is running as.

Every AWS API call is authenticated and then authorised by IAM. Two kinds of identity make those calls. Humans should sign in through a central identity provider with MFA, for example IAM Identity Center. Workloads (instances, containers, functions, CI jobs) should use roles. A role has no password and no long-lived key. A trusted principal assumes it, and AWS STS (the Security Token Service) returns temporary credentials: an access key ID, a secret key and a session token. By default these last an hour; the role's maximum session duration, at most 12 hours, caps what a caller may request.

02. Step 1: The permissions policy for the worker

Write down what the worker does, then grant exactly that. Each policy statement has four parts:

  • Effect: Allow or Deny. An explicit Deny in any applicable policy (identity policy, bucket policy, permissions boundary or an organisation's SCP) beats every Allow.
  • Action: the API operations, such as s3:GetObject. Wildcards such as "s3:*" (every S3 action) or "*" (every action in every service) break least privilege.
  • Resource: the ARNs the actions apply to. Object actions apply to object ARNs (bucket/*); bucket actions such as s3:ListBucket apply to the bucket ARN itself.
  • Condition: optional checks at request time, for example that the request used HTTPS (aws:SecureTransport).

The second statement denies any S3 call on this bucket that does not use TLS. It lists both the bucket ARN and the object ARN, so bucket-level calls such as ListBucket over plain HTTP are denied as well. In an identity policy it constrains only this role. To enforce TLS for every caller, put the same Deny in the bucket policy with "Principal": "*".

JSON · worker-policy.json (permissions policy)
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadWriteInvoiceObjects",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::acme-invoices-2026/*"
    },
    {
      "Sid": "DenyPlainHttp",
      "Effect": "Deny",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::acme-invoices-2026",
        "arn:aws:s3:::acme-invoices-2026/*"
      ],
      "Condition": {"Bool": {"aws:SecureTransport": "false"}}
    }
  ]
}

Note what is missing. There is no s3:ListBucket, so the worker cannot enumerate invoices; a side effect is that reading a key that does not exist returns 403 Access Denied rather than 404, which can confuse debugging. There is no s3:DeleteObject, because the worker never deletes. Before attaching the policy, let IAM Access Analyzer check it for errors and over-broad grants:

Terminal
aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY \
  --policy-document file://worker-policy.json
Illustrative output (no findings means no errors, warnings or suggestions)
{
    "findings": []
}

03. Step 2: A role for the instance

A role has two policies. The permissions policy from step 1 says what the role may do. The trust policy says who may assume it. For an instance, the trusted principal is the EC2 service; you attach the role through an instance profile, and AWS delivers short-lived credentials to the instance through the instance metadata service and replaces them before they expire. AWS SDKs and the CLI find them automatically, so the code needs no keys and no configuration.

Require IMDSv2 on the instance (http_tokens = "required", as the lab 3 probe does). A caller must first obtain a session token with an HTTP PUT carrying a special header, then send it with each request. That stops the common server-side request forgery (SSRF) bug that can only make the server fetch a URL with GET from also fetching the role's credentials. It is a strong mitigation, not a guarantee: code that lets an attacker control the method and headers can still reach the service.

JSON · worker-trust.json (trust policy)
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {"Service": "ec2.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }
  ]
}

On the instance, aws sts get-caller-identity shows which identity the CLI is using. You should see an assumed-role ARN that names the role and, as the session name, the instance ID, for example arn:aws:sts::123456789012:assumed-role/invoice-worker/i-0123456789abcdef0. If you see a user/... ARN instead, a leftover key in environment variables or ~/.aws/credentials is taking precedence; remove it. The lab 3 probe is the same pattern, with the AWS managed policy AmazonSSMManagedInstanceCore as its permissions.

04. Step 3: OIDC federation for the deployment workflow

GitHub Actions can issue each job a signed OpenID Connect (OIDC) token that says which repository, branch or environment and which event started it. Register GitHub as an IAM OIDC identity provider once per account (issuer https://token.actions.githubusercontent.com, audience sts.amazonaws.com). Then write a trust policy that lets that provider assume the deploy role only for tokens with the right audience and subject. The deploy role gets its own narrow permissions policy, for whatever the deployment changes.

The sub condition is the part people get wrong. repo:acme/app:ref:refs/heads/main admits only workflows running on main in that repository. A wildcard such as repo:acme/* admits every branch and every pull-request workflow in every repository of the organisation, and a trust policy with no sub condition at all would trust workflows in repositories you do not control. Use StringEquals, list exact subjects, and prefer a GitHub environment with required reviewers for production deploys (the subject then becomes repo:acme/app:environment:production).

Check which subject format your repository uses. acme/app is an older repository, so its subject holds only names. Repositories created after 15 July 2026, and repositories whose owner opted in, use the immutable format, which adds the owner and repository IDs: repo:acme@123456/app@456789:ref:refs/heads/main. The IDs stop a new owner of a recycled name from matching your policy. A policy written in one format does not match tokens in the other, so the deploy fails with Not authorized to perform sts:AssumeRoleWithWebIdentity. Check which format the repository uses, in its OIDC settings or in GitHub's OIDC reference, before you write the condition.

JSON · deploy-trust.json (trust policy for the deploy role)
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Principal": {"Federated":
      "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"},
    "Condition": {"StringEquals": {
      "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
      "token.actions.githubusercontent.com:sub": "repo:acme/app:ref:refs/heads/main"
    }}
  }]
}

In the workflow, id-token: write lets the job request the token, and the official action exchanges it for role credentials. The action is pinned to the full commit SHA of its v6.3.1 tag, so a moved tag cannot change what runs. In your repository, write that step as one line, - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1, so that update tools such as Dependabot and Renovate can raise the SHA and the version comment together. The last step prints the identity, which is the evidence that federation, not a stored key, supplied the credentials.

YAML · .github/workflows/deploy.yml
name: deploy
on:
  push:
    branches: [main]
permissions:
  id-token: write # lets the job request an OIDC token
  contents: read
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      # aws-actions/configure-aws-credentials v6.3.1, pinned by commit.
      # Split over two lines only to fit this page: in a real workflow keep
      # uses:, the SHA and a "# v6.3.1" comment on one line, because
      # Dependabot and Renovate update the version comment only there.
      - uses:
          aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5
        with:
          role-to-assume: arn:aws:iam::123456789012:role/deploy-from-main
          aws-region: ap-southeast-1
      - run: aws sts get-caller-identity
Illustrative output of the last step (account and IDs are placeholders)
{
    "UserId": "AROAEXAMPLEDEPLOYID:GitHubActions",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/deploy-from-main/GitHubActions"
}

05. Check your understanding

Practice check · 3 questions

Roles, trust policies and policy evaluation

Spot the access each policy really grants.

Q1. A deploy role's trust policy uses `StringLike` with `token.actions.githubusercontent.com:sub` set to `repo:acme/*`, plus the correct audience. The acme repositories use the name-only subject format. Who can assume the role?
Q2. A role's policy denies `s3:*` on `arn:aws:s3:::reports/*` when `aws:SecureTransport` is false, and separately allows `s3:ListBucket` on the bucket and `s3:GetObject` on its objects. Which plain-HTTP request still succeeds?
Q3. A role allows `ec2:*` on `*`. The organisation attaches an SCP to the account that denies `ec2:RunInstances` outside two regions. The role calls `RunInstances` in a third region. What happens?
Practice only: not graded, not saved, not evidence.

06. Apply it

For the skill practice, give the web service its own role:

  • List every AWS call the service makes and write a permissions policy with only those actions and ARNs. Run aws accessanalyzer validate-policy on it.
  • Attach the role to the instance or task (an instance profile, or an ECS task role), require IMDSv2 on instances, and record aws sts get-caller-identity from inside the workload as evidence.
  • Deploy from CI with OIDC and an exact sub condition; delete any access key the project used before.
  • Prove one denial: try an action the role should not have (for example s3:DeleteObject) and keep the AccessDenied error as evidence.
  • Optionally, after a week of use, compare the policy with IAM Access Analyzer's unused-access findings and remove what is never used.

07. Review prompt

Without looking back, explain the difference between a trust policy and a permissions policy, and write the two conditions a GitHub OIDC trust policy needs. Say why the TLS Deny must list the bucket ARN as well as bucket/*, how IMDSv2 changes what an SSRF bug can reach, and which command shows the identity a process is really using.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check