Sat. Feb 4th, 2023
ansible or terraform
ansible or terraform
ansible or terraform

We can also use Ansible as an Infrastructure as Code then why should we go with Terraform?

Ansible follows a procedural style whereas Terraform follows a declarative style.

To demonstrate the difference, let’s go through an example. Imagine you wanted to deploy 10 servers (“EC2 Instances”).

Here is a simplified example of an Ansible template that does this using a procedural approach:
– ec2:
count: 10
image: ami-90d28157
  instance_type: t2.micro

And here is a simplified example of a Terraform template that does the same thing using a declarative approach:

resource “aws_instance” “example” {
count = 10
ami = “ami-90d28157”
  instance_type = “t2.micro”
}

Now at the surface, these two approaches may look similar, and when you initially execute them with Ansible or Terraform, they will produce similar results. The interesting thing is what happens when you want to make a change.

For example, imagine traffic has gone up and you want to increase the number of servers to 15. With Ansible, the procedural code you wrote earlier is no longer useful; if you just updated the number of servers to 15 and reran that code, it would deploy 15 new servers, giving you 25 in total!
So instead, you have to be aware of what is already deployed and write a totally new procedural script to add the 5 new servers:
– ec2:
count: 5
image: ami-90d28157
instance_type: t2.micro

With declarative code, since all you do is declare the end state you want, and Terraform figures out how to get to that end state, Terraform will also be aware of any state it created in the past. Therefore, to deploy 5 more servers, all you have to do is go back to the same Terraform template and update the count from 10 to 15:
resource “aws_instance” “example” {
count = 15
ami = “ami-90d28157”
instance_type = “t2.micro”
}

If you executed this template, Terraform would realize it had already created 10 servers and therefore that all it needed to do was create 5 new servers. 

With Terraform’s declarative approach, the code always represents the latest state of your infrastructure. At a glance, you can tell what’s currently deployed and how it’s configured, without having to worry about history or timing. This also makes it easy to create reusable code, as you don’t have to manually account for the current state of the world. Instead, you just focus on describing your desired state and Terraform figures out how to get from one state to the other automatically. As a result, Terraform codebases tend to stay small and easy to understand.


Ansible can be used as Infrastructure configuration

Terraform can be used as Infrastructure Provisioning

By admin

Leave a Reply

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