How to use Terraform Sentinel for policy as code

Policy as Code (PaC) represents a revolutionary shift in how modern organizations manage and enforce security, compliance, and cost control across their cloud infrastructure. By treating policies like software—defined, versioned, and tested—PaC ensures consistency, scalability, and auditability. In the vast and dynamic landscape of cloud operations, one tool stands out for implementing PaC within the Terraform ecosystem: Terraform Sentinel.

Introduction to Policy as Code

The rise of Infrastructure as Code (IaC) tools like Terraform has enabled teams to manage infrastructure reliably through codified templates. However, managing infrastructure alone is not enough; governance must keep pace. This is where Policy as Code (PaC) enters the picture. PaC is the practice of writing, managing, and automating policy guardrails using software development workflows.

In traditional infrastructure management, policies (such as “all virtual machines must have encryption enabled” or “never deploy resources in unsupported regions”) are often enforced manually or through external, disconnected auditing tools. This is slow, error-prone, and struggles to keep up with rapid deployment cycles. PaC flips this model by embedding these rules directly into the deployment pipeline.

The importance of PaC cannot be overstated:

  • Consistency: PaC ensures that rules are applied uniformly across all environments, eliminating human error.
  • Speed: Policies are checked automatically before deployment, catching errors early when they are cheapest and easiest to fix.
  • Auditability: Policies are stored in version control (like Git), providing a clear history of changes and making compliance audits much simpler.
  • Scalability: As infrastructure grows, PaC scales seamlessly to maintain governance without adding manual overhead.

For organizations using Terraform, which is already managing their infrastructure definition, integrating a PaC tool is the logical next step. Terraform Sentinel, a governance framework integrated into the HashiCorp ecosystem, is the key tool that enables the enforcement of policies directly within the Terraform Enterprise and Terraform Cloud workflow.

Understanding Terraform Sentinel

Terraform Sentinel is an embedded policy-as-code framework used to enforce logic across the HashiCorp suite of products, but it is most tightly integrated with Terraform Cloud and Terraform Enterprise. It allows operations and security teams to define fine-grained, logic-based policies that govern infrastructure provisioning.

When a user initiates a Terraform run (a plan or apply), Sentinel automatically evaluates the proposed changes against predefined policies. Instead of waiting for an auditor to check compliance days or weeks later, Sentinel provides immediate feedback, often blocking non-compliant infrastructure from ever being deployed.

Sentinel is written in a proprietary, Go-like language designed to be easy to read and focused on evaluating data structures, which, in the context of Terraform, are the plan files.

The core components of Sentinel include:

  • Policies: These are the Sentinel code files themselves, containing the rules and logic to be enforced. Policies evaluate whether a Terraform plan is compliant.
  • Imports: Sentinel policies gain access to data about the Terraform run (such as the proposed infrastructure changes, variables, and modules) through imports. The primary import for Terraform is tfplan, which exposes the entire plan file structure for inspection.
  • Rules: Policies are built from rules—Boolean expressions that define whether a specific condition is met. A policy passes if its main rule evaluates to true; otherwise, it fails and can prevent the infrastructure apply from proceeding.

Setting Up Your Sentinel Environment

Sentinel policies are managed within Terraform Cloud or Terraform Enterprise workspaces. Setting up the environment involves integrating your policy code repository and configuring the enforcement levels for your policies.

Detail the steps for enabling Sentinel in your Terraform Cloud/Enterprise workspace:

  • Link VCS: Ensure your Terraform Cloud or Enterprise account is linked to a Version Control System (VCS) like GitHub or GitLab.
  • Create Policy Set: Policies are grouped into “Policy Sets” in the Terraform application. You link a policy set to a VCS repository where your Sentinel policies are stored.
  • Define Scopes: You must then define which workspaces or projects the policy set applies to. A policy set can govern a single workspace, a selection of workspaces, or all workspaces within an organization.
  • Configure Enforcement: For each policy within the set, you assign an enforcement level, which dictates how Sentinel will act when the policy fails.

Outline how to structure and store your Sentinel policy files:

Sentinel policies are typically stored in a dedicated repository separate from the Terraform configuration files. A common structure includes:

/policies_repo
/policy_set_name
/enforce_s3_encryption
policy.sentinel
test/
/require_tags
policy.sentinel
test/
sentinel.hcl (defines configuration for the policy set)

The sentinel.hcl file specifies where policies are located and their names, helping Terraform Cloud map the VCS repository structure to runnable policies.

Writing Your First Sentinel Policy

Sentinel policies allow you to write detailed logic against the resource attributes in the Terraform plan. A fundamental policy every organization needs is one that enforces mandatory resource tagging for cost allocation and operational insight.

Provide an example of a simple policy, like enforcing tag requirements:

A simple policy might enforce that all AWS EC2 instances must include a tag named Owner and a tag named Environment.

import "tfplan"
import "strings"Define the required tags

required_tags = ["Owner", "Environment"]Function to check if a resource has all required tags

check_tags = rule {
all tfplan.resource_changes as address, rc {
# Only evaluate creation or updates of AWS EC2 instances
rc.type is "aws_instance" and (rc.change.actions contains "create" or rc.change.actions contains "update")``` 
# Check if the resource has tags configured
rc.change.after.tags else {} is tags {
  # Check if all required tags are present in the 'tags' map
  all required_tags as rt {
    tags contains rt
  }
}

```}
}

main = rule {
check_tags
}

If any new or updated AWS instance lacks either the Owner or Environment tag, the check_tags rule fails, and consequently, the main rule fails, blocking the application of the infrastructure changes.

Explain common Sentinel functions and language syntax:

The Sentinel language provides powerful functions for list processing and string manipulation:

  • all and any: These are used for iterating over collections (like resource changes) and checking if all items or any items meet a specified condition.
  • filter: Used to create a new list containing only elements from the original list that satisfy a given expression.
  • strings.contains(): Useful for checking if a string includes a specific substring, often used when validating resource names.
  • tfplan.resource_changes: This is the core import, a map of all resources in the plan, allowing you to access their type, address, and proposed changes (rc.change.after or rc.change.before).

Testing and Enforcement

Writing policies is only half the battle; ensuring they work as intended is crucial. Sentinel offers mechanisms for local testing and different enforcement paradigms.

Discuss how to test policies locally before deployment:

The Sentinel CLI allows developers to run policy checks on their local machines before pushing code to the centralized VCS repository. This is vital for maintaining a fast feedback loop.

  • Mock Data: Local testing requires “mock data,” which are sample Terraform plan files (tfplan JSON output) representing scenarios where the policy should pass and scenarios where it should fail.
  • Testing Workflow: The command sentinel test [policy-directory] executes the policy against the mock data, reporting whether the rules pass or fail based on the predefined test cases. This integration into the local development workflow significantly reduces deployment risk.

Explain the different enforcement levels:

Terraform Sentinel provides granular control over how a policy failure affects the run. The three main enforcement levels are:

  • Advisory: The weakest level. If the policy fails, the Terraform run continues, but a warning is logged. This is often used for new policies during an introductory phase to gather data without disrupting operations.
  • Soft-Mandatory: If the policy fails, the user is notified and given the option to override the policy failure, usually requiring justification or a specific permission level. This is useful for high-priority rules with legitimate exceptions.
  • Hard-Mandatory: The strictest level. If the policy fails, the Terraform run is immediately blocked, and the infrastructure apply cannot proceed. This is reserved for critical security and compliance policies (e.g., “no public S3 buckets”).

Advanced Sentinel Use Cases

Once basic policies are in place, Sentinel’s power can be leveraged for more complex governance requirements.

Suggest more complex policies, such as cost control or security compliance checks:

  • Cost Control: Policies can be written to limit the size or type of compute resources. For example, blocking the creation of expensive virtual machine types (e.g., t3.2xlarge) unless explicitly authorized, or ensuring all database instances are configured with a mandatory maximum IOPS limit.
  • Security Compliance: Advanced security checks include ensuring network security groups only open specific ports (e.g., blocking port 22 access from 0.0.0.0/0), or verifying that all resources created in a production environment are associated with specific compliance certifications or audit logs.
  • Module Usage Enforcement: Sentinel can force teams to use pre-approved, well-governed modules instead of writing bespoke resource blocks, ensuring consistency in configuration across the organization.

Mention integrating Sentinel with other tools or reporting mechanisms:

While Sentinel lives within Terraform Cloud/Enterprise, its results are often critical for broader compliance reporting. Integration possibilities include:

  • Reporting Dashboards: Using webhooks or API access to pull Sentinel policy failure data into centralized reporting tools like Splunk or dedicated compliance dashboards.
  • Ticketing Systems: Integrating policy failures with tools like Jira or ServiceNow to automatically generate tickets when a soft-mandatory policy is overridden, ensuring that exceptions are properly documented and reviewed.

A Quick Safety Checklist

  • Is your Policy Set linked to the correct repository?
  • Are the enforcement levels (Advisory, Soft, Hard) set appropriately for the risk level of each policy?
  • Have you run local Sentinel tests against both passing and failing mock data scenarios?
  • Are critical security policies set to Hard-Mandatory?
  • Are policy exceptions documented and managed via Soft-Mandatory enforcement?

Conclusion and Final Thoughts

Terraform Sentinel transforms infrastructure governance from a post-deployment audit activity into a proactive, preventative gatekeeping process. By integrating policy enforcement directly into the Terraform workflow, organizations achieve greater security, better cost management, and streamlined compliance. Mastering Sentinel is crucial for any organization operating at scale with Terraform Cloud or Enterprise, turning policy definition from a burdensome manual task into codified, reliable, and scalable governance.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.