Pourquoi Terraform ?
L'Infrastructure as Code — traiter l'infra comme du code.
Sans IaC, l'infrastructure est créée manuellement via des consoles web ou des scripts. C'est fragile, non reproductible et impossible à auditer. Terraform permet de décrire l'infrastructure souhaitée en code HCL, et de la créer/modifier/détruire de façon reproductible.
| Déclaratif | Vous décrivez quoi vous voulez, pas comment le créer. Terraform calcule les différences. |
| Multi-cloud | AWS, GCP, Azure, Kubernetes, GitHub, Datadog… via des providers. |
| Idempotent | Exécuter apply deux fois ne crée pas deux fois la même ressource. |
| Plan avant action | terraform plan affiche exactement ce qui va changer — avant de toucher quoi que ce soit. |
Installation & Configuration
Préparer son environnement de travail.
# Ajout du dépôt HashiCorp sudo yum install -y yum-utils sudo yum-config-manager --add-repo \ https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo # Installation sudo yum install terraform -y # Vérification terraform version Terraform v1.8.x
# Option 1 : variables d'environnement export AWS_ACCESS_KEY_ID="AKIA..." export AWS_SECRET_ACCESS_KEY="wJalr..." export AWS_DEFAULT_REGION="eu-west-3" # Option 2 : AWS CLI (recommandée) aws configure # Option 3 : IAM Role sur EC2 (production) # Attacher un rôle IAM à l'instance — aucune clé à gérer
Syntaxe HCL — HashiCorp Configuration Language
Le langage déclaratif de Terraform.
# Structure : TYPE "PROVIDER_TYPE" "NOM_LOCAL" { ... } resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" tags = { Name = "mon-serveur-web" Env = "production" } } # Référencer une autre ressource : TYPE.NOM.ATTRIBUT resource "aws_eip" "ip" { instance = aws_instance.web.id }
# Chaînes name = "mon-app" # Interpolation name = "${var.env}-mon-app" # Nombres count = 3 # Booléens enabled = true # Liste availability_zones = ["eu-west-3a", "eu-west-3b"] # Map tags = { Team = "platform" Project = "backend" } # Fonctions bucket_name = lower(join("-", [var.env, "mon-bucket"]))
Cycle de vie Terraform
Les 4 commandes fondamentales — à mémoriser.
| terraform init | Initialise le répertoire de travail, télécharge les providers et les modules. Toujours la première commande. |
| terraform validate | Vérifie la syntaxe HCL sans contacter les APIs cloud. |
| terraform fmt | Formate automatiquement les fichiers .tf selon le style canonique. |
| terraform plan | Calcule et affiche les changements à appliquer. Rien n'est modifié. |
| terraform plan -out=tfplan | Sauvegarde le plan dans un fichier pour un apply déterministe. |
| terraform apply | Applique les changements (demande confirmation). Crée/modifie/détruit. |
| terraform apply -auto-approve | Apply sans confirmation — à réserver aux pipelines CI/CD. |
| terraform apply tfplan | Applique un plan préalablement sauvegardé. |
| terraform destroy | Détruit toutes les ressources gérées par cette configuration. |
| terraform show | Affiche l'état actuel (state) en format lisible. |
| terraform output | Affiche les valeurs des outputs définis. |
Terraform will perform the following actions: # aws_instance.web will be created + resource "aws_instance" "web" { + id = (known after apply) + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t3.micro" } # aws_security_group.allow_http will be updated ~ resource "aws_security_group" "allow_http" { ~ name = "old-name" -> "new-name" } # aws_s3_bucket.old will be destroyed - resource "aws_s3_bucket" "old" { - id = "mon-old-bucket" } Plan: 1 to add, 1 to change, 1 to destroy.
apply. Un - rouge signifie destruction de ressource. Les bases de données détruites ne se récupèrent pas facilement.Providers
Les plugins qui connectent Terraform aux APIs cloud.
Un provider est un plugin qui sait parler à une API spécifique (AWS, Azure, Kubernetes, GitHub…). On le déclare dans un bloc terraform et Terraform le télécharge lors du init.
terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } # Configuration du provider AWS provider "aws" { region = "eu-west-3" # Paris # Tags appliqués à toutes les ressources default_tags { tags = { ManagedBy = "Terraform" Project = "mon-projet" } } }
Resources & Data Sources
Créer des ressources ou lire des ressources existantes.
# Bucket S3 resource "aws_s3_bucket" "assets" { bucket = "mon-app-assets-${var.env}" } # Security Group resource "aws_security_group" "web" { name = "sg-web-${var.env}" vpc_id = aws_vpc.main.id # référence ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } }
Les data sources permettent de lire des informations de ressources déjà créées (hors Terraform).
# Lire la dernière AMI Amazon Linux 2023 data "aws_ami" "amazon_linux" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al2023-ami-*-x86_64"] } } # Utiliser dans une resource resource "aws_instance" "web" { ami = data.aws_ami.amazon_linux.id instance_type = "t3.micro" }
Variables & Outputs
Paramétrer la configuration et exporter les valeurs importantes.
variable "env" { description = "Environnement de déploiement" type = string default = "dev" validation { condition = contains(["dev", "staging", "prod"], var.env) error_message = "env doit être dev, staging ou prod." } } variable "instance_type" { description = "Type d'instance EC2" type = string default = "t3.micro" } variable "allowed_cidrs" { description = "CIDRs autorisés pour SSH" type = list(string) default = ["10.0.0.0/8"] }
env = "prod" instance_type = "t3.large" allowed_cidrs = ["82.64.0.0/16"]
terraform apply -var-file=prod.tfvars
output "instance_public_ip" { description = "IP publique de l'instance EC2" value = aws_instance.web.public_ip } output "bucket_arn" { description = "ARN du bucket S3" value = aws_s3_bucket.assets.arn } output "db_password" { description = "Mot de passe DB" value = aws_db_instance.main.password sensitive = true # masqué dans les logs }
État (State)
Le fichier terraform.tfstate — la source de vérité de Terraform.
Terraform maintient un fichier d'état (terraform.tfstate) qui mappe votre configuration HCL aux ressources réelles dans le cloud. C'est grâce à cet état qu'il sait quoi créer, modifier ou détruire.
.gitignore.En équipe, le state doit être partagé et verrouillé. La solution standard sur AWS est S3 (stockage) + DynamoDB (verrouillage).
terraform { backend "s3" { bucket = "mon-projet-tfstate" key = "prod/terraform.tfstate" region = "eu-west-3" encrypt = true # Verrouillage pour éviter les conflits en équipe dynamodb_table = "terraform-state-lock" } }
| terraform state list | Liste toutes les ressources dans le state. |
| terraform state show aws_instance.web | Affiche les détails d'une ressource dans le state. |
| terraform state rm aws_instance.old | Retire une ressource du state sans la détruire (pour import manuel). |
| terraform import aws_instance.web i-1234567890 | Importe une ressource existante dans le state. |
| terraform refresh | Synchronise le state avec l'état réel du cloud. |
Modules
Encapsuler et réutiliser des blocs d'infrastructure.
Un module est un répertoire de fichiers .tf qui peut être réutilisé comme une fonction. Vous définissez des inputs (variables) et des outputs — et l'appelant passe les valeurs.
# Module local module "web" { source = "../../modules/ec2-web" # Variables d'entrée du module env = "prod" instance_type = "t3.large" key_name = "prod-key" } # Module public (Terraform Registry) module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "~> 5.0" name = "mon-vpc" cidr = "10.0.0.0/16" azs = ["eu-west-3a", "eu-west-3b"] private_subnets = ["10.0.1.0/24", "10.0.2.0/24"] public_subnets = ["10.0.10.0/24", "10.0.11.0/24"] } # Utiliser les outputs du module output "vpc_id" { value = module.vpc.vpc_id }
Workspaces
Gérer plusieurs environnements avec le même code.
| terraform workspace list | Liste les workspaces (default + créés). |
| terraform workspace new staging | Crée un nouveau workspace staging. |
| terraform workspace select prod | Bascule vers le workspace prod. |
| terraform workspace show | Affiche le workspace courant. |
# terraform.workspace retourne "default", "staging", "prod"… resource "aws_instance" "web" { instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro" tags = { Environment = terraform.workspace } }
Projet : VPC + EC2 + Nginx sur AWS
Provisionner une infra AWS complète avec Terraform.
Structure du projet
infra-aws/ ├── main.tf ← VPC, subnets, EC2 ├── variables.tf ← paramètres ├── outputs.tf ← IP publique ├── versions.tf ← provider AWS └── terraform.tfvars
main.tf — VPC, subnets, SG et EC2
# ── VPC ──────────────────────────────────────────── resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = true tags = { Name = "vpc-${var.env}" } } resource "aws_subnet" "public" { vpc_id = aws_vpc.main.id cidr_block = "10.0.1.0/24" availability_zone = "eu-west-3a" map_public_ip_on_launch = true tags = { Name = "subnet-public-${var.env}" } } resource "aws_internet_gateway" "igw" { vpc_id = aws_vpc.main.id } resource "aws_route_table" "public" { vpc_id = aws_vpc.main.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.igw.id } } resource "aws_route_table_association" "public" { subnet_id = aws_subnet.public.id route_table_id = aws_route_table.public.id } # ── Security Group ───────────────────────────────── resource "aws_security_group" "web" { name = "sg-web-${var.env}" vpc_id = aws_vpc.main.id ingress { from_port=80 to_port=80 protocol="tcp" cidr_blocks=["0.0.0.0/0"] } ingress { from_port=22 to_port=22 protocol="tcp" cidr_blocks=var.allowed_cidrs } egress { from_port=0 to_port=0 protocol="-1" cidr_blocks=["0.0.0.0/0"] } } # ── EC2 Instance ─────────────────────────────────── data "aws_ami" "al2023" { most_recent = true; owners = ["amazon"] filter { name="name" values=["al2023-ami-*-x86_64"] } } resource "aws_instance" "web" { ami = data.aws_ami.al2023.id instance_type = var.instance_type subnet_id = aws_subnet.public.id vpc_security_group_ids = [aws_security_group.web.id] key_name = var.key_name # Script exécuté au premier démarrage user_data = <<-EOF #!/bin/bash yum update -y yum install nginx -y systemctl start nginx systemctl enable nginx EOF tags = { Name = "web-${var.env}" } }
Déploiement
# Initialiser le projet terraform init # Valider la syntaxe terraform validate # Prévisualiser terraform plan -var-file=prod.tfvars # Appliquer (crée le VPC, subnet, SG, EC2…) terraform apply -var-file=prod.tfvars # Récupérer l'IP publique terraform output instance_public_ip 54.210.88.12 # Tester : http://54.210.88.12 → page Nginx !
Nettoyage
# Détruit TOUTES les ressources créées (économise les coûts AWS) terraform destroy -var-file=prod.tfvars
destroy en production sans revue. Toujours utiliser plan d'abord pour confirmer ce qui sera supprimé.