DevOps & Containers
Infrastructure as Code: A Practical Guide with Terraform and Ansible
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيMost servers start life configured by hand: a few commands over SSH, a package installed here, a config file edited there. It works until you need a second identical server, or until the original breaks and nobody remembers exactly what was done. Infrastructure as Code (IaC) solves this by describing servers, networks and configuration in text files that live in Git. Those files become the single source of truth: you review changes like application code, apply them with a tool, and can rebuild the same environment at any time. This guide explains the core ideas, compares Terraform and Ansible, and shows small working examples you can run against a VPS.
Why Infrastructure as Code Matters
- Repeatability: the same code produces the same result, whether it is your first server or your tenth.
- History and review: every change is a commit, with an author, a reason and a diff that colleagues can review.
- Faster recovery: if a server is lost, you rebuild it from code and restore data from backups.
- Less drift: manual tweaks slowly make servers differ from each other. Re-applying code brings them back in line.
- Documentation that stays current: the code describes the real setup, unlike a wiki page written once.
Declarative vs Procedural
IaC tools follow one of two styles:
- Declarative: you describe the end state ("a container named
webrunning nginx on port 8080") and the tool works out the steps. Terraform is declarative. - Procedural: you list the steps in order. Plain shell scripts are procedural.
Ansible sits in between. Playbooks run tasks in order, but most modules are idempotent: they check the current state and change something only when needed, so running the same playbook twice is safe.
Terraform vs Ansible
| Terraform (or OpenTofu) | Ansible | |
|---|---|---|
| Main job | Provisioning resources through APIs | Configuring servers and deploying apps |
| Language | HCL | YAML playbooks |
| Style | Declarative, with a state file | Mostly idempotent tasks in order |
| How it connects | Provider APIs | SSH, agentless |
| Typical targets | Cloud servers, DNS, load balancers, containers | Packages, users, files, services |
They complement each other. A common pattern is Terraform to create resources and Ansible to configure what runs inside them. OpenTofu is an open-source fork of Terraform that uses the same language and workflow.
Ansible: Configure a VPS in Minutes
Install Ansible on your own computer (Linux, macOS or WSL), not on the server:
python3 -m pip install --user ansibleCreate an inventory file, inventory.ini:
[web]
203.0.113.10 ansible_user=deployThen a playbook, site.yml:
- hosts: web
become: true
tasks:
- name: Install nginx and ufw
ansible.builtin.apt:
name: [nginx, ufw]
state: present
update_cache: true
- name: Allow SSH and HTTP through ufw
community.general.ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop: ["22", "80"]
- name: Enable ufw
community.general.ufw:
state: enabled
- name: Ensure nginx is running
ansible.builtin.service:
name: nginx
state: started
enabled: truePreview, then apply:
ansible-playbook -i inventory.ini site.yml --check --diff
ansible-playbook -i inventory.ini site.ymlRun it again and Ansible reports no changes, which is idempotency in action. Use SSH keys rather than passwords; our guide on securing SSH with keys covers the setup.
Terraform: Declare Resources and Apply
Terraform works with many providers. This small example uses the Docker provider to manage a container on a server where Docker is installed:
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:1.27"
}
resource "docker_container" "web" {
name = "web"
image = docker_image.nginx.image_id
ports {
internal = 80
external = 8080
}
}The workflow is always the same:
terraform init # download providers
terraform plan # show what will change
terraform apply # make the changes
terraform destroy # remove everything this code managesTerraform records what it created in a state file (terraform.tfstate). Protect it: it can contain sensitive values, and losing it means Terraform no longer knows what it manages. Teams usually keep state in a remote backend with locking instead of on a laptop.
Best Practices
- Keep all IaC in Git and change infrastructure only through it.
- Never commit secrets. Use Ansible Vault, environment variables or a secrets manager, and add
*.tfstateand.terraform/to.gitignore. - Always run
terraform planoransible-playbook --checkbefore applying. - Pin provider, module and collection versions to avoid surprise upgrades.
- Split code into reusable modules and roles once you repeat yourself.
- Run IaC from a CI pipeline for shared environments, so changes are reviewed and logged.
- Test on a disposable VPS before touching production, and take a snapshot first.
Want a clean server to practice on? Pick a small plan on our pricing page, point your inventory at it and rebuild it from scratch as often as you like.
FAQ
Should I learn Terraform or Ansible first?
If you mostly manage existing servers, start with Ansible: it needs only SSH and gives quick results. If you create many resources through cloud APIs, Terraform becomes valuable. Most DevOps engineers end up using both.
Is a collection of shell scripts infrastructure as code?
Partly. Scripts in Git are better than undocumented manual work, but they are usually not idempotent and do not track state, so re-running them can cause errors or duplicate changes. Purpose-built tools handle those problems for you.
Can I adopt infrastructure as code on servers that already exist?
Yes. Write Ansible playbooks that describe the current setup and run them in check mode until they report no changes. Terraform can also bring existing resources under management with its import feature.