Pourquoi un backend distant ?
Le fichier terraform.tfstate contient l'etat complet de votre infrastructure. En equipe, le stocker localement pose des problemes de synchronisation et de conflit. Un backend distant resout ces problemes.
Backend S3 avec verrouillage DynamoDB
terraform {
backend "s3" {
bucket = "mon-projet-tfstate"
key = "production/terraform.tfstate"
region = "eu-west-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
Creer la table DynamoDB pour le verrouillage
resource "aws_dynamodb_table" "terraform_locks" {
name = "terraform-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
Backend GCS (Google Cloud)
terraform {
backend "gcs" {
bucket = "mon-projet-tfstate"
prefix = "production"
}
}
Commandes de gestion du state
# Lister les ressources dans le state
terraform state list
# Afficher les details d'une ressource
terraform state show aws_instance.web
# Deplacer une ressource (renommage)
terraform state mv aws_instance.old aws_instance.new
# Supprimer une ressource du state (sans la detruire)
terraform state rm aws_instance.web
# Recuperer le state distant
terraform state pull > backup.tfstate
# Pousser un state local vers le backend
terraform state push backup.tfstate
Bonne pratique : Toujours activer le chiffrement du state et le verrouillage pour eviter les corruptions en cas d'acces concurrent.