terraform_validate icon indicating copy to clipboard operation
terraform_validate copied to clipboard

Validate variable values based on ".tfvars" input

Open mechastorm opened this issue 6 years ago • 0 comments

It would be helpful if we can validate terraform code based on the input file/vars it uses. Example from ".tfvars" file.

Example Code

main.tf

resource "aws_security_group" "test" {
  name        = "test"
  description = test"

  vpc_id = "${var.vpc_id}"

  ingress {
    from_port   = 1
    to_port     = 65535
    protocol    = "tcp"
    cidr_blocks = ["${var.cidr_allow}"]
  }
}

variable "cidr_allow" {}

terraform.tfvars

cidr_allow = "0.0.0.0/0"

tests.py

import os
import unittest
import terraform_validate

class TestEncryptionAtRest(unittest.TestCase):

    def setUp(self):
        # Tell the module where to find your terraform configuration folder
        self.path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"terraform")
        self.v = terraform_validate.Validator(self.path)

    def test_security_group_open_traffic(self):
        # Assert no open security traffic
        self.v.error_if_property_missing()
        self.v.enable_variable_expansion()
        self.v.resources('aws_security_group').property('ingress').property('cidr_blocks').list_should_not_contain("0.0.0.0/0")

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestEncryptionAtRest)
    unittest.TextTestRunner(verbosity=0).run(suite)

Expected

The tests to fail because the security group ingress allows "0.0.0.0/0" traffic based on the input from the terraform.tfvars

Actual

The tests pass

mechastorm avatar May 31 '18 23:05 mechastorm