Définition
Terraform est un outil d'Infrastructure as Code (IaC) open source créé par HashiCorp. Il permet de définir, provisionner et gérer l'infrastructure cloud de manière déclarative dans des fichiers versionnes (HCL — HashiCorp Configuration Language).
Terraform supporte plus de 3000 providers (AWS, Azure, GCP, Cloudflare, GitHub, etc.), permettant de gérer n'importe quelle ressource cloud dans un seul outil.
Pourquoi Terraform ?
Sans IaC
- Infrastructure configurée manuellement via la console cloud
- Pas de versionning, pas de reproductibilite
- "Ca marchait sur mon cloud" — impossible à recréer
Avec Terraform
- Infrastructure définie dans du code (revue, versionne, teste)
- Reproductible sur n'importe quel environnement
- Plan avant apply : preview des changements
- State : Terraform sait ce qui existe et ce qui doit changer
Workflow
terraform init # Telecharger les providers
terraform plan # Previsualiser les changements
terraform apply # Appliquer les changements
terraform destroy # Supprimer toute l'infrastructure
Exemple : déployer un serveur sur AWS
# main.tf
provider "aws" {
region = "eu-west-3" # Paris
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "MonServeurWeb"
Environment = "production"
}
}
resource "aws_security_group" "web" {
name = "web-sg"
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
output "server_ip" {
value = aws_instance.web.public_ip
}
Concepts clés
State
Terraform maintient un fichier terraform.tfstate qui mappe les ressources du code aux ressources réelles dans le cloud. Le state doit être stocke de manière sécurisée (S3 + DynamoDB lock, Terraform Cloud).
Modules
Packages réutilisables de configuration Terraform :
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.0"
cidr = "10.0.0.0/16"
}
Variables et outputs
variable "environment" {
type = string
default = "staging"
}
output "db_endpoint" {
value = aws_db_instance.main.endpoint
sensitive = true
}
Terraform vs alternatives
| Terraform | Pulumi | CloudFormation | CDK | |
|---|---|---|---|---|
| Langage | HCL | Python, TS, Go | YAML/JSON | TS, Python |
| Multi-cloud | Oui | Oui | AWS only | AWS only |
| State | Fichier/Cloud | Cloud | AWS managed | AWS managed |
| Maturité | Très mature | En croissance | Mature | En croissance |