Made by PreviousNext
Development

A Terraform Layout You Can Actually Read

I've seen too many Terraform modules that look like this:

  • main.tf
  • variables.tf
  • output.tf

Three files. Every single time. It doesn't matter if the module deploys a whole platform, a single stack, one application, or nothing useful at all.

And that's the problem. Those three names tell you nothing about what the module actually provisions. You have to open main.tf and read the whole thing before you know what you're looking at.

A layout you can read at a glance

Here's the approach we've landed on. An operator can glance at the file list and know what a module manages, without opening a single file.

The rules are short:

  • One file per resource. The file name is the resource name.
  • If a file gets too big, split it. Add a suffix to the resource name, separated by a double underscore.

That's it. Simple and effective.

Naming examples

Say you're managing IAM roles. Your files look like this:

  • aws_iam_role.tf
  • aws_iam_role__this.tf
  • aws_iam_role__that.tf

The base file is the resource type. When you need more than one, the double underscore keeps related resources grouped and sorted together in the directory listing.

A real module

Here's the layout of one of our modules:

  • main.tf
  • aws_bedrock_inference_profile.tf
  • aws_caller_identity.tf
  • aws_iam_access_key.tf
  • aws_iam_policy.tf
  • aws_iam_policy_document.tf
  • aws_iam_user.tf
  • aws_iam_user_policy_attachment.tf
  • aws_region.tf
  • output.tf

Can you guess what this module does? You sure can! It sets up an AWS Bedrock inference profile, plus an IAM user, policy, and credentials to use it.

Now picture the same module in the default layout:

  • main.tf
  • output.tf
  • variables.tf

Would you have known any of that at a glance? Not a chance.

Two Terraform manifest lists demonstrating visibility provided by a better layout

Give it a try

The next time you build a module, name your files after the resources they hold. Your future self, and every operator who reads your code after you, will thank you.

Tags