DevOpsApril 13, 202612 min read

Infrastructure Testing: Terratest, Checkov, and Validating Your IaC

Share:

Free DevOps Audit Checklist

Get our comprehensive checklist to identify gaps in your infrastructure, security, and deployment processes

Instant delivery. No spam, ever.

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

Need DevOps help?

InstaDevOps provides expert DevOps engineering starting at $2,999/mo. Skip the hiring headache.

Book a free 15-min call →

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

Ready to Transform Your DevOps?

Get started with InstaDevOps and experience world-class DevOps services.

Book a Free Call

Never Miss an Update

Get the latest DevOps insights, tutorials, and best practices delivered straight to your inbox. Join 500+ engineers leveling up their DevOps skills.

We respect your privacy. Unsubscribe at any time. No spam, ever.