Terraform and Ansible are both infrastructure as code tools that help automate core infrastructure tasks. However, they use different languages and often serve different purposes. Terraform is used to provision infrastructure resources, while Ansible is often used for managing resource configurations.
Terraform uses a purely declarative language, while Ansible combines both declarative and procedural languages. In procedural configuration, a developer specifies the steps for configuring resources in the desired state. Procedural configuration is more labor intensive, but it can also provide more control.
Ansible playbooks, written in YAML, allow for fine-grained control over tasks such as installing software and updating system settings. Ansible also has a variety of prebuilt modules for common configuration management tasks, including package management and operating system updates. And Ansible can apply changes to resources idempotently—meaning that, after an operation is applied the first time, further applications of the same operation do not change the resource.
Taken together, these characteristics help explain why Ansible is a common choice for configuration management.
While Terraform can provision infrastructure resources, it cannot manage software inside of resources as effectively as Ansible. For example, Terraform can define a new virtual machine, including properties such as instance type and disk size, but it cannot update the operating system on the virtual machine.
However, Terraform can work hand-in-hand with configuration management tools such as Ansible to simplify and streamline infrastructure configuration. For example, an organization might use Terraform to provision virtual machines and Ansible to configure the software on those machines.