Infrastructure as Code Explained: How Declarative Definitions, State, Drift Detection, and Code Review Make Environments Repeatable

Infrastructure as Code Explained: How Declarative Definitions, State, Drift Detection, and Code Review Make Environments Repeatable

Few operational problems are as frustrating as an environment that nobody can fully explain. A server was tuned by hand during an outage, a firewall rule was added through a web console, and a database setting was changed “temporarily” months ago. Infrastructure as code (IaC) is the practice of describing infrastructure in text files that are versioned, reviewed, tested, and applied by tooling instead of by hand. This article explains the core ideas, how the pieces fit together, and where the approach demands care.

What Infrastructure as Code Actually Means

At its simplest, IaC treats networks, compute, storage, permissions, and configuration the way software teams treat application code. The definition lives in a repository, changes arrive through commits, and a tool translates the files into real resources. The benefit is not just automation. It is that the intended state of a system becomes something you can read, diff, and discuss before it changes.

Declarative and Imperative Styles

Declarative tools let you describe the end result: “there should be a private network with two subnets and a load balancer.” The tool compares that description with reality and works out the steps. Imperative approaches, such as shell scripts or procedural code, spell out the steps themselves: “create this, then attach that.” Declarative definitions are easier to reason about and to re-run safely. Imperative code offers more flexibility for unusual logic. Many teams use declarative tools for the bulk of their infrastructure and keep scripts for glue and one-off tasks.

Provisioning and Configuration Management

Two related jobs are often blurred together. Provisioning creates the resources themselves, such as networks, virtual machines, managed databases, and DNS records. Configuration management shapes what runs inside those resources, such as packages, services, and files. Container-based workflows shift much of the second job into image builds, but the distinction remains useful when deciding which tool owns which responsibility.

The Core Building Blocks

  • Resources: the individual objects under management, such as a subnet, a storage bucket, or an access policy.
  • Variables and outputs: inputs that let one definition serve several environments, and values that one component exposes for others to consume.
  • Modules: reusable bundles of resources with a clear interface, so a team can define “a standard service network” once and use it many times.
  • State: the tool’s record of which real resources correspond to which definitions.
  • Plan and apply: a preview of proposed changes, followed by execution of those changes.
  • Providers or plugins: the layer that talks to a cloud platform or service API on the tool’s behalf.

How State Keeps Definitions Tied to Reality

Most declarative tools need a way to know that a resource in a file is the same object that exists in the cloud account. They keep that mapping in a state record. When you run a plan, the tool reads the definitions, consults the state, queries the real environment where needed, and calculates the difference.

State is powerful and sensitive. It can contain resource identifiers and, depending on the tool and resources, sometimes secret values. Practical habits include:

  • Store state in a shared remote backend rather than on one laptop.
  • Enable locking so two people or pipelines cannot apply changes at once.
  • Restrict read access, and encrypt it at rest.
  • Split state into smaller units, for example by environment or by system, so one mistake or one slow plan does not affect everything.

Drift: When Reality Diverges from the Code

Drift happens when the live environment no longer matches the definitions. Typical causes are emergency console edits, other automation touching the same resources, or provider-side changes. Drift matters because the next apply may silently revert a manual fix, or because the code no longer describes what is actually protecting or serving users.

Ways to manage it include running read-only plans on a schedule and alerting when they show unexpected differences, limiting who can change production through consoles, and deciding in each case whether to update the code to match the change or revert the environment to match the code. Both are legitimate. What matters is that the decision is deliberate and recorded.

Code Review and Pipelines as Safety Nets

Once infrastructure is text, ordinary engineering controls apply. A typical workflow looks like this:

  1. An engineer opens a pull request with a change to the definitions.
  2. Automation runs formatting checks, validation, and static analysis for risky patterns such as publicly open storage or overly broad permissions.
  3. The pipeline produces a plan and attaches it to the review so reviewers see the real effect, not just the diff of text.
  4. After approval and merge, a pipeline applies the change, often to a lower environment first.

Reviewing the plan is as important as reviewing the code. A one-line edit can imply destroying and recreating a database, and the plan is where that becomes visible.

A Practical Example

Imagine a team that runs a web service in three environments: development, staging, and production. Without IaC, each was built at a different time by different people, and staging differs from production in ways nobody remembers. With IaC, they write a module describing the service: network, load balancer, compute group, and database. Each environment is a small file that passes in its own values, such as instance size and replica count. A new region or a fresh test environment becomes a matter of adding another small file and running the pipeline.

When production needs a larger database, the change is a variable edit in a pull request. The plan shows an in-place modification rather than a replacement, reviewers approve, and the history records who changed what and why. If something breaks, the previous commit shows the earlier intended state.

Trade-offs and Pitfalls

  • Learning curve and abstraction cost: modules and clever logic can make definitions harder to read than the resources they describe. Prefer plain, explicit code until repetition justifies abstraction.
  • State management overhead: state corruption, lock contention, and large monolithic states are real operational burdens.
  • Blast radius: a pipeline with broad permissions can damage a lot quickly. Use separate credentials per environment and require approval for production.
  • Secrets handling: never commit credentials to the repository. Reference a secrets manager instead and be aware of what ends up in state.
  • Destructive changes: some edits force replacement of a resource. Read plans carefully and use deletion protection for stateful resources.
  • Tool lock-in: definitions are tied to a tool’s language and provider model. Weigh portability against the productivity of a mature ecosystem.
  • Adoption of existing systems: importing hand-built resources is possible but tedious. Start with new components or with the most failure-prone areas rather than attempting a big-bang rewrite.

Testing Infrastructure Code

Testing happens in layers. Formatting and validation catch syntax and obvious mistakes. Policy checks encode organizational rules, such as required tags or banned configurations. Plan-level tests assert on what would change. Finally, short-lived real environments can be created and destroyed to confirm that a module truly works end to end. Cost and time increase at each layer, so most teams run cheap checks on every change and heavier ones less often.

Guidelines for Getting Started

  • Pick one well-bounded system and bring it under management first.
  • Keep production changes flowing through the pipeline, and treat console edits as exceptions to be reconciled.
  • Name and tag resources consistently so ownership and cost are clear.
  • Pin tool and provider versions so runs are reproducible.
  • Document how to recover: how to unlock state, restore it, and apply a previous version.

Conclusion

Infrastructure as code turns environments from folklore into artifacts. Declarative definitions state the intent, state records tie that intent to real resources, drift detection exposes where the two part ways, and review plus pipelines place human judgment before every change. The approach brings its own costs in state handling, permissions, and abstraction discipline, but for any system that must be rebuilt, scaled, or audited, those costs are usually far smaller than the price of an environment nobody can reproduce.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *