Structure de projet recommandee
infrastructure/
├── environments/
│ ├── dev/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── terraform.tfvars
│ │ └── backend.tf
│ ├── staging/
│ └── prod/
├── modules/
│ ├── networking/
│ ├── compute/
│ └── database/
└── README.md
Conventions de nommage
# Ressources : snake_case
resource "aws_instance" "web_server" { }
resource "aws_security_group" "allow_http" { }
# Variables : snake_case, prefixees par contexte
variable "vpc_cidr_block" { }
variable "db_instance_type" { }
# Fichiers : snake_case.tf
# main.tf, variables.tf, outputs.tf, providers.tf, backend.tf
Workspaces
# Un workspace par environnement
terraform workspace new dev
terraform workspace new staging
terraform workspace new prod
terraform workspace list
terraform workspace select prod
# Utiliser dans le code
resource "aws_instance" "web" {
instance_type = terraform.workspace == "prod" ? "t2.large" : "t2.micro"
tags = {
Environment = terraform.workspace
}
}
Securite
- Ne commitez jamais terraform.tfstate dans Git
- Ajoutez au
.gitignore:*.tfstate*,.terraform/,*.tfvars(si contient des secrets) - Utilisez des variables d'environnement pour les credentials
- Chiffrez le state remote
- Activez le state locking (DynamoDB pour S3)
.gitignore pour Terraform
# .gitignore
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
!example.tfvars
.terraform.lock.hcl
crash.log
Integrer a la CI/CD
# .gitlab-ci.yml simplifie
stages:
- validate
- plan
- apply
terraform-validate:
stage: validate
script:
- terraform init -backend=false
- terraform validate
- terraform fmt -check
terraform-plan:
stage: plan
script:
- terraform init
- terraform plan -out=plan.tfplan
artifacts:
paths:
- plan.tfplan
terraform-apply:
stage: apply
script:
- terraform apply plan.tfplan
when: manual
only:
- main
Check-list :
- State remote + locking
- .gitignore configure
- Modules pour la reutilisabilite
- CI/CD avec validate + plan + apply manuel
- Revue de code sur les plans