Notes
The pattern
Every automated check follows the same four steps. Ask an API for the current state. Compare it with a rule, such as no access key older than ninety days. Report whatever breaks the rule to someone who can fix it. And run again tomorrow, because the state will have changed. That loop is policy as code in its simplest form. Once you have written one check, the next ten are small variations on it.
- 1 ask an API for the current state
- 2 compare it with the rule ("no key older than 90 days")
- 3 report what breaks the rule, to someone who can fix it
- 4 run again tomorrow
- this is "policy as code" in its simplest form
Access first
Before any code, decide what the script may do. Give it a dedicated role, not a person's account. Make that role read-only; clouds provide ready-made audit policies for this. Use short-lived credentials from an assumed role or from your pipeline's identity, so there is no long-lived key to leak. And if you later add automatic fixes, give those a separate, narrow role. A checking script that can only read cannot become the incident.
- a dedicated role, not a person's account
- read-only: SecurityAudit or ViewOnlyAccess style policy
- short-lived credentials: an assumed role or OIDC from the pipeline, no stored keys
- separate role for anything that fixes
- every call is logged
Check 1 · Old keys
First check: access keys that should have been rotated. With the AWS library for Python, boto three, you list every user, list each user's access keys, and compute the age of each from its creation date. Anything over ninety days is reported. Notice the paginator. Cloud APIs return results a page at a time, and a script that reads only the first page silently checks the first hundred users and reports that everything is fine.
iam = boto3.client("iam")
now = datetime.now(timezone.utc)
pages = iam.get_paginator("list_users")
for page in pages.paginate():
for u in page["Users"]:
name = u["UserName"]
keys = iam.list_access_keys(
UserName=name)
for k in keys["AccessKeyMetadata"]:
age = (now - k["CreateDate"]).days
if age > 90: report(name, age) Check 2 · Public data
Second check: storage that could be public. For each bucket we read its public access block settings, four switches that together stop a bucket being exposed. If all four are on, the bucket passes. If the settings do not exist at all, the API raises an error, and the script treats that as a failure rather than skipping it. That is fail closed from Part zero, applied to your own tooling: when a check cannot tell, it must not report success.
s3 = boto3.client("s3")
for b in s3.list_buckets()["Buckets"]:
name = b["Name"]
try:
cfg = s3.get_public_access_block(
Bucket=name)[
"PublicAccessBlockConfiguration"]
ok = all(cfg.values())
except ClientError:
ok = False # no block set
if not ok: report(name) Check 3 · Repositories
Third check, on a code platform. Branch protection is what forces a review before code reaches the main branch, which is separation of duties in practice. The script asks the API for the protection settings of each repository's main branch. A 404 answer means none are set, so the repository is reported. Any other error raises an exception. The token comes from the environment, there is a timeout, and the token needs only read access.
H = {"Authorization":
"Bearer " + os.environ["GH_TOKEN"]}
url = f"{API}/repos/{org}/{repo}"
url += "/branches/main/protection"
r = requests.get(url, headers=H,
timeout=10)
if r.status_code == 404:
report(repo, "no protection")
else:
r.raise_for_status() APIs push back
Real APIs push back, and good scripts expect it. Always follow pagination to the last page. Honour rate limits: when the API answers with status four twenty nine, wait as long as it tells you and retry, with a little randomness so parallel jobs do not retry in step. Put a timeout on every call. Distinguish a real no from a could not check. Make the script safe to run twice. And log each run, so you can prove the check happened.
- pagination: always loop until there is no next page
- rate limits: honour HTTP 429 and Retry-After; back off and retry with jitter
- timeouts on every call
- distinguish "no" from "could not check"
- idempotent: safe to run twice
- log each run: what, when, how many
Report it well
A finding that nobody receives never gets fixed. So each one should say what is wrong, where, why it matters, how to fix it and who owns it. Find the owner from resource tags or a service catalogue, and deliver the finding where that owner already works, a ticket queue or a team chat channel. Keep state, so the same finding is not sent again every hour until people mute the channel. And measure how long fixes take; that number tells you if the programme works.
- one finding = what, where, why it matters, how to fix, who owns it
- find the owner from tags or a service catalogue
- send it where the owner works: a ticket, a chat channel
- do not repeat the same alert every hour: track state
- measure time to fix
Fixing automatically
The next temptation is to have the script fix what it finds. That is powerful, and it is also how a script takes down production at three in the morning. Earn it in steps. Report only. Then report with a one-click fix that a person approves. Then fix automatically, but only for low-risk, reversible cases, such as switching on a public access block. Always with a dry-run mode, a list of approved exceptions, a log of every change and a way to undo it.
- step 1: report only step 2: report + a one-click fix for a human
- step 3: fix automatically, for low-risk, reversible cases
- always: --dry-run, an allow list of exceptions, a log of every change, a way to undo
- never auto-delete data
Where it runs
Where the script runs matters. On your laptop it is a habit that ends when you go on holiday. As a scheduled job, in a pipeline, a serverless function or cron, it is a control. Better still, trigger it on events, so a new bucket is checked seconds after it is created. Keep the code in git with review and tests like any other software. And monitor the monitor: alert when the job fails or silently stops running, because a check that died looks exactly like good news.
- on a schedule: a CI workflow, a serverless function, a cron job
- or on an event: "bucket created" triggers the check
- code in git, reviewed, tested
- secrets from the platform, never in the repo
- alert if the job itself fails or stops running
Build or buy
Before writing your own, know what exists. Prowler and ScoutSuite run hundreds of ready-made cloud checks for free. Steampipe lets you query cloud APIs using SQL. Cloud Custodian expresses rules with actions. Each cloud has a native policy service, and commercial platforms such as Wiz go much further. So why learn to write checks? Because every company has rules that are its own, and because you cannot judge or extend these tools until you understand what they do underneath.
- Prowler, ScoutSuite: hundreds of cloud checks, free
- Steampipe: query cloud APIs with SQL
- Cloud Custodian: rules with actions
- cloud-native: AWS Config, Azure Policy, GCP org policy
- commercial: Wiz and others
- write your own for rules that are yours alone
Common mistakes
Mistakes. Reading only the first page of results and reporting a clean bill of health. Running a read-only check with an administrator token. Treating an error as a pass. Alerts that reach no owner. The same alert repeated hourly until everyone ignores the channel. Automatic fixes with no dry-run mode and no undo. And the quiet one: a scheduled job that stopped months ago, while everyone assumed that no alerts meant no problems.
- reading only the first page
- an admin token for a read-only job
- errors treated as "passed"
- alerts with no owner
- the same alert every hour
- auto-fix with no dry run
- a job that stopped months ago and nobody noticed
Say it like this
In the interview, describe one real automation end to end. For example: a scheduled Python check running with a read-only role that lists access keys, flags any older than ninety days, finds the owner from tags and opens a ticket. Mention the engineering: it paginates, respects rate limits, fails closed on errors and alerts if the job itself stops. Then give the outcome, such as the time to fix falling from weeks to days. Outcomes are what interviewers remember.
- "A scheduled Python check with a read-only role that lists
- IAM access keys, flags any older than 90 days, finds the owner from tags and opens a ticket. It paginates, handles
- rate limits, fails closed and alerts if the job stops. Fix
- time dropped from weeks to days."