Tutorial · AWS IAM · Secrets management
IAM and least privilege on AWS – roles, policies, conditions, SCPs/RCPs, Access Analyzer and OIDC for GitHub Actions
We clean up permissions in the pierogi shop's AWS account – from "everyone has AdministratorAccess" to least privilege. Identities and roles instead of users, policy evaluation logic, ECS task and Lambda roles in CDK, condition keys, permissions boundaries and ABAC, organization guardrails (SCPs and RCPs), IAM Access Analyzer as a CI gate, and deployments from GitHub Actions through OIDC – with no long-lived keys.
In the pierogi shop's AWS account, three developers, the CI pipeline and two services had one thing in common: the AdministratorAccess policy, granted "just for now, to get things going". "Now" lasted eighteen months. In this tutorial we replace that state with the principle of least privilege: every identity gets exactly what it needs, for as short a time as possible – so that a mistake or a leak has a limited blast radius.
Prerequisites: an AWS account (ideally in AWS Organizations), AWS CLI v2, Node.js 22+ and AWS CDK v2, JSON basics. The tutorials on the scalable portal and S3 bucket security help.
- Deny
- always wins – an explicit deny in any policy
- 0
- long-lived keys – in the target setup: SSO, roles, OIDC
- 1 h
- GitHub Actions deployment session – then the credentials expire
- 90 days
- default unused-access window – Access Analyzer, configurable
Identities: who is who
| Identity | What for | Credentials | Rule |
|---|---|---|---|
| Root account | closing the account, a few billing operations | password + MFA | no access keys; in an organization – centralized root access management (since 2024) |
| Identity Center user | people | SSO, short sessions, MFA | the default way people sign in |
| IAM user | exceptions: legacy tools without role support | long-lived key | avoid; if you must – one purpose, rotation, IP/VPC conditions |
| IAM role | services, CI, cross-account access, federation | temporary (STS) | the basic building block |
| Service-linked role | AWS services working in your account | managed by AWS | you don't edit them, but it's worth knowing they exist |
A role has no password or key – it has a trust policy (who may assume it) and permission policies (what is allowed once assumed). Credentials from sts:AssumeRole expire on their own, so a leak from logs or a memory dump has a limited lifetime.
How AWS makes a decision
By default everything is denied (implicit deny). Access requires an Allow, and a single explicit deny overrides every Allow. The asterisk on the resource policy: within the same account an Allow in a resource policy can be enough even without an identity policy (the details depend on the principal type), while cross-account access needs an Allow on both sides.
| Policy type | Grants permissions? | Example |
|---|---|---|
| Identity policy (managed or inline) | yes | what the API role may do |
| Resource policy | yes | a bucket, queue, KMS key or secret policy |
| Permissions boundary | no – only limits | the ceiling for roles created by teams |
| Session policy | no – only limits | narrowing at AssumeRole time |
| SCP (AWS Organizations) | no – limits identities in accounts | "nobody disables CloudTrail" |
| RCP (AWS Organizations, since 2024) | no – limits access to resources | "our buckets only from our organization" |
Step 1. The application role policy
Permission policy and trust policy of the ECS task role
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "InvoicesReadWrite",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::pierogi-invoices-123456789012/invoices/*"
},
{
"Sid": "InvoicesKeyViaS3Only",
"Effect": "Allow",
"Action": ["kms:Decrypt", "kms:GenerateDataKey"],
"Resource": "arn:aws:kms:eu-central-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",
"Condition": { "StringEquals": { "kms:ViaService": "s3.eu-central-1.amazonaws.com" } }
},
{
"Sid": "EnqueueJobs",
"Effect": "Allow",
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:eu-central-1:123456789012:pierogi-jobs"
},
{
"Sid": "ReadOwnParameters",
"Effect": "Allow",
"Action": "ssm:GetParameter",
"Resource": "arn:aws:ssm:eu-central-1:123456789012:parameter/pierogi/prod/api/*"
}
]
}{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ecs-tasks.amazonaws.com" },
"Action": "sts:AssumeRole",
"Condition": {
"ArnLike": { "aws:SourceArn": "arn:aws:ecs:eu-central-1:123456789012:*" },
"StringEquals": { "aws:SourceAccount": "123456789012" }
}
}
]
}- Specific actions and resources.
s3:GetObjectands3:PutObjectonly oninvoices/*– nos3:*, noDeleteObject, no listing the whole bucket. kms:ViaService– the role can use the key only through S3. Even with stolen credentials, nobody can decrypt anything with it directly through the KMS API.- Parameter Store by path –
/pierogi/prod/api/*, not every parameter in the account. - A trust policy with
aws:SourceAccountandaws:SourceArn– protects against the confused deputy: the ECS service assumes this role only on behalf of tasks from our account and region.
Step 2. Roles in CDK: handy grant* and its price
ECS and Lambda roles with a permissions boundary (AWS CDK)
import { Construct } from 'constructs';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
export interface AppRolesProps {
invoices: s3.IBucket;
jobs: sqs.IQueue;
dbSecret: secretsmanager.ISecret;
boundary: iam.IManagedPolicy;
}
export class AppRoles extends Construct {
constructor(scope: Construct, id: string, props: AppRolesProps) {
super(scope, id);
// Every role created inside this construct gets the permissions boundary.
iam.PermissionsBoundary.of(this).apply(props.boundary);
const task = new ecs.FargateTaskDefinition(this, 'ApiTask', { cpu: 512, memoryLimitMiB: 1024 });
task.addContainer('api', {
image: ecs.ContainerImage.fromRegistry('public.ecr.aws/docker/library/node:24-alpine'),
logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'api' }),
// Injected at start by the ECS agent → GetSecretValue lands on the EXECUTION role.
secrets: { DB_PASSWORD: ecs.Secret.fromSecretsManager(props.dbSecret, 'password') },
});
// The TASK role is what your code gets from the SDK.
// grantReadWrite() would also add s3:DeleteObject*, s3:PutObjectRetention, s3:List*…
// For sensitive data, write the two actions you actually need.
task.taskRole.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['s3:GetObject', 's3:PutObject'],
resources: [props.invoices.arnForObjects('invoices/*')],
}));
props.invoices.encryptionKey?.grant(task.taskRole, 'kms:Decrypt', 'kms:GenerateDataKey');
props.jobs.grantSendMessages(task.taskRole); // SendMessage + GetQueueAttributes + GetQueueUrl
// A Lambda gets its own role – never share one "app role" across services.
const thumbnailer = new lambda.Function(this, 'Thumbnailer', {
runtime: lambda.Runtime.NODEJS_24_X,
handler: 'index.handler',
code: lambda.Code.fromInline('exports.handler = async () => ({ ok: true });'),
});
props.invoices.grantRead(thumbnailer, 'uploads/*');
}
}import { Construct } from 'constructs';
import { Stack } from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
/** The ceiling for every role a product team creates: workload services only, one region, no IAM. */
export function devBoundary(scope: Construct): iam.ManagedPolicy {
const region = Stack.of(scope).region;
return new iam.ManagedPolicy(scope, 'DevBoundary', {
managedPolicyName: 'pierogi-dev-boundary',
statements: [
new iam.PolicyStatement({
sid: 'WorkloadServicesInOurRegion',
actions: [
's3:*', 'sqs:*', 'dynamodb:*', 'logs:*', 'xray:*', 'cloudwatch:PutMetricData',
'secretsmanager:GetSecretValue', 'kms:Decrypt', 'kms:GenerateDataKey',
'ecr:GetAuthorizationToken', 'ecr:BatchGetImage', 'ecr:GetDownloadUrlForLayer',
],
resources: ['*'],
conditions: { StringEquals: { 'aws:RequestedRegion': region } },
}),
],
});
}The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Conditions: the most important keys
- Step 3. GitHub Actions without keys: OIDC
- Step 4. Delegation with permissions boundaries and ABAC
- Step 5. Organization guardrails: SCPs and RCPs
- Step 6. Access Analyzer as a CI gate
- Credential hygiene
- Common mistakes
- Test yourself
- What's next