Podcast about DevSecOps

#57 - Terraform Best Practices with Ben Goodman

One growing state file and a few console edits can turn routine Terraform deploys into detective work.

17 min read

In this episode, Mattias is joined by Ben Goodman, the founder of dragondrop.cloud, a platform that offers Terraform Best Practices as a Pull Request. They discuss the best workflows for Terraform, open-source tools that can be used in conjunction with Terraform, the most effective best practices, and common pitfalls to avoid when implementing infrastructure as code using Terraform.

Discuss the episode or ask us anything on LinkedIn


The Terraform choices you make in week one are the ones you live in

Most Terraform problems don’t arrive looking like problems. You start with one state file, because on day one there’s one VPC and one bucket. You run terraform apply from your laptop, because there’s nobody else on the project yet. You write resources straight into the root module, because wrapping them up is work you can do later. None of it hurts in month one. By month eighteen a plan takes long enough to make coffee, two teams can’t push at the same time, and a single bad apply can take the estate with it.

That’s the shape of almost every Terraform regret we hear: something innocuous at the start that turns into tech debt and then charges interest on it. We went through the list with Ben Goodman, founder and CEO of dragondrop.cloud, a New York developer tooling company that delivers Terraform best practices as a pull request, and lead maintainer of its open source tool cloud-concierge. His view of the common mistakes is from the outside in. He spends his days looking at other people’s Terraform stacks and at the gap between those stacks and the cloud accounts they claim to describe.

There are four decisions that set how much that debt costs you: how you split state, where it lives, who is allowed to apply, and what runs against a plan before it becomes real infrastructure. Then there’s the fifth thing, which quietly voids the other four.

One state file is the first mistake

Start with the one that bites every team that got going quickly.

What belongs in one state file?

A logical slice of your cloud, which in practice means one application area in one environment.

Dev networking is one state file. Production networking is another. The infrastructure behind one team’s application is its own, again per environment. That division caps the blast radius, so a corrupted state file costs you one slice instead of the estate. It keeps plans fast, because Terraform refreshes by calling the cloud provider’s API for everything the file manages. And it decouples teams: a change to dev networking doesn’t halt an application deploy in production.

We know the other path from the inside. Our everything-in-one state file started small and grew. Runs are slow, one careless destroy reaches the whole environment, and only one person holds the lock, so work queues behind whoever got there first.

Splitting a file you already have is a different job, and terraform state mv alone won’t do it. The command takes a source and a destination address, one move per run, and its -state and -state-out options work on local state only. So on a remote backend it’s pull, move, push: terraform state pull writes each state to a local copy, then one command per address with both ends spelled out, terraform state mv -state=old.tfstate -state-out=new.tfstate aws_vpc.main aws_vpc.main, then terraform state push uploads each copy to its own backend. Push refuses a state whose lineage doesn’t match the destination or whose serial is behind.

State is only half the move. The resource blocks have to land in the new root module in the same change, with every reference that pointed at them. A subnet still reading aws_vpc.main.id where that VPC no longer exists won’t plan, and a resource whose state moved without its configuration is unmanaged on one side and orphaned on the other. So plan both root modules before anyone applies: neither should want to create or destroy what you moved. If one does, an address or a reference is wrong. Check both the configuration and the state addresses, correct the mismatch, and rerun both plans before applying.

The warning on the state mv page is the step people skip: communicate carefully with your coworkers to ensure that nobody makes any other changes while the move is half done, or someone’s plan destroys the old object and creates a new one. Pause deploys on that slice, and check the backend keeps versions (on S3, the bucket versioning its docs call highly recommended), before you start.

Remote state is the floor, not the achievement

Splitting state only helps if everyone is reading the same copies of it.

Where should the state file live?

Anywhere except a laptop.

Local state can’t be shared, which makes it a single point of failure with a person attached. From there the options split two ways. Stay fully open source and use blob storage from whichever cloud you’re already in: an S3 backend, an Azure storage account, Google Cloud Storage. Or take a managed backend with other functionality attached, which at the time of recording means Terraform Cloud from HashiCorp, plus Spacelift, Scalr and env0.

Whatever you pick, turn on locking. Terraform locks state for any operation that writes it, so the second person to run an apply is refused rather than merged into a race. With the S3 backend that means a DynamoDB table alongside the bucket; the managed backends do it for you.

Locking is not coordination. The change that just landed may still break the one you’re about to apply, and you’ll find that out the hard way. That’s true of any codebase several people commit to, and infrastructure gets no exemption.

Nobody applies from a laptop

Remote state settles where the record lives. It says nothing about who gets to change it.

Who should be running terraform apply?

Your pipeline, and not a person.

A local apply can go around the shared path. Nothing in the command itself requires a pull request anyone read, a plan posted where a second pair of eyes lands on it, or an approval between the idea and the API calls; whatever review happened was voluntary. Whoever runs it can deploy whatever their own credentials allow, and unless something else captured the run, the record of what ran against which code is their shell history. Scoped roles and short-lived sessions limit the damage a bad apply can do, and they are worth having, but they don’t add the review back.

The replacement is a GitOps-shaped flow. You open a pull request with the infrastructure change. CI runs terraform plan against it and posts the output. A human approves, the code merges to the main branch, and an automated process applies what’s now on main. Developers and operators keep read access; write access belongs to the pipeline.

The pipeline still needs credentials, and that’s the part worth being careful about. Static keys in environment variables work and are the least secure version. Short-lived credentials from an OIDC trust between your CI provider and your cloud are the better one: GitHub Actions can assume an AWS role through OIDC with no stored secret at all. Terraform needs the same kind of credentials any API client needs, so the question isn’t whether they exist but how long they live and who can reach them. We argued through this one back in Episode 9, Terraform in CI, when handing the keys to the kingdom to an automated process still felt new.

The plan is a hook for cost and security checks

Once the plan runs in CI, it stops being only a preview for the author.

What else can run against a plan before anything is created?

Cost estimation and misconfiguration scanning, both from community tools you don’t have to build.

Infracost reads your Terraform and returns an expected monthly cost per resource. It sees that this is an EC2 instance, takes the instance type and the other attributes the configuration carries, and prices them at on-demand rates. What it cannot read, you supply: its AWS reference wants operating_system in the usage file for Windows, RHEL and SUSE, and leaves Marketplace AMI costs out of the number entirely. Ben Goodman isn’t affiliated with it and recommends it anyway, for a reason anybody who has approved an infrastructure pull request will recognise: “Like, whoa, this is a $3,000 pull request.” That number is visible before the apply, when changing it costs a review comment.

On the security side, Checkov, tfsec and Terrascan read the same configuration and flag the familiar misconfigurations. An endpoint that allows plain HTTP where it should require HTTPS. A port open wider than anyone meant. It’s linting, applied to infrastructure, with the finding attached to the diff that caused it. One caveat on that list: Aqua said in February 2023 that tfsec’s scanning work is consolidating into Trivy, which already reads Terraform, and that tfsec stays available for the time being. If you’re choosing a scanner rather than keeping one you already run, that’s where the checks are heading.

None of this is Terraform doing the work. It’s a consequence of Terraform describing intended state in a form other tools can parse before the state exists. The ecosystem is the feature here, which is a point that comes back when we get to the alternatives.

Drift undoes all of it

Every check so far lives on the path from pull request to apply. None of them sees a change that never took that path.

Why is drift worse than the change that caused it?

Because it voids the guarantees the rest of the workflow just bought you.

Drift is the gap between what your state file believes and what the cloud actually holds. It opens whenever a change happens outside the workflow: a few clicks in the AWS or GCP console, a CLI call, or application code reaching for the cloud API with Boto3 and creating something nobody wrote down.

The cost is partly in the timing. You usually discover drift when you run terraform plan to ship something else, and the plan comes back with a long list of changes you didn’t ask for. Now you’re not shipping. You’re working out “I need to track down who changed this EC2 instance size”, and then the harder question, “am I going to break something if I overwrite this change?” Your afternoon is gone and the change you came to make hasn’t moved.

We have the other version of this too. A few weeks before recording we found an EC2 instance in a region nobody had reason to look at, and nobody could say what it was for or who created it.

The clean fix is to take away write access outside the pipeline, so there’s no console path to drift in the first place. That’s hard, and it’s hardest exactly when you need it most: part way through adopting Terraform, when some of the estate is codified and some of it was clicked into existence by someone who left. Full console access is fine when you’re a startup clicking things together. It stops being fine the moment you want to replicate an environment.

The resources nobody ever wrote down

Drift assumes the resource is in your code at all. The other half of the problem is everything that never was.

What do you do with resources that were never in Terraform?

Generate the configuration and import them, rather than retyping them by hand and hoping you matched the settings.

Terraform has shipped a native version of this since 1.5: you declare import blocks for the resources you want, run terraform plan -generate-config-out=generated.tf, and get HCL back. HashiCorp’s own docs set expectations plainly. The feature is experimental, and the output is Terraform’s best guess at each argument, so it’s a starting template rather than finished code. It also doesn’t help with the first problem, which is knowing what’s out there to import.

That’s the gap cloud-concierge aims at. It scans a cloud environment on a cadence, compares what it finds against your existing state files, and opens a pull request with the difference: which managed resources have drifted, and for anything unmanaged, generated code plus the import statements to adopt it. It also reaches into CloudTrail to answer the question the plan output can’t, which is who created this thing outside Terraform in the first place.

The scepticism this deserves is the one we had on air: plenty of companies have promised to read an AWS account back out as usable Terraform, and reading the account is the hard part. Treat the generated code the same way you’d treat the output of -generate-config-out, as a draft for review. The pull request format does buy you the right posture: it highlights rather than blocks, which is what you want while half the estate is still being adopted.

Modules are how you hand infrastructure to a developer

Adoption gets easier when the people creating infrastructure don’t have to become Terraform experts first.

What does a module give a team that a wiki page can’t?

The guardrails live in the code they run, instead of in instructions they have to remember.

A module turns that into an interface. The platform team publishes an EC2 module with the organisation’s security defaults baked in; the developer supplies a handful of variables and gets an instance that can’t be configured into the shapes you’ve ruled out. At mid-sized companies with a mature platform or ops team, that grows into an internal catalogue of pre-approved components. How much of this developers touch at all varies enormously by organisation, and at the largest scale you often don’t see developers writing their own infrastructure code.

The same packaging pays off for the team that owns the modules. dragondrop keeps one module per logical division of its own infrastructure, including the Google Cloud resources behind its core API. Deploying that API into another environment is a module reference and a few variables rather than a new set of files to keep in sync.

Not starting with modules is the second mistake that compounds quietly. One S3 bucket wired to one Lambda is easy to write inline, and painful the day you need it in three environments.

Worth knowing how far this reaches: Terraform is fundamentally an API management tool that happens to be used mostly on cloud provider APIs. HashiCorp’s own tutorial builds a Spotify playlist with it, which is a good hack-day project and a better reminder of what the tool actually is.

The fork, and the case for Pulumi

All of the above assumes Terraform, and in November 2023 that assumption is less settled than it was a year ago.

HashiCorp moved all future releases of its products, Terraform included, to the Business Source License on 10 August 2023. A fork was announced two weeks later, on 25 August, at a point when its repository was not yet public, and on 20 September the project, previously named OpenTF, launched as OpenTofu under the Linux Foundation. That fork is Terraform’s most direct competitor precisely because the switching cost between them should be very low, and the most likely near-term effect of two projects chasing the same users is more features on both sides. We walked through the licence change and the registry questions in Episode 54 a couple of months before this conversation.

Pulumi is the different answer. Terraform configurations are written in HCL, a configuration language that reads close to declarative; Pulumi programs are written in Go, Python or TypeScript. For a developer-heavy DevOps team that doesn’t want to learn HCL, that’s a real advantage, and the trade-off is equally real: a general-purpose language lets complexity hide in ways a declarative file tends to surface. We had Paul Stack on to argue this properly in Episode 25.

That’s the part of the comparison that’s easy to miss. Infracost, Checkov and the rest are prebuilt for Terraform because that’s where the users are. Pulumi is not short of a policy story, CrossGuard has been generally available since May 2020, but matching the particular checks you run today is work your team does rather than work the ecosystem has already done for you.

What this means for teams

None of this needs a budget line. The expensive version is doing it in year three instead of this quarter, when the single state file has a thousand resources in it and three teams waiting on the lock.

Four things worth doing this week:

  • Count the resources in your largest state file, then pick the first seam. Application area and environment is the division to cut along: dev networking, production networking, one team’s application per environment. Which slice moves first is a question about your own dependency graph, so read the outputs and remote state data sources in that root module and start with the one fewest other resources reach into.
  • Check whether anyone can still apply from a laptop. Not whether they’re supposed to: whether the credentials on their machine would let them. If the answer is yes, move the apply into CI before you touch anything else on this list.
  • Add Infracost and one security scanner to the pull request checks. Both read the configuration you already have, both post to the diff, and the first surprising number pays for the afternoon it takes.
  • Change one tag by hand and see what notices. If nothing does until the next terraform plan, your detection works but arrives late, in the middle of somebody’s deploy. Running that plan on a schedule, or scanning the account on a cadence, moves the discovery off the path of whoever is trying to ship.

Common questions, answered

How do I split a Terraform state file that’s already too big?

Carve out one slice at a time, along application and environment lines, starting with the one fewest other resources reach into. Move the resource blocks and every reference to them into the new root module, then move the state to match: on a remote backend that is terraform state pull, then terraform state mv -state=old.tfstate -state-out=new.tfstate SOURCE DESTINATION once per address on the local copies, then terraform state push, because the cross-file options work on local state only. Pause deploys on that slice first, and finish by planning both root modules: neither should want to create or destroy what you moved.

How do I stop people changing things in the AWS console?

Remove write access from human roles and leave it only on the role your pipeline assumes. That’s the complete fix, and the hardest to apply mid-adoption, when some of your estate still has no code behind it. Until you get there, close the gap with detection instead: scan the account on a schedule, compare it against your state files, and route the differences somewhere a person reads. Tools like cloud-concierge do this as a pull request, which flags the change and names who made it without blocking the emergency fix that caused it.

How do I let developers create infrastructure without giving them cloud write access?

Publish modules with your defaults already in them and let developers supply variables. The developer gets an interface with a few inputs, your security settings apply whether or not anyone read the docs, and the apply still runs in the pipeline with its credentials rather than theirs. This is the mid-size pattern: a platform team maintaining a catalogue of pre-approved components, and teams composing from it. It beats the pre-IaC alternative, which was a list of buttons not to click.

Resources

  • Terraform S3 backend documentation settles what a remote S3 backend actually requires, including the DynamoDB table you need for locking and the bucket versioning it tells you to turn on.
  • Terraform state locking says which operations take a lock and what happens to the second run, plus the force-unlock escape hatch and when not to use it.
  • terraform state mv is the command reference for moving resources: the source and destination addresses every run needs, which options only work on local state, and the coordination warning that makes a state split a scheduled job rather than an afternoon’s tinkering.
  • terraform state push covers the upload half of a split, including the lineage and serial checks that stop you overwriting the wrong backend.
  • Generating configuration from import blocks is HashiCorp’s own description of the native import path, and its own warning that the feature is experimental and the output is a best guess.
  • Infracost supported AWS resources settles what the tool prices from code alone, which usage-file inputs it needs first, and what it leaves out, Marketplace AMI costs included.
  • cloud-concierge on GitHub is the Apache 2.0 tool behind the pull request workflow described here, including what it scans and what lands in the report.
  • Ben Goodman on LinkedIn is the profile published with the episode.

Since we recorded

The fork stopped being a question mark: OpenTofu shipped 1.6 as its first stable release on 10 January 2024, and we picked up what migrating actually costs with Timur Bublik in Episode 64, From Terraform to OpenTofu. The other side of the licence story closed too, with IBM completing its acquisition of HashiCorp on 27 February 2025. cloud-concierge is still on GitHub under Apache 2.0, though its last tagged release, v0.2.5, was published in January 2025.