Introduction
Infrastructure as Code has transformed cloud management, but when a single Terraform apply can spin up hundreds of resources, testing becomes essential.
This article explores Terratest for functional testing and Checkov for security scanning.
Static Analysis with Checkov
pip install checkov
checkov -d ./terraform
Custom Policies
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.models.enums import CheckCategories, CheckResult
class EC2HasEnvironmentTag(BaseResourceCheck):
def __init__(self):
name = "Ensure EC2 instances have environment tag"
id = "CKV_CUSTOM_1"
supported_resources = ['aws_instance']
super().__init__(name=name, id=id,
supported_resources=supported_resources)
def scan_resource_conf(self, conf):
tags = conf.get('tags', [{}])[0]
if isinstance(tags, dict) and 'Environment' in tags:
return CheckResult.PASSED
return CheckResult.FAILED
Functional Testing with Terratest
func TestS3Bucket(t *testing.T) {
t.Parallel()
terraformOptions := terraform.WithDefaultRetryableErrors(t,
&terraform.Options{
TerraformDir: "../modules/s3-bucket",
Vars: map[string]interface{}{
"bucket_name": "test-bucket-" + random.UniqueId(),
},
})
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
bucketID := terraform.Output(t, terraformOptions, "bucket_id")
actualStatus := aws.GetS3BucketVersioning(t, "us-east-1", bucketID)
assert.Equal(t, "Enabled", actualStatus)
}
When to Use Each Tool
| Aspect | Checkov | Terratest |
|---|---|---|
| Type | Static analysis | Functional testing |
| Speed | Seconds | Minutes to hours |
| Cost | Free | Incurs cloud costs |
| Coverage | Security, compliance | Actual functionality |
CI/CD Integration
jobs:
static-analysis:
steps:
- uses: bridgecrewio/checkov-action@master
with:
directory: terraform/
terratest:
needs: static-analysis
steps:
- run: |
cd test
go test -v -timeout 30m ./...
Conclusion
Layer your testing: Start with Checkov for fast feedback, add Terratest for critical modules, and run full integration tests before production.
Need Help with Your DevOps Infrastructure?
At InstaDevOps, we specialize in helping startups build production-ready infrastructure.
📅 Book a Free 15-Min Consultation
Originally published at instadevops.com
Top comments (0)