Terraform Vs Ansible

Context

For companies that mainly host their services in a legacy system, the movement towards Infrastructure-as-code raises the question of the choice of tools. Terraform and Ansible are commonly used tool in this field. But, when, how to use Terraform, Ansible? And do we have to use both?


Important notice: this article intentionally ignores Kubernetes and native cloud provisioning tools and their advanced abstract infrastructure layer.


First, let's go back in time a bit.


Infrastructure as Code


Wikipedia:

"Infrastructure as code (IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools. The IT infrastructure managed by this process comprises both physical equipment, such as bare-metal servers, as well as virtual machines, and associated configuration resources…"


Since the origin, the purpose of IaC is to deploy infrastructure with declarative files depicting resources (i.e. components, variables and so on ... ). Ideally, to track the changes, the files are under source repository.


Lot of tools exist to perform this task, Ansible and Terraform are part of them.

But, before comparing, let’s have a quick refresh about paradigms commonly mentioned in IaC


Let's take the example of modifying an element of an existing infrastructure. How to perform the update?


Mutable or Immutable paradigm

Mutable Update in place the item in the infrastructure, changing the old version to reach the new one

Immutable Destroy and re-create the item in the infrastructure

Imperative or Declarative paradigm

Imperative Specify the How to do? It is a Workflow or a Procedure

Declarative Depict the What to do? It is a Model

Example of files

Terraform is a pure declarative tool: it will reach a desired state. Below is given an example of provisioning an Nginx container with Docker and Terraform:

Terraform HCL file:



Ansible is an imperative tool, at the module level. It provides, at higher scale, modules orchestration. Loop, test condition, wait until, repetition, error detection ... are possible. The same way than Coding language.

Ansible Yaml file:





How do they work?

Terraform

Terraform loads all the files, binaries, configs and required modules. Once everything is configured, Terraform compares the persisted state and objects in the real infrastructure. Afterwards, Terraform executes the commands to be applied on this infrastructure. Finally a new state is saved.


The communication between the Terraform CLI and targeted hosts depends on the providers. The protocol between Terraform and provider plugins is gRPC. Provider plugins use their own API to interact with the infrastructure.

Ansible