Automation
Rebuilding a cleanup job that couldn’t say “not this one”
Short-lived demo environments on a shared EKS cluster were cleaned up by two separate automations. One failed 220 times a day. The other destroyed an environment marked do-not-delete.
- Stack
- Python, Elastic Load Balancing, EKS, ECS, PostgreSQL, cron, a workflow-automation tool
- My role
- Audit, rewrite and rollout
- Outcome
- A replacement that dry-runs by default is running in production, on an instance role, with audit logs and tag protection.
What I found
- An hourly root cron job ran the cleanup script with a plaintext IAM user key in the shell file. The log was overwritten on every run, so there was no history.
- About 220 target-group deletions failed every day with
ResourceInUse. Only two succeeded in 14 days. Redeploys had left duplicate listener rules that still forwarded to those target groups, and the script only knew about the rules in its own mapping table. - A separate automation called an internal API that triggered a destroy pipeline for idle environments. Its only protection was a hard-coded list of names, with no tag check. It destroyed an environment that was tagged do-not-delete.
I traced the second chain end to end: the automation’s schedule, then the internal API, then the destroy job and its parameters. That told us exactly which build removed the protected environment, and why nothing had stopped it.
The rewrite
- It runs on the build host’s instance role. No static keys.
- It does a dry run by default, and only changes things with
--apply. - It finds orphaned listener rules by reading the load balancer itself, not only the mapping table.
- It skips anything tagged do-not-delete.
- It marks database rows as resources-deleted instead of deleting them, so a record remains.
- It writes an audit log entry for every action, rotated by logrotate, and runs from a normal user’s cron rather than root.
- The code lives in the team repo, and the copy on the server matches what’s merged.
Rolling it out
The first dry run sorted the environments into three groups: 8 ready, 5 blocked, 1 protected. The blocked ones mattered most. Four had database rows with a doubled name suffix, and their resource maps pointed at target groups belonging to live environments. Cleaning those up through AWS would have taken down sandboxes people were using. They are only marked in the database.
The first --apply ran against a single environment, and I checked the result. Then the new cron went live, and the old one was disabled.
What I took from it
- A cleanup job needs a way to say “not this one” that isn’t a list in code.
- Dry run first, by default, every time. The first dry run here caught the four cases that would have caused an outage.
- Read the real state from the provider. Your own bookkeeping drifts.