1. Static analysis #
Even before the plan.
Tools #
terraform fmt -check -recursive
terraform validate
tflint --init && tflint --recursive
checkov -d . # ou : trivy config .2. Native tests #
terraform test.
Example #
# tests/app.tftest.hcl
mock_provider "aws" {
mock_resource "aws_instance" { defaults = { id = "i-0123456789" } }
}
variables { environnement = "recette" }
run "une_seule_instance_en_recette" {
command = plan
assert {
condition = length(aws_instance.web) == 1
error_message = "Une instance en recette."
}
}
run "refuse_un_environnement_inconnu" {
command = plan
variables { environnement = "demo" }
expect_failures = [var.environnement]
}Real tests: Tests can also run against an emulator (LocalStack) or a real test account with command = apply: they create and then destroy the resources.
3. Guardrails in the code #
Preconditions, check, secrets.
Examples #
resource "aws_instance" "web" {
instance_type = var.type
lifecycle {
precondition {
condition = !startswith(var.type, "p5")
error_message = "Pas d'instance GPU coûteuse ici."
}
}
}
check "site_repond" {
data "http" "accueil" { url = "https://${aws_lb.web.dns_name}/healthz" }
assert {
condition = data.http.accueil.status_code == 200
error_message = "Le site ne répond pas."
}
}- Sensitive variables marked
sensitive = true; values supplied by the CI or a vault (Vault, secrets manager), never in the code. - Terraform 1.10+: ephemeral values (
ephemeral) that are never written to the state.
