Skip to main content

Define a Policy

Styra DAS provides a library of built-in Terraform rules for AWS, GCP, and Azure, which you can explore in the Terraform Policy Library Rules documentation.

Since we're using the Terraform Fake Web Services provider, we'll instead create a simple custom policy for the fake VPC resource.

Create the policy

  1. In your Terraform system in Styra DAS, use the left-side file tree and navigate to the policy directory.

  2. Click on the options menu on the policy directory and select Add Policy.

  3. Enter a path of fws/vpc and a module name of rules.rego, then click Add.

Decision Input Format

As part of the Run Task integration with DAS, Terraform Cloud will send DAS the plan details and context for each run. Within DAS, you can use rego policies to evaluate properties of this data, which is available via the input parameter in the following format:

{
"format_version": "1.0",
"terraform_version": "1.1.9",
"configuration": {},
"prior_state": {},
"planned_values": {},
"resource_changes": [],
"variables": {},
"styra-tfc-webhook": {
"access_token": "",
"organization_name": "",
"plan_json_api_url": "",
"run_app_url": "",
"run_created_at": "",
"run_created_by": "",
"run_id": "",
"run_message": "",
"task_result_callback_url": "",
"task_result_id": "",
"workspace_app_url": "",
"workspace_id": "",
"workspace_name": ""
}
}

Full details of Terraform's plan data can be found in the Plan Representation Terraform documentation.

Add a rule

In the new fws/vpc/rules.rego policy file, add the following rule:

enforce[decision] {
resource := input.planned_values.root_module.resources[0]
resource.type == "fakewebservices_vpc"
resource.values.cidr_block == "10.0.0.0/16"

message := "VPC CIDR of 10.0.0.0/16 is not allowed"

decision := {
"allowed": false,
"message": message
}
}

This rule prevents using 10.0.0.0/16 for a VPC's CIDR block for the Fake Web Services provder. This is done by evaluating the properties of the resources in the root module (i.e., main.tf) which DAS receives in the plan JSON from Terraform Cloud. For this demo, since we have only the VPC resource in our root module, the rule checks if that resource is the VPC resource and then checks the CIDR block value. If both of these conditions match, the rule will not allow the resource change.

This rule is in Enforce mode, which means when it is evaluated against a Terraform plan, the plan will fail the policy check if the rule generates a violation.

Rules can also be in Monitor mode, which will not prevent the full policy check to pass, but Styra DAS will generate warnings.

Publish the policy

To make this policy live, click on the Publish button and confirm. Your policy will now be enforced on the the next Terraform plan and apply command.