Tests natifs Terraform (terraform test)
Depuis Terraform 1.6, les tests natifs permettent de valider la configuration sans deployer.
Fichier de test (.tftest.hcl)
# tests/vpc.tftest.hcl
run "verify_vpc_cidr" {
command = plan
assert {
condition = aws_vpc.main.cidr_block == "10.0.0.0/16"
error_message = "Le CIDR du VPC doit etre 10.0.0.0/16"
}
}
run "verify_vpc_tags" {
command = plan
assert {
condition = aws_vpc.main.tags["Environment"] == "production"
error_message = "Le tag Environment doit etre production"
}
}
run "full_apply_test" {
command = apply
assert {
condition = aws_vpc.main.id != ""
error_message = "Le VPC doit etre cree avec un ID"
}
}
# Executer les tests
terraform test
# Avec verbose
terraform test -verbose
Preconditions et postconditions
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = var.instance_type
lifecycle {
precondition {
condition = data.aws_ami.selected.architecture == "x86_64"
error_message = "L'AMI doit etre en architecture x86_64."
}
postcondition {
condition = self.public_ip != ""
error_message = "L'instance doit avoir une IP publique."
}
}
}
Terratest (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{}{
"cidr_block": "10.0.0.0/16",
"environment": "test",
},
}
defer terraform.Destroy(t, opts)
terraform.InitAndApply(t, opts)
vpcId := terraform.Output(t, opts, "vpc_id")
assert.NotEmpty(t, vpcId)
}
CI/CD Pipeline
# .github/workflows/terraform.yml
name: Terraform
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform fmt -check
- run: terraform validate
- run: terraform test
Bonne pratique : Executez terraform fmt -check, terraform validate et terraform test dans votre CI a chaque PR.