← Back to blog

Terraform and Ansible: optimizing costs with reproducible infrastructure

Lazy Read

Terraform describes resources and Ansible configures systems. Together with Git, metrics and documented decisions, they support informed changes and measurable results.

  • Purpose: Identify owners and dependencies.
  • Evidence: Use representative metrics and costs.
  • Validation: Review risk and measure the change.

“If I shrink this machine, what stops working? Who created this gateway? Why do we maintain the same capacity in every environment?”

Finding unnecessary spending is only part of the job. Correcting it requires understanding dependencies, preserving data and repeating the change without relying on one person’s memory.

The AWS, Azure and Google Cloud articles covered provider-specific opportunities. Terraform and Ansible help turn that analysis into a maintainable workflow. They do not generate savings themselves: they make the decisions behind potential savings explicit and reviewable.

Assign clear responsibilities

Terraform declares resources and relationships through providers: machines, networks, disks, identities and managed services. Ansible can configure packages, files and services inside systems we administer.

ResponsibilityTypical tool
Cloud resource lifecycleTerraform
Declared sizing, networking and capacityTerraform
Packages, users and services inside a VMAnsible
Reviewing infrastructure changesTerraform plan
Checking system configurationAnsible, subject to module support and limits

Responsibilities can overlap. Avoid having two tools manage the same property. An immutable image or fully managed service may handle configuration without Ansible accessing its machines. Terraform provisioners exist, but should not become a recurring configuration system when more suitable tools are available.

A reviewable plan needs context

Configuration can describe instance size, ownership and purpose. Git records when it changed; reviews explain the intended result. A Terraform plan shows proposed operations on managed resources.

terraform fmt -check
terraform validate
terraform plan -out=change.tfplan
terraform show change.tfplan
# Apply the saved plan only after review and authorization.

This assumes an initialized directory with providers and access already prepared. It is not an invitation to run commands in an arbitrary repository: Terraform loads providers and can query data sources or execute programs defined by configuration. Review code first and use scoped identities.

A plan cannot know every external consumer, scheduled job or business agreement. Before removing a resource, combine configuration, metrics, traffic, owners and recovery requirements. An apparently minor replacement may affect data or connectivity.

Protect state and saved plans

State and plan files can contain sensitive data. Marking a variable sensitive hides certain output values, but does not by itself remove them from stored artifacts.

Keep state and plans out of Git and public artifacts. Backends need access control, encryption, recovery and locking where supported. Separate states and identities across different trust boundaries. Workspaces alone do not enforce separate permissions.

Version configuration and relevant lockfiles; keep credentials out of HCL, published variables and logs. Review what CI plans disclose and who can download them.

Ansible handles the system inside the server

A playbook can install Nginx, apply configuration and reload through a handler only when a task notifies a change. Template validation can check a file before installation, using commands and context appropriate to the service.

A changed template does not prove correctness or safe reload behavior. Prepare validation, dependencies, permissions and recovery. When managing secrets, avoid exposing them through results and differences; use appropriate secret handling and output controls.

Ansible check mode helps anticipate certain changes, subject to module and conditional limitations. It is not a sandbox: tasks with check_mode: false can execute normally. Review playbooks and plugins before trusting them; --diff can also disclose sensitive information.

Reproducibility does not require identical capacity

Environments can share modules and automation while using different parameters. Permanent capacity, replicas and retention should serve their purpose. A controlled environment may use synthetic data, smaller capacity or limited operating hours when dependencies allow. Availability and load tests still need representative conditions when performed.

Declare those differences. Lower cost does not justify removing necessary controls, leaving data unprotected or assuming a reduced configuration validates the entire production architecture.

The same reasoning supports separating a nightly job from an API, adjusting historical storage or reviewing NAT and load balancers. Each proposal needs total cost, reversibility and service metrics. Purchasing a spending commitment remains a separate financial decision even when configuration is versioned.

Adopt existing infrastructure gradually

Start with inventory, ownership and dependencies. Import resources where supported and complete their configuration until plan differences are understood. Importing does not guarantee the next apply is harmless.

Next, reproduce known configuration with Ansible in a controlled environment. Avoid overwriting critical settings simply to match an example. The first goal is to represent the system; the next is to improve one component using evidence.

Record the rationale in an architecture decision: problem, alternatives, action, owner, validation and review date. An instance named batch-worker still does not explain why it needs a particular capacity or availability level.

Investigate drift before correcting it automatically. A manual change may be supporting emergency recovery. Decide whether to incorporate it into code or revert it through a reviewed plan.

Measure the complete change

For a specific optimization, record comparable workload and cost metrics; review restart or replacement requirements; protect data and prepare recovery. After authorized infrastructure and configuration stages, measure latency, errors, job duration and unit cost.

Terraform and Ansible preserve what we want to deploy and how systems should operate. Git, documented decisions and observability provide history and context. Their value is being able to explain why each resource exists and verify whether a change improved anything.