Passer au contenu principal

Production (Terraform)

Tests et validation

Terraform peut déployer de l'infrastructure en production en quelques minutes. Un test insuffisant peut coûter bien plus que les 5 minutes gagnées sur la review. L'écosystème d'outils de validation et de test Terraform s'est considérablement enrichi ces dernières années.

Validation syntaxique

# Vérifier la syntaxe HCL (sans contacter les providers)
terraform validate

# Formater le code selon le style officiel
terraform fmt
terraform fmt -recursive    # tous les sous-répertoires
terraform fmt -check        # mode CI : échoue si le code n'est pas formaté

tflint : linting avancé

# Installation via script officiel (Linux/macOS)
curl -s https://raw.githubusercontent.com/terraform-linters/tflint/master/install_linux.sh | bash

# ou via binaire GitHub Releases
TFLINT_VERSION=$(curl -s https://api.github.com/repos/terraform-linters/tflint/releases/latest | grep tag_name | cut -d'"'  -f4)
curl -Lo tflint.zip "https://github.com/terraform-linters/tflint/releases/download/${TFLINT_VERSION}/tflint_linux_amd64.zip"
unzip tflint.zip && mv tflint /usr/local/bin/ && rm tflint.zip

tflint --init       # télécharge les rulesets des providers
# .tflint.hcl
plugin "aws" {
  enabled = true
  version = "0.27.0"
  source  = "github.com/terraform-linters/tflint-ruleset-aws"
}

rule "aws_instance_invalid_type" {
  enabled = true
}
tflint
tflint --format=compact    # format CI

tflint détecte : types d'instances invalides, AMIs dépréciées, paramètres obligatoires manquants, naming conventions.

Checkov et tfsec : security scanning

pip install checkov
checkov -d .                          # scanner le répertoire courant
checkov -d . --framework terraform
checkov -d . --check CKV_AWS_8       # vérifier une règle spécifique
checkov -d . --output junitxml > checkov.xml  # rapport CI
brew install tfsec    # ou télécharger le binaire
tfsec .
tfsec . --format json | jq '.results[] | select(.severity == "HIGH")'

Ces outils détectent : buckets S3 publics, security groups ouverts sur 0.0.0.0/0, encryption désactivée, logging absent.

terraform test (Terraform 1.6+)

Terraform test permet d'écrire des tests d'intégration en HCL :

# tests/vpc.tftest.hcl
run "valid_vpc_creation" {
  command = plan

  assert {
    condition     = aws_vpc.main.cidr_block == "10.0.0.0/16"
    error_message = "Le CIDR du VPC est incorrect."
  }

  assert {
    condition     = aws_vpc.main.enable_dns_hostnames == true
    error_message = "DNS hostnames doit être activé."
  }
}

run "actual_apply" {
  command = apply

  assert {
    condition     = aws_vpc.main.id != ""
    error_message = "Le VPC n'a pas été créé."
  }
}
terraform test
terraform test -filter=tests/vpc.tftest.hcl

Terratest : tests Go

// test/vpc_test.go
package test

import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
)

func TestVpc(t *testing.T) {
    opts := &terraform.Options{
        TerraformDir: "../modules/vpc",
        Vars: map[string]interface{}{
            "name":      "test-vpc",
            "cidr_block": "10.0.0.0/16",
        },
    }
    defer terraform.Destroy(t, opts)
    terraform.InitAndApply(t, opts)

    vpcId := terraform.Output(t, opts, "vpc_id")
    assert.NotEmpty(t, vpcId)
}
go test -v -timeout 30m ./test/...

Terratest déploie réellement l'infrastructure, teste les outputs, puis la détruit. Coûteux en temps et potentiellement en argent — à réserver aux modules critiques et aux environnements de test dédiés.