
Course 4 Β· Security, governance and monitoring
Badges, safe secrets and a smoke detector
π― By the end of today
- You can explain why humans log in through SSO and machines use roles, and spot an IAM policy that grants too much.
- You can explain envelope encryption and KMS to a teammate in two minutes.
- You can store a secret in Secrets Manager and have your container receive it at start, with no password in your scripts or task definition.
- You can draw a multi-account layout for a company and say where SCPs, logs and backups live.
- You can wire a CloudWatch alarm to a pager through SNS, fire it on purpose, and prove a least-privilege role gets AccessDenied (project M3).
ποΈ The plan for today
| Time | What | Where |
|---|---|---|
| 0:00 (10 min) | Recap: what's still wrong after M2 | Lecture |
| 0:10 (35 min) | IAM deeper, least privilege, roles vs users, Zero Trust, encryption, KMS, secrets | Lecture |
| 0:45 (20 min) | CloudTrail, CloudWatch, alarms, budgets | Lecture |
| 1:05 (15 min) | Multi-account and Organizations (paper), running it: from MCO to SRE | Lecture |
| 1:20 (10 min) | Break | |
| 1:30 (40 min) | Project M3, steps 1 to 3: the secret, the execution role, logs | Project |
| 2:10 (30 min) | Step 4: the pager | Project |
| 2:40 (35 min) | Step 5: the deployer role and its AccessDenied | Project |
| 3:15 (15 min) | Step 6: check M3, commit. Each group picks its EPITA idea | Project |
| 3:30 | Buffer. Not done? Course 5's project block opens with 15 minutes of catch-up |
πͺͺ IAM, one level deeper
Most cloud breaches start with a leaked key that still worked.
In first course, you met IAM (Identity and Access Management) as users, groups and policies, here's the version you'll meet at work.
An IAM user has long-lived credentials, a password for the console and access keys (AKIA...) for the CLI (command line interface).
- Those keys never expire on their own.
- They end up on laptops, in CI (continuous integration, the tools that build your code) variables and in public GitHub repos, where bots find them within minutes.
An IAM role has no credentials of its own.
Something it trusts (a person, an EC2 instance, a Lambda function, another account) assumes the role and gets temporary credentials from STS (Security Token Service).
They last from 15 minutes to a few hours, then they're worthless, like a visitor badge.
π Want more? IAM user vs IAM role, side by side
| IAM user | IAM role | |
|---|---|---|
| Credentials | A password and keys that last forever | Temporary, handed out by STS each time |
| Who uses it | One person or one script, forever | Anyone or anything the role trusts |
| If credentials leak | They work until someone notices and deletes them | They expire on their own, usually within the hour |
| Typical use today | Emergency access, old tools | Everything else |
Humans sign in through SSO (Single Sign-On, one company login backed by the company directory) and land in a role, machines get a role attached (an instance profile for EC2, an execution role for Lambda).
Nobody should hold an access key that doesn't expire.
You've done this since course 1.
Run aws sts get-caller-identity and look at the ARN (Amazon Resource Name, the unique ID of anything in AWS). On Floci it says root: the keys in your env.sh can do everything.
Today you create a role and assume it, so your terminal holds temporary credentials with an assumed-role/... ARN, the way real companies work. Your containers already do the same through their execution role.
π Want more? How an instance gets its credentials
Temporary credentials from STS come in three parts, an access key, a secret key and a session token.
An EC2 instance asks its metadata service (an address only the instance itself can reach) for them, and the SDK (the AWS library in your code) or the CLI refreshes them before they expire.
You never copy a key onto the machine.
Least privilege, before and after
Least privilege means a role gets the permissions its job needs and nothing more, like a cashier's badge that opens the till and not the vault.
This is the policy many people write for the Puff API on their first day, because it works:
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": "ssm:*", "Resource": "*" },
{ "Effect": "Allow", "Action": "kms:*", "Resource": "*" }
]
}The * means everything.
If someone gets to run code on that instance, they can read and delete every parameter in the account, and decrypt anything KMS lets them touch.
This version does the same job for Puff:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ssm:GetParameter",
"Resource": "arn:aws:ssm:us-east-1:123456789012:parameter/puff/db/*"
},
{
"Effect": "Allow",
"Action": "kms:Decrypt",
"Resource": "*",
"Condition": { "StringEquals": { "kms:ViaService": "ssm.us-east-1.amazonaws.com" } }
}
]
}It has one read action, limited to the /puff/db/ path, and decryption only works when the request comes through Parameter Store.
A hacked app can read the database password (it needs it anyway) and nothing else.
How AWS decides: explicit deny wins
Every time anyone calls AWS, it checks every policy that applies, in three steps:
- It starts from deny, if nothing allows the action it's refused (the "implicit deny").
- If any policy that applies says
"Effect": "Deny"for this action, it's refused, and nothing can override that. - Otherwise, if a policy allows it and every guardrail like an SCP allows it too, it goes through.
It's like a nightclub, you need your name on the guest list, but if you're on the banned list no guest list helps you.
π Want more? Which policies get checked, with an example
Example: a developer has AdministratorAccess, and the company's SCP denies cloudtrail:StopLogging. The developer can do almost anything, but stopping the audit trail fails with AccessDenied, because the explicit deny in the SCP beats the allow in the admin policy.
For each call, AWS gathers the caller's identity policies, the resource's own policy (an S3 bucket policy, a KMS key policy), any SCP from the organization and any permission boundary (a cap an admin can put on a role). All of them go through those three steps together.
π‘οΈ Zero Trust, applied to Puff
Attackers get in eventually, so you want the damage to stop at the first door.
The old model puts a strong wall around the network and trusts everyone inside.
Attackers get in anyway (a phished laptop, a leaked VPN password), and then they're trusted too.
Zero Trust drops the idea that being on the network means anything, like an office where every door checks your badge, even the ones deep inside.
Puff already has some of this, and today's hands-on adds the rest.
π Want more? Zero Trust, piece by piece in your Puff
- Never trust the network, a request from a private subnet isn't safe because of where it came from.
- Verify every request, each call proves who's making it and gets checked against policy.
- Use short-lived credentials, whatever leaks should expire before it's useful.
- Apply least privilege, so a verified identity only reaches what it needs.
| Principle | Where it shows up in your Puff |
|---|---|
| Never trust the network | The database lives in a private subnet and still requires a password, and db-sg only lets in traffic from app-sg, not from "anything in the VPC" |
| Verify every request | Every AWS call is signed with the caller's credentials and checked by IAM, including the instance reading its own password |
| Short-lived credentials | The container gets fresh credentials from its role, with no access key on disk |
| No permanent way in | Today you remove SSH and port 22, and you reach the machine through Session Manager, which checks you with IAM and records the session |
π Federation and Amazon Cognito
Nobody wants a separate password for every tool, and you don't want to store your app users' passwords yourself.
Federation means AWS trusts someone else to say who you are, like a hotel that accepts your passport instead of issuing its own ID card.
- Your company's login system (Google Workspace, Okta, Microsoft Entra ID) checks your password and MFA (multi-factor authentication, the code on your phone).
- Then it hands AWS a signed note saying "this is Alice, she's in group
platform". - AWS maps that group to a role and never sees her password.
That covers your employees.
For your customers, the people who sign up to your app, use Amazon Cognito, which has two pieces that people mix up:
π Want more? Cognito for your app, SAML and OpenID Connect
Example: if your app needed accounts, the frontend would send users to a Cognito login page and attach the returned token to each POST /api/messages, and the API would read the author from the verified token instead of trusting the JSON.
The "signed note" in federation follows a standard: SAML (Security Assertion Markup Language, older, XML) or OpenID Connect (newer, built on JWT). Both let the login system vouch for you with a signature AWS can verify, without ever sharing your password.
π Encryption at rest and in transit
Data gets stolen in two places, on the wire while it travels and on the disk where it's stored, so you protect both.
In transit means the bytes moving across a network are encrypted, almost always with TLS (Transport Layer Security, the "S" in HTTPS), like a sealed envelope instead of a postcard.
Puff stays on plain HTTP because the sandbox has no domain to issue a certificate for, so say so in your project justification.
At rest means data on disk is encrypted, so a stolen disk or snapshot is unreadable.
On AWS it's mostly a checkbox backed by KMS, with one catch for databases.
π Want more? Encryption at rest, service by service
| Service | At rest |
|---|---|
| S3 | New files are encrypted by default, you can switch to your own KMS key |
| EBS (the disks of EC2) | Per disk, or turn on "encryption by default" for the whole Region |
| RDS | Chosen when you create the database, can't be switched on later |
| Parameter Store | SecureString parameters are encrypted with a KMS key |
π Want more? TLS hop by hop
Browser to ALB (your Application Load Balancer) is HTTPS with a certificate from AWS Certificate Manager, ALB to API can be encrypted again if the rules require it, and API to PostgreSQL can use TLS too (sslmode=require).
ποΈ KMS and envelope encryption, plainly
If your encryption key sits in a config file, whoever reads the file can read your data.
AWS KMS (Key Management Service) keeps encryption keys inside tamper-proof hardware you never see, and the key never leaves KMS.
You ask KMS to use the key for you, and every request is checked by IAM and the key's own policy, then logged in CloudTrail.
KMS only encrypts small things directly (up to 4 KB), so for real data AWS uses envelope encryption:
- Your service asks KMS for a data key, and KMS returns it twice, once in plaintext and once encrypted under your KMS key.
- Your service encrypts the data locally with the plaintext data key (fast, any size), then throws that key away.
- It stores the encrypted data key right next to the encrypted data.
- To read the data later, it sends the encrypted data key to KMS, KMS checks permissions and returns the plaintext data key, then the service decrypts the data and throws the key away again.
It works like a building where every office has its own key and all the office keys sit in one safe at reception, and the receptionist (KMS) checks your badge and writes down every visit.
π Want more? The three kinds of KMS keys
- AWS owned keys are invisible to you.
- AWS managed keys (
aws/ssm,aws/rds,aws/ebs) are created for you per service, free, rotated automatically, but you can't edit their policy or share them with another account. - Customer managed keys are yours, you write the key policy, you can disable them, share them across accounts and schedule their deletion.
That last point matters for backups: if you want to copy encrypted snapshots into a separate backup account, you need a customer managed key, because the AWS managed one can't be used by another account.
π€« Secrets management
A secret is anything that grants access, like a database password, an API token or a signing key.
These rules hold everywhere:
- never in Git,
- never in user data,
- never in a container image,
- readable only by the identity that needs it.
AWS gives you two places to keep them.
Secrets Manager is built for secrets and can change passwords for you on a schedule, SSM Parameter Store is a free place for settings that can also hold encrypted secrets.
π Want more? Secrets Manager vs Parameter Store, side by side
| Secrets Manager | SSM Parameter Store | |
|---|---|---|
| Built for | Secrets | Settings, including secrets as SecureString |
| Encryption | Always, with KMS | SecureString with KMS, String in clear |
| Changes the password for you on a schedule | Yes, built in for RDS and others | No, you build it yourself |
| Cost | Paid per secret per month, plus API calls | Standard parameters are free |
| Sharing with another account | Yes | Not for standard parameters |
| On Floci, in your project | Available, used in M3 | Available |
Your project uses Secrets Manager, Floci has it.
In a real company, we'd put database credentials in Secrets Manager for the automatic password rotation alone (RDS can even manage its master password there for you), and keep plain settings (feature flags, addresses, the database hostname) in Parameter Store.
ποΈ Governance: many accounts, one organization
If everything lives in one account, one wrong command or one stolen password can reach everything.
An AWS account is the strongest wall AWS has, nothing in one account can touch another unless both sides open a door, like separate apartments.
So companies use one account per environment or per team, and a mistake in staging can't delete production.
AWS Organizations groups those accounts under one management account, and it gives you:
- a single bill,
- a tree of organizational units (OUs, folders of accounts),
- service control policies (SCPs).
An SCP is a rule on an account or a whole OU.
It never grants anything, it sets the maximum anyone in those accounts can do, even the account's root user.
Same logic as the nightclub, an explicit deny in an SCP beats any allow inside the account.
π Want more? Classic SCPs
- Deny any action outside
eu-central-1andeu-west-3(keep data in Europe). - Deny
cloudtrail:StopLoggingandcloudtrail:DeleteTrail(nobody erases the audit trail). - Deny leaving the organization.
- Deny creating IAM users with access keys, so everyone goes through SSO.
The management account sits at the top, with folders of accounts (OUs) under it for Security, Infrastructure, Workloads (split into prod and non-prod) and Sandbox.
Every account sends its CloudTrail logs to a log archive account in Security, and production sends its backups to a separate backup account in Infrastructure.
π Want more? Landing zones
A landing zone is the ready-made starting setup of that organization: the OU structure, a security account, a log archive account that collects CloudTrail from every account, SSO wired to the company directory, baseline SCPs, and a way to create a new account that follows the rules from its first minute.
AWS Control Tower builds one for you, many teams build theirs in Terraform.
βοΈ Design exercise: the account layout for a 200-person startup (15 min)
You've joined a 200-person health startup as its first platform engineer.
About 60 engineers, one main product (web and mobile apps, an API, a PostgreSQL database with customer health data), a data team running analytics, everything in one AWS account today. The CTO asks you for a target layout.
On paper, draw:
- The OU tree and every account, with a one-line purpose for each.
- Where CloudTrail logs go, and who can read them.
- Where backups go, and why there.
- Which SSO groups exist and which accounts each one can reach, with what level of access.
- Two SCPs you'd apply on day one, and on which OU.
There's no single right answer, compare with your neighbour, then open the toggle.
π§ One possible layout (open after you drew yours)
- Management account: Organizations, billing and SSO only. Nobody deploys workloads here.
- Security OU: a log archive account (organization CloudTrail, read by security only, deletion denied by SCP) and a security tooling account.
- Infrastructure OU: a shared networking account, and a backup account that receives encrypted copies through a customer managed KMS key.
- Workloads OU, split into Prod (production, data platform prod) and Non-prod (staging, dev).
- Sandbox OU: one account per team for experiments, with a budget alert and a strict SCP.
- SSO groups such as
engineers(read-only on prod, write on non-prod),platform(admin on infrastructure accounts),data(data platform accounts),oncall(time-boxed admin access to prod for the person on duty). - SCPs on the root: region restriction to your EU Regions, deny stopping CloudTrail, deny leaving the organization.
π΅οΈ CloudTrail: who did what, when
When something changes and nobody remembers doing it, you want a recording.
CloudTrail records the calls made to AWS, like a security camera for your account, who called (user, role, instance), what action, on which resource, from which IP, when, and whether it worked.
Console clicks are API calls too, so they show up.
Event history keeps 90 days of management events (creating, changing, deleting resources) per Region, free, with nothing to set up, and that's what you'll use today.
Example: production's security group suddenly allows 0.0.0.0/0 on port 5432.
CloudTrail tells you it was AuthorizeSecurityGroupIngress, called by the role oncall assumed by a specific SSO user, at 14:32, from the office IP. Now you know who to talk to.
π Want more? Trails and organization trails
A trail sends events to an S3 bucket for as long as you want, and can include data events (S3 file reads, Lambda runs), which are high volume and paid.
In an organization, one organization trail sends every account's events to the log archive account, where nobody in the workload accounts can touch them.
π CloudWatch: metrics, logs, alarms
You want to know your app is down before the first angry message.
Metrics are numbers over time, grouped by service (AWS/EC2, AWS/ApplicationELB, AWS/RDS).
EC2 sends basic metrics every 5 minutes for free, and the ALB sends request counts, response times and error counts every minute.
An alarm watches one metric, like a smoke detector, and sits in one of three states, OK, ALARM or INSUFFICIENT_DATA (not enough numbers yet).
When the state changes it triggers an action, usually an SNS topic, which passes the message on to email, SMS or a chat tool.
The two ALB error metrics are easy to confuse, and it matters today.
A 5xx is an HTTP error code meaning the server side failed.
HTTPCode_Target_5XX_Count | HTTPCode_ELB_5XX_Count | |
|---|---|---|
| Who produced the 5xx | Your Flask app answered with a 500 | The ALB itself, because it got no usable answer |
| Typical cause | A bug, the database refusing connections | Container down, nothing listening, timeouts, no healthy target |
| What it tells you | Your code is failing | Your service is gone |
π Want more? Logs and tuning an alarm
Logs are lines of text, stored in log groups.
Set a retention when you create one, by default logs are kept forever and you pay for all of it.
Docker's awslogs driver can ship your container's output there.
You choose the statistic (average, sum, max), the period (how long each measurement window lasts), how many periods in a row must break the threshold, and what missing data means (is silence good news or bad news?).
An alarm can also watch a math expression combining several metrics. Beyond email, SNS can call a Lambda function that posts to Slack, or a paging tool that phones whoever is on duty.
πΈ Budgets and cost alerts
A forgotten NAT gateway or a leaked key used to mine crypto breaks nothing, it just costs money until the invoice arrives a month later.
With AWS Budgets you set an amount (say 200 USD per month) and get an email when spend crosses 50%, 80% or 100% of it, or when the forecast says it will, like a low-fuel light.
You hear about it on day two instead of at the end of the month.
Every new account should get a budget alert before its first workload.
In a landing zone that's built into account creation, so nobody has to remember.
π Want more? Budget options
You can budget on cost, on usage, or on Savings Plans coverage (a discount you get by committing to spend), and filter by service or tag.
π Running it: from MCO to SRE
Building Puff takes a week. Running it is every day after that.
French IT calls this MCO (maintien en conditions opΓ©rationnelles): keeping a system working, safe and up to date. It's the number one constraint of any IT department.
Running a system is four jobs:
- Watch. Alarms that mean "act now", and nothing else.
- Respond. Someone on call, and a known path from the alert to the fix.
- Repair and learn. Fix it, then write down what happened and change something so it doesn't come back.
- Maintain. Patch, upgrade, rotate secrets, test that backups really restore.
There are two ways to organize it, one per platform:
| Platform 2.0: ITIL | Platform 3.0: DevOps and SRE | |
|---|---|---|
| Who runs it | A separate operations team | The team that builds it ("you build it, you run it") |
| Changes | Approved in a change board meeting | Small, automated, reversible, many per day |
| The promise | An SLA (Service Level Agreement) in a contract | An SLO (Service Level Objective) with an error budget |
| After an incident | Find who made the mistake | Blameless postmortem: why did the system let it happen? |
| Repetitive work | Tickets | Called toil, and automated away on purpose |
π Words for running things
- On call: being the person who gets paged when an alarm fires, for a week at a time, then handing over.
- Runbook: the page an alert links to. What it means, what to check first, how to fix the usual cause.
- SLO and error budget: "99.9% of requests succeed this month". The 0.1% left is a budget: spend it on risky changes, stop changing when it's gone.
- Postmortem: the write-up after an incident: timeline, cause, what we change.
- Toil: manual, repetitive work that grows with the system and teaches nothing.
Key point: your project defense includes a tiny on-call shift. I break something in your Puff, and you have two minutes to find it with the tools from this session.
π§ͺ Project M3: secrets, logs, a pager, and least privilege
Your platform is private now, but your database password sits in clear in your script and your Git history, nobody would know if the app died at 3 a.m., and every one of you is a full admin.
Today you fix the three.
Before you start: M2 green, source env.sh, export GROUP=gXX. Get the new checks:
# Update the check scripts from the course repo
curl -fsSL https://raw.githubusercontent.com/ricoleabricot/puff/main/starter/checks/check.sh -o checks/check.sh
chmod +x checks/check.sh
# Don't commit the cloned app into your repo
echo "app-src/" >> .gitignore# Update the check scripts from the course repo
curl.exe -fsSL https://raw.githubusercontent.com/ricoleabricot/puff/main/starter/checks/check.ps1 -o checks/check.ps1
# Don't commit the cloned app into your repo
Add-Content .gitignore "app-src/"Step 1: a real secret, and rotate the leaked password. The old one is in your Git history forever, so the only fix is to change it.
# A random 24-character password, stored in Secrets Manager
aws secretsmanager create-secret --name $GROUP/db-password \
--secret-string "$(aws secretsmanager get-random-password --password-length 24 \
--exclude-punctuation --query RandomPassword --output text)"
# Its ARN, the address your app will use to ask for it
SECRET_ARN=$(aws secretsmanager describe-secret --secret-id $GROUP/db-password --query ARN --output text)
# Rotate: the database now uses the new password, the old one is dead
aws rds modify-db-instance --db-instance-identifier $GROUP-db2 --apply-immediately \
--master-user-password "$(aws secretsmanager get-secret-value --secret-id $GROUP/db-password \
--query SecretString --output text)"# A random 24-character password, stored in Secrets Manager
$NEWPW = aws secretsmanager get-random-password --password-length 24 `
--exclude-punctuation --query RandomPassword --output text
aws secretsmanager create-secret --name "$env:GROUP/db-password" --secret-string $NEWPW
# Its ARN, the address your app will use to ask for it
$SECRET_ARN = aws secretsmanager describe-secret --secret-id "$env:GROUP/db-password" --query ARN --output text
# Rotate: the database now uses the new password, the old one is dead
aws rds modify-db-instance --db-instance-identifier "$env:GROUP-db2" --apply-immediately `
--master-user-password (aws secretsmanager get-secret-value --secret-id "$env:GROUP/db-password" `
--query SecretString --output text)Now open infra/deploy.sh and replace 'ChangeMe-123' everywhere by:
"$(aws secretsmanager get-secret-value --secret-id $GROUP/db-password --query SecretString --output text)"(aws secretsmanager get-secret-value --secret-id "$env:GROUP/db-password" --query SecretString --output text)Step 2: the execution role. The identity ECS uses to start your container: it may read this one secret and write logs, nothing else.
# Who may use the role: ECS tasks
aws iam create-role --role-name $GROUP-exec-role --assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"Service": "ecs-tasks.amazonaws.com"}, "Action": "sts:AssumeRole"}]
}'
# What the role may do: read your secret, write logs
aws iam put-role-policy --role-name $GROUP-exec-role --policy-name read-secret-write-logs --policy-document "{
\"Version\": \"2012-10-17\",
\"Statement\": [
{\"Effect\": \"Allow\", \"Action\": \"secretsmanager:GetSecretValue\", \"Resource\": \"$SECRET_ARN\"},
{\"Effect\": \"Allow\", \"Action\": [\"logs:CreateLogStream\", \"logs:PutLogEvents\"], \"Resource\": \"*\"}
]
}"
# Keep its ARN for the next step
EXEC_ROLE=$(aws iam get-role --role-name $GROUP-exec-role --query Role.Arn --output text)# Who may use the role: ECS tasks (trust policy written to a file)
@'
{"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"Service": "ecs-tasks.amazonaws.com"}, "Action": "sts:AssumeRole"}]}
'@ | Set-Content exec-trust.json
aws iam create-role --role-name "$env:GROUP-exec-role" --assume-role-policy-document file://exec-trust.json
# What the role may do: read your secret, write logs
@"
{"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "$SECRET_ARN"},
{"Effect": "Allow", "Action": ["logs:CreateLogStream", "logs:PutLogEvents"], "Resource": "*"}
]}
"@ | Set-Content exec-policy.json
aws iam put-role-policy --role-name "$env:GROUP-exec-role" --policy-name read-secret-write-logs `
--policy-document file://exec-policy.json
# Keep its ARN for the next step
$EXEC_ROLE = aws iam get-role --role-name "$env:GROUP-exec-role" --query Role.Arn --output textStep 3: logs, and a new version of your task. Same image, now with the password injected from Secrets Manager and logs sent to CloudWatch.
# A place for the logs
aws logs create-log-group --log-group-name /ecs/$GROUP-app
# The database address, passed as plain config (it's not a secret)
read DB_HOST DB_PORT < <(aws rds describe-db-instances --db-instance-identifier $GROUP-db2 \
--query 'DBInstances[0].Endpoint.[Address,Port]' --output text)
# Revision 2 of the task: secrets by reference, logs to CloudWatch
aws ecs register-task-definition --family $GROUP-app \
--network-mode awsvpc --requires-compatibilities FARGATE --cpu 256 --memory 512 \
--execution-role-arn $EXEC_ROLE \
--container-definitions "[{
\"name\": \"app\", \"image\": \"$REGISTRY/$GROUP-app:v1\", \"essential\": true,
\"portMappings\": [{\"containerPort\": 80}],
\"environment\": [{\"name\": \"DB_HOST\", \"value\": \"$DB_HOST\"}, {\"name\": \"DB_PORT\", \"value\": \"$DB_PORT\"}],
\"secrets\": [{\"name\": \"DB_PASSWORD\", \"valueFrom\": \"$SECRET_ARN\"}],
\"logConfiguration\": {\"logDriver\": \"awslogs\", \"options\": {
\"awslogs-group\": \"/ecs/$GROUP-app\", \"awslogs-region\": \"us-east-1\", \"awslogs-stream-prefix\": \"app\"}}
}]"
# Roll the service to the new revision
aws ecs update-service --cluster $GROUP --service $GROUP-app2 --task-definition $GROUP-app
# A minute later: your app's logs, and what anyone reading the task definition sees
aws logs tail /ecs/$GROUP-app --since 10m
aws ecs describe-task-definition --task-definition $GROUP-app \
--query 'taskDefinition.containerDefinitions[0].secrets'# A place for the logs
aws logs create-log-group --log-group-name "/ecs/$env:GROUP-app"
# The database address, passed as plain config (it's not a secret)
$DB_HOST, $DB_PORT = (aws rds describe-db-instances --db-instance-identifier "$env:GROUP-db2" `
--query 'DBInstances[0].Endpoint.[Address,Port]' --output text) -split '\s+'
# Revision 2 of the task: secrets by reference, logs to CloudWatch (written to a file)
@"
[{
"name": "app", "image": "$env:REGISTRY/$env:GROUP-app:v1", "essential": true,
"portMappings": [{"containerPort": 80}],
"environment": [{"name": "DB_HOST", "value": "$DB_HOST"}, {"name": "DB_PORT", "value": "$DB_PORT"}],
"secrets": [{"name": "DB_PASSWORD", "valueFrom": "$SECRET_ARN"}],
"logConfiguration": {"logDriver": "awslogs", "options": {
"awslogs-group": "/ecs/$env:GROUP-app", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "app"}}
}]
"@ | Set-Content task-v2.json
aws ecs register-task-definition --family "$env:GROUP-app" `
--network-mode awsvpc --requires-compatibilities FARGATE --cpu 256 --memory 512 `
--execution-role-arn $EXEC_ROLE --container-definitions file://task-v2.json
# Roll the service to the new revision
aws ecs update-service --cluster $env:GROUP --service "$env:GROUP-app2" --task-definition "$env:GROUP-app"
# A minute later: your app's logs, and what anyone reading the task definition sees
aws logs tail "/ecs/$env:GROUP-app" --since 10m
aws ecs describe-task-definition --task-definition "$env:GROUP-app" `
--query 'taskDefinition.containerDefinitions[0].secrets'The task definition only shows the secret's ARN. The password exists in one place, and only the execution role can read it.
Step 4: the pager. On real AWS the alarm would page your phone. Floci doesn't send emails, so your pager is an SQS queue you read.
# A topic: the alarm's loudspeaker
TOPIC=$(aws sns create-topic --name $GROUP-alerts --query TopicArn --output text)
# Your pager: a queue subscribed to the topic
PAGER=$(aws sqs create-queue --queue-name $GROUP-pager --query QueueUrl --output text)
PAGER_ARN=$(aws sqs get-queue-attributes --queue-url $PAGER --attribute-names QueueArn \
--query Attributes.QueueArn --output text)
aws sns subscribe --topic-arn $TOPIC --protocol sqs --notification-endpoint $PAGER_ARN
# The alarm: 1 error or more in a minute pages you
aws cloudwatch put-metric-alarm --alarm-name $GROUP-errors \
--namespace $GROUP --metric-name Errors --statistic Sum --period 60 --evaluation-periods 1 \
--threshold 1 --comparison-operator GreaterThanOrEqualToThreshold --alarm-actions $TOPIC
# Simulate your app reporting 3 errors
aws cloudwatch put-metric-data --namespace $GROUP --metric-name Errors --value 3
# Within a minute, read your pager and keep the page in NOTES.md
aws sqs receive-message --queue-url $PAGER --query 'Messages[0].Body' --output text | tee -a NOTES.md# A topic: the alarm's loudspeaker
$TOPIC = aws sns create-topic --name "$env:GROUP-alerts" --query TopicArn --output text
# Your pager: a queue subscribed to the topic
$PAGER = aws sqs create-queue --queue-name "$env:GROUP-pager" --query QueueUrl --output text
$PAGER_ARN = aws sqs get-queue-attributes --queue-url $PAGER --attribute-names QueueArn `
--query Attributes.QueueArn --output text
aws sns subscribe --topic-arn $TOPIC --protocol sqs --notification-endpoint $PAGER_ARN
# The alarm: 1 error or more in a minute pages you
aws cloudwatch put-metric-alarm --alarm-name "$env:GROUP-errors" `
--namespace $env:GROUP --metric-name Errors --statistic Sum --period 60 --evaluation-periods 1 `
--threshold 1 --comparison-operator GreaterThanOrEqualToThreshold --alarm-actions $TOPIC
# Simulate your app reporting 3 errors
aws cloudwatch put-metric-data --namespace $env:GROUP --metric-name Errors --value 3
# Within a minute, read your pager and keep the page in NOTES.md
$r = aws sqs receive-message --queue-url $PAGER --query 'Messages[0].Body' --output text
$r; $r | Add-Content NOTES.mdEmpty? Wait 30 seconds and read again. In a real app, the code itself would publish this metric, or a log filter would count error lines.
Step 5: least privilege, a deployer role. Today you're all full admins. A deploy only needs to update one service.
# Who may become the deployer: people of this account
aws iam create-role --role-name $GROUP-deployer --assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::000000000000:root"}, "Action": "sts:AssumeRole"}]
}'
# What the deployer may do: update your service, register task versions, read logs, nothing else
aws iam put-role-policy --role-name $GROUP-deployer --policy-name deploy-only --policy-document "{
\"Version\": \"2012-10-17\",
\"Statement\": [
{\"Effect\": \"Allow\", \"Action\": [\"ecs:DescribeServices\", \"ecs:UpdateService\"],
\"Resource\": \"arn:aws:ecs:us-east-1:000000000000:service/$GROUP/$GROUP-app2\"},
{\"Effect\": \"Allow\", \"Action\": [\"ecs:RegisterTaskDefinition\", \"ecs:DescribeTaskDefinition\",
\"logs:GetLogEvents\", \"logs:FilterLogEvents\", \"logs:DescribeLogStreams\"], \"Resource\": \"*\"},
{\"Effect\": \"Allow\", \"Action\": \"iam:PassRole\", \"Resource\": \"$EXEC_ROLE\"}
]
}"
# Become the deployer for this terminal: temporary credentials, valid one hour
read DK DS DT < <(aws sts assume-role --role-arn arn:aws:iam::000000000000:role/$GROUP-deployer \
--role-session-name $USER --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text)
export AWS_ACCESS_KEY_ID=$DK AWS_SECRET_ACCESS_KEY=$DS AWS_SESSION_TOKEN=$DT
aws sts get-caller-identity
# Allowed: scale your service
aws ecs update-service --cluster $GROUP --service $GROUP-app2 --desired-count 1 --query service.desiredCount
# Denied: delete the database. Keep the proof
echo "## deployer proof" >> NOTES.md
aws rds delete-db-instance --db-instance-identifier $GROUP-db2 --skip-final-snapshot 2>&1 | tee -a NOTES.md
# Back to your admin keys
unset AWS_SESSION_TOKEN && source env.sh# Who may become the deployer: people of this account (trust policy in a file)
@'
{"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::000000000000:root"}, "Action": "sts:AssumeRole"}]}
'@ | Set-Content deployer-trust.json
aws iam create-role --role-name "$env:GROUP-deployer" --assume-role-policy-document file://deployer-trust.json
# What the deployer may do: update your service, register task versions, read logs, nothing else
@"
{"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["ecs:DescribeServices", "ecs:UpdateService"],
"Resource": "arn:aws:ecs:us-east-1:000000000000:service/$env:GROUP/$env:GROUP-app2"},
{"Effect": "Allow", "Action": ["ecs:RegisterTaskDefinition", "ecs:DescribeTaskDefinition",
"logs:GetLogEvents", "logs:FilterLogEvents", "logs:DescribeLogStreams"], "Resource": "*"},
{"Effect": "Allow", "Action": "iam:PassRole", "Resource": "$EXEC_ROLE"}
]}
"@ | Set-Content deployer-policy.json
aws iam put-role-policy --role-name "$env:GROUP-deployer" --policy-name deploy-only `
--policy-document file://deployer-policy.json
# Become the deployer for this window: temporary credentials, valid one hour
$DK, $DS, $DT = (aws sts assume-role --role-arn "arn:aws:iam::000000000000:role/$env:GROUP-deployer" `
--role-session-name $env:USERNAME --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text) -split '\s+'
$env:AWS_ACCESS_KEY_ID = $DK; $env:AWS_SECRET_ACCESS_KEY = $DS; $env:AWS_SESSION_TOKEN = $DT
aws sts get-caller-identity
# Allowed: scale your service
aws ecs update-service --cluster $env:GROUP --service "$env:GROUP-app2" --desired-count 1 --query service.desiredCount
# Denied: delete the database. Keep the proof
Add-Content NOTES.md "## deployer proof"
$r = aws rds delete-db-instance --db-instance-identifier "$env:GROUP-db2" --skip-final-snapshot 2>&1 | Out-String
$r; $r | Add-Content NOTES.md
# Back to your admin keys
. .\env.ps1Step 6: check, commit, push.
./checks/check.sh M3 | tee -a NOTES.md
git add -A
git commit -m "M3"
git push$r = .\checks\check.ps1 M3
$r; $r | Add-Content NOTES.md
git add -A
git commit -m "M3"
git pushπ§― If it doesn't work
- The service doesn't start after step 3:
aws ecs describe-services --cluster $GROUP --services $GROUP-app2 --query 'services[0].events[:3]'. Most often the secret ARN or the execution role ARN is empty in your terminal. aws logs tailsays the group doesn't exist: create it first (step 3, first command), then roll the service again.- The pager stays empty: the alarm needs a minute.
aws cloudwatch describe-alarms --alarm-names $GROUP-errors --query 'MetricAlarms[0].StateValue'should say ALARM. Fire it by hand withaws cloudwatch set-alarm-state --alarm-name $GROUP-errors --state-value ALARM --state-reason test. - Everything is AccessDenied: you're still the deployer in this terminal, run
unset AWS_SESSION_TOKEN && source env.sh. check.shsays a password is left:git grep ChangeMeshows where.
πΈ On real AWS
The alarm's topic would have an email or a Slack subscription, and the page would wake someone up.
People wouldn't assume a deployer role with the account's admin keys: they'd sign in through SSO (IAM Identity Center) and pick a role, with temporary credentials, the same assume-role mechanism you just used.
CloudTrail would record every call you made today, including your AccessDenied. On Floci, CloudTrail only records a few S3 and Secrets Manager events, so the "who did what" part stays a lecture topic.
π² Today's quiz
π€ Think about it
- Your API reads the database password at boot and passes it to the container as an environment variable. Who can still see it, and what would you change so they can't?
- An SCP denies
s3:DeleteBucketon the Prod OU. A developer withAdministratorAccessin a prod account tries to delete a bucket. What happens, and why can't the account's admin fix it from inside the account? - You rotated the password in Secrets Manager and RDS, and rolled the service. What happened to the containers that started with the old one, and why did ECS replace them instead of fixing them?
- Why does copying RDS snapshots into a separate backup account protect you against things that encryption alone doesn't?
- Your CPU alarm fired at 3am because a nightly job pushed CPU to 75%, and nobody using your app noticed anything. What would you change?
π‘ Hints
- Think about
docker inspect, the process environment, and who can open a shell in the container. The app could call Secrets Manager itself with boto3 at startup. - Go back to the three steps of how AWS decides, and remember who controls SCPs.
- User data runs once at first boot, so the container keeps the old password until it's replaced. In course 5, with an Auto Scaling group, replacing instances becomes routine.
- Think about who holds the credentials to delete things in production, and about ransomware.
- Symptoms versus causes: did users feel anything?