Infrastructure as Code
Describe servers and networks in files you can review, repeat and roll back, and avoid common traps.
Key takeaways
- Infrastructure as code makes environments reproducible, reviewable and versioned.
- Declarative tools describe the desired end state, and imperative scripts list the steps to take.
- Always read the preview of a change before applying it, especially anything that replaces or deletes resources.
- State files and secrets need protection, because they can expose your whole environment.
- Manual edits cause drift, so route changes through the code and check for differences regularly.
Infrastructure as code means describing your servers, networks, databases and permissions in text files, then letting a tool create and update the real things to match. Instead of clicking through a cloud console and hoping you remember what you did, you edit a file, review the proposed change and apply it.
The payoff is repeatability. You can build a second environment from the same files, see who changed a firewall rule and why, and rebuild after a disaster without relying on memory. The cost is a new tool to learn and some discipline to keep the files and reality in agreement.
The problem with clicking
Building by hand works once. The trouble starts later. Someone opens a port to debug an issue and forgets to close it. The test environment slowly differs from production, so a change that passed testing fails live. The one person who set up the load balancer leaves, and nobody knows why a certain setting exists.
Written instructions help but go stale, because nothing forces them to match reality. When the description is what actually builds the system, it has to stay accurate.
Declarative and imperative
A declarative tool lets you state what should exist: two web servers of this size, behind this load balancer, in this network. The tool compares that with what exists and works out the changes. Terraform, OpenTofu, AWS CloudFormation and Azure Bicep are examples.
An imperative approach lists actions: create a server, then install a package, then open a port. Shell scripts do this naturally. The risk is that running a script twice may create duplicates or fail halfway.
The useful property is idempotency: applying the same description repeatedly leaves the system in the same state. Declarative tools aim for it by design.
A different group of tools, such as Ansible, Puppet and Chef, concentrates on configuring what's inside machines: packages, files and services. Some tools let you write infrastructure in general programming languages while still producing a desired-state plan.
A small example
Here is an illustrative snippet in the HashiCorp configuration language used by Terraform and OpenTofu. It describes a storage bucket on AWS. The bucket name is a placeholder.
resource "aws_s3_bucket" "reports" {
bucket = "example-reports-bucket"
tags = {
team = "finance"
environment = "test"
}
} A real project also declares which provider and region to use and how you sign in. The usual commands are:
terraform init
terraform plan
terraform apply init downloads the provider plugins, plan shows what would change, and apply makes the changes after you confirm. OpenTofu uses the same pattern with the tofu command.
Reading a plan carefully
The plan is your safety check. It marks resources to be added, changed or destroyed. Pay close attention to replacements. Some properties can't be edited in place, so the tool deletes the old resource and creates a new one. For a web server that may be harmless. For a database it can mean losing data.
Guard important resources with deletion protection in the cloud service or a lifecycle rule in the tool, and keep tested backups regardless. Prefer small changes, because a plan with three lines gets read and a plan with three hundred gets skimmed.
State: the tool's memory
Many tools keep a state file recording which real resources correspond to which lines of code. Without it, the tool can't tell whether to create something or update it.
Treat state with care. It can contain sensitive values, including generated passwords. Store it in a shared, encrypted location with restricted access, enable versioning so you can recover from corruption, and use locking so two people can't apply changes at the same moment. Don't commit it to your code repository.
CloudFormation and similar provider-native services keep that record for you, which removes one chore at the price of working with a single provider.
Secrets and permissions
Never write passwords or access keys into configuration files. Even if you delete them later, version history remembers. Fetch secrets at run time from a secrets manager or the pipeline's protected store. Environment variables and secrets covers the basics.
The account that applies changes is powerful. Give it only the permissions it needs, prefer short-lived credentials over long-lived keys, and keep production credentials away from laptops where practical. Policy checks can block risky settings, such as storage open to the public, before they're ever created.
Variables, modules and environments
You rarely want identical environments. Test might run one small server where production runs four large ones. Variables let the same code accept different values, kept in a separate file for each environment, so the structure stays shared and the differences are visible in one place.
A module is a reusable bundle of resources with inputs and outputs. A "web service" module might create the servers, load balancer, firewall rules and alarms together, with inputs for size and count. Teams then get sensible defaults without copying a hundred lines.
Pin versions of the tool, the provider plugins and any shared modules. An unpinned upgrade can change behavior between two runs of unchanged code. Upgrade deliberately, read the release notes and review the resulting plan. Be cautious with modules from public sources: they run with your credentials' authority, so read what they create before you use them.
Version control and reviews
Keeping the files in Git gives you history, branching and review. A commit message can explain why a rule exists, which is the information that tends to vanish.
Rolling back is usually a matter of reverting the commit and applying again. Be careful, though. Reverting code doesn't restore deleted data, and some changes can't be undone cleanly.
Organize code so that a mistake has a limited reach. Separate production from test, with separate state. Group resources by how often they change and who owns them. Turn repeated patterns into modules with a few clear inputs, but wait until you've repeated something a few times; premature abstraction is hard to read.
Drift
Drift is the gap between what the code says and what exists, usually caused by an emergency fix in the console. Left alone, the next apply may quietly undo the fix, or fail in a confusing way.
Run scheduled plans and investigate unexpected differences. When someone has to make an emergency change by hand, record it and bring it into the code afterward. Limiting who can edit production directly makes drift rare.
Adopting it on an existing setup
You don't need to rebuild everything. A sensible path:
- Start with something new and low risk.
- Set up shared state, version control and review from the beginning.
- Import existing resources a few at a time, checking that the plan shows no changes before moving on.
- Move applying changes into a continuous delivery pipeline.
- Reduce manual edit rights as coverage grows.
Networks and security groups are a good early target, since their history matters and mistakes are easy to spot in a diff.
Test and disposable environments
Once an environment is described in code, creating a copy becomes cheap in effort. Teams spin up a temporary environment to test a risky change and destroy it afterward. This also proves the code can build from nothing, something a long-lived environment never demonstrates.
That matters for disaster recovery. Code can rebuild the structure, but it doesn't hold your data. Keep backups, and note any manual steps, such as verifying a domain or requesting a capacity limit increase, that the code can't perform.
Watch the cost too. Temporary environments that nobody destroys keep billing. Tag them with an owner and an expiry, and clean up automatically.
What can go wrong
An apply can fail partway, leaving some resources created and others not. Declarative tools usually let you fix the cause and run again, but check the state and the console before assuming.
Two people applying from different branches can overwrite each other's work. State locking and a single pipeline that applies only from the main branch prevent most of this.
Renaming something in code can look to the tool like deleting one resource and creating another. Many tools offer a way to declare a move or rename so the real object is kept. If a plan wants to destroy something you only meant to rename, stop and use it.
Finally, a destroy command does exactly what it says. Restrict who can run it against production, and require a separate approval.
Immutable servers
A related practice is to stop patching running machines. You build a new image containing the updated software, start fresh servers from it and retire the old ones. Every server matches a known version, and rolling back means starting the previous image.
Containers make this habit natural. It works best when servers hold no unique data, so move uploads, sessions and logs elsewhere first.
Is it worth it for you?
If you run one small site on a managed host, a written checklist may be enough. Once you have multiple environments, more than one person making changes, or a need to show auditors what changed, infrastructure as code usually repays the effort quickly. Pick the tool that your team can read and that supports your providers, and keep the first project modest.