Infrastructure as Code: Ansible vs Vagrant vs Terraform

Infrastructure as code provides the ability to provision infrastructure automatically via configuration files. Multiple solutions exist to automatically provision infrastructure. The most well-known tools are explained (including examples) in this article. These are Vagrant, Ansible and Terraform.

The primary advantage of infrastructure as code is the speed of provisioning new infrastructure on the fly. The hassle of creating a new virtual machine, including all its configurations, especially if you need to manage many instances, can significantly be reduced by applying infrastructure as code.

Key advantages of using infrastructure as code

  • Fast provisioning of infrastructure.
  • Always use and apply the same configuration for provisioning infrastructure.
  • It is easy to change the configuration of your infrastructure.

Ansible

With Ansible it is perfectly possible to configure your infrastructure from a central point in your network. Especially when having multiple machines to configure and manage, it makes sense to centralize this effort. Manually updating, installing, or configuring packages on each component within your network is a tedious job. As a result, Ansible can easily support this process via the creation of configuration files, or playbooks.

The creation of Ansible configuration files and subsequently running them is done via the Linux command line. An example YAML code is presented below which would install net-tools in two virtual machines (‘domo’ & ‘pihole’). In a separate INVENTORY configuration file, the connection details would be defined for both servers to allow connecting via SSH to execute the apt install net-tools on both virtual machines.

---
-
  become: true
  hosts: domo
  tasks:
    -
      apt:
        name: net-tools
      name: "install net-tools"
-
  become: true
  hosts: pihole
  tasks:
    -
      apt:
        name: net-tools
        state: present
      name: "install net-tools"

As you can easily see, instead of executing both commands separately on each virtual machine, Ansible allows executing this command from a central point in your network, just once.