How to Use Sentinel in Terraform for Policy as Code
To use
Sentinel in Terraform, you write policy rules in the Sentinel language and integrate them with Terraform Cloud or Enterprise to enforce governance on infrastructure changes. Sentinel policies evaluate Terraform plans and can block changes that don't meet your rules before applying them.Syntax
Sentinel policies use a simple language to define rules that check Terraform plans or states. The main parts are:
- import: brings in Terraform data to check
- main rule: the rule that returns true or false to allow or deny
- expressions: conditions using data from Terraform
sentinel
import "tfplan" main = rule { all tfplan.resource_changes["aws_instance"] as _, rc { rc.change.actions contains "create" } }
Example
This example policy allows creating AWS instances only if their instance type is t2.micro. It checks the Terraform plan and denies changes that create instances with other types.
sentinel
import "tfplan" main = rule { all tfplan.resource_changes as _, rc { if rc.type is "aws_instance" and rc.change.actions contains "create" { rc.change.after.instance_type is "t2.micro" } else { true } } }
Output
Policy check failed: aws_instance instance type must be t2.micro
Common Pitfalls
Common mistakes when using Sentinel with Terraform include:
- Not importing the correct Terraform data source like
tfplanortfstate. - Writing rules that always return true or false, which disables policy enforcement.
- Forgetting to test policies locally before applying in Terraform Cloud.
- Misunderstanding resource change structures, causing incorrect checks.
sentinel
import "tfplan" # Wrong: always allow main = rule { true } # Right: check instance type main = rule { all tfplan.resource_changes as _, rc { if rc.type is "aws_instance" and rc.change.actions contains "create" { rc.change.after.instance_type is "t2.micro" } else { true } } }
Quick Reference
| Concept | Description |
|---|---|
| import | Load Terraform data like tfplan or tfstate |
| main rule | The policy's main condition that returns true or false |
| resource_changes | List of resources changed in the Terraform plan |
| actions | Actions on resources: create, update, delete |
| after | Resource attributes after the change |
| each/all | Loops to check multiple resources |
Key Takeaways
Sentinel policies in Terraform enforce rules by evaluating plans before apply.
Use the tfplan import to access planned resource changes in your policy.
Write a main rule that returns true to allow or false to deny changes.
Test policies locally with Sentinel CLI before using in Terraform Cloud.
Avoid always-true or always-false rules to ensure effective policy enforcement.