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
On this page
- The problem
- Step 1: The permissions policy for the worker
- Step 2: A role for the instance
- Step 3: OIDC federation for the deployment workflow
- Check your understanding
- Apply it
- Review prompt
Lessons of Cloud Basics
- What you rent, what you still own, and which service to pick Concept · 25 min
- Lab: a two-tier network with public and private subnets Lab · 30 min
- Identities, roles and least-privilege policies Worked example · 20 min
- Cost as an engineering signal: tags, budgets, rightsizing and teardown Worked example · 20 min
- Lab: automated backups and a timed restore Lab · 25 min
- Check: architecture, permissions and recovery review Knowledge check · 10 questions
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:
AlloworDeny. An explicitDenyin any applicable policy (identity policy, bucket policy, permissions boundary or an organisation's SCP) beats everyAllow. - 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 ass3:ListBucketapply 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": "*".
{
"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:
aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY \
--policy-document file://worker-policy.json{
"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.
{
"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.
{
"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.
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{
"UserId": "AROAEXAMPLEDEPLOYID:GitHubActions",
"Account": "123456789012",
"Arn": "arn:aws:sts::123456789012:assumed-role/deploy-from-main/GitHubActions"
}05. Check your understanding
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-policyon 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-identityfrom inside the workload as evidence. - Deploy from CI with OIDC and an exact
subcondition; 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 theAccessDeniederror 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
- AWS IAM: security best practices
- IAM JSON policy elements: Action
- IAM policy evaluation logic
- Amazon S3 security best practices (aws:SecureTransport)
- IAM: update the maximum session duration for a role
- Amazon EC2: use IMDSv2
- GitHub Docs: configuring OpenID Connect in Amazon Web Services
- GitHub Docs: OpenID Connect reference (immutable subject claims)
- GitHub Docs: about push protection
- aws-actions/configure-aws-credentials
- IAM Access Analyzer policy validation
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.