Terraform

Policy as Code with Sentinel on Terraform Cloud/Enterprise: A Practical Guide

2026-04-19
NicheeLab Editorial Team

Managing infrastructure as code alone does not make it safe. You need a mechanism that mechanically enforces your organization's standards and compliance. Sentinel on Terraform Cloud/Enterprise is the Policy as Code engine for exactly this purpose: it analyzes plan results and blocks non-compliant changes.

This article walks through Sentinel's role in Terraform, when to use each evaluation data source (tfplan/v2, tfconfig/v2, tfstate/v2, tfrun), enforcement modes, policy set design, and local testing — all framed with exam-relevant angles and real-world tips.

Policy as Code and Sentinel Basics

Policy as Code is the idea of managing operational rules and compliance requirements as code, subjecting them to review, testing, and version control just like CI/CD. On Terraform Cloud/Enterprise, Sentinel fills this role and integrates directly into Terraform's run flow.

A Sentinel policy ingests Terraform data at evaluation time and uses a boolean main rule to decide pass or fail. On pass, apply continues. On fail, the run is blocked or warned depending on the enforcement mode.

  • Runtime: Built into Terraform Cloud/Enterprise (does not run on standalone OSS)
  • Evaluation timing: After plan completes, before apply (also applies to speculative plan-only runs on PRs)
  • Primary imports: tfplan/v2, tfconfig/v2, tfstate/v2, tfrun
  • Pass/fail: A true main rule passes; failure handling is controlled by the enforcement mode

Evaluation Flow and Choosing the Right Data Model

Sentinel evaluates primarily against plan output. Use tfplan/v2 for cost or diff-based decisions, tfconfig/v2 to inspect static definitions, tfstate/v2 to look at the state of existing assets, and tfrun for workspace and run metadata.

Evaluation happens at the policy set level, executing every policy attached to the target workspace in sequence. Failure behavior is determined by the enforcement mode (advisory / soft-mandatory / hard-mandatory).

  • tfplan/v2: Evaluate proposed creates/updates/deletes and attribute diffs
  • tfconfig/v2: Evaluate Terraform configuration file content (variable definitions, provider configs, etc.)
  • tfstate/v2: Reference the state at run start (existing resources)
  • tfrun: Workspace name, run type (speculative/regular), queue info, and other metadata

Terraform run and Sentinel evaluation flow

DeveloperVCS push/PRTerraform Cloud/Runterraform plangenerate tfplan/tfconfigSentinel Policiespolicy sets scopedEvaluate & Gateadvisory: warn / soft-mandatory: can be overridden / hard-mandatory: stoppass → apply / fail → stop or overrideDeveloper → Terraform Cloud/Run → Sentinel → Evaluate & Gate → apply / stop

Guardrail Design Patterns (With Examples)

Common real-world rules include required tags, region allowlists, size/class ceilings, and bans on public exposure. The standard approach is to inspect diffs via tfplan/v2. Judging on tfconfig/v2 alone can miss cases where dynamic values are not yet resolved, so evaluate against the post-plan values to be safe.

Below is an example that requires mandatory tags on AWS resources. It walks every resource change being created or updated and checks for missing tags.

  • Tags and naming conventions: are they applied to every changed resource?
  • Cost controls: reject oversized instances and expensive SKUs
  • Networking/security: detect public access and overly broad CIDRs
  • Metadata: branch on workspace name or run type via tfrun

Sentinel sample: enforce required tags (cost-center, owner)

import "tfplan/v2" as tfplan

required = ["cost-center", "owner"]

# Collect tags for every created or updated resource
changed = func() {
  resources = []
  for tfplan.resource_changes as rc {
    if rc.mode is "managed" and (rc.change.actions contains "create" or rc.change.actions contains "update") {
      resources = append(resources, rc)
    }
  }
  return resources
}

missing_tags = func() {
  violations = []
  for changed() as rc {
    # Assumes AWS's typical tags attribute (attribute name may differ by provider)
    proposed = rc.change.after.tags else {}
    for required as k {
      if not (k in keys(proposed)) or length(trim(proposed[k])) == 0 {
        violations = append(violations, sprintf("%s.%s missing tag: %s", [rc.type, rc.name, k]))
      }
    }
  }
  return violations
}

main = rule { length(missing_tags()) == 0 }

# Emit a reason on failure
violation["missing_tags"] = rule { length(missing_tags()) > 0 }

Policy Sets, Scope, and Enforcement Modes

Group policies into policy sets and attach them to the entire organization or specific workspaces. You can source from a VCS repository or upload via API/CLI. Make sure version control and review apply to policies too.

Tighten enforcement modes in steps as operational maturity grows. A realistic path is: start with advisory for visibility, move to soft-mandatory once teams are comfortable (exceptions require an explicit override by an authorized user), then graduate to hard-mandatory once things stabilize.

  • Policy set scope: all workspaces / selected workspaces
  • Version control: integrate with VCS so pull request review is mandatory
  • Modes: advisory (warn only), soft-mandatory (overridable by authorized users), hard-mandatory (must pass)

Practical Notes on Local Testing and Mocks

Test policies the same way you test application code. Use sentinel test to verify pass/fail and output, and cover representative cases with mock data. For tfplan/v2-based policies, prepare diff mocks that include creates, updates, and deletes.

It also works well to pull mocks from real Terraform Cloud/Enterprise runs and replay them in tests. Codifying representative failure cases as tests prevents future regressions.

  • sentinel fmt / sentinel test for static checks and unit tests
  • Favor representative mock patterns over minimal ones (create/update/delete, boundary pass/fail cases)
  • Watch for provider attribute name differences (tags vs labels, etc. — verify with real data)

Exam Prep Highlights and Comparison with Other Approaches

Exams frequently test which import to use for what, the differences between enforcement modes, policy set scope, and evaluation timing. On design, expect questions about whether something can be detected statically with tfconfig or should be caught as a diff with tfplan.

Terraform Cloud also offers Run Tasks, a gate for integrating external services. It is common to plug in vendor tools for cost or security and use them alongside Sentinel.

  • Evaluation timing: be able to articulate post-plan / pre-approve precisely
  • Mode behavior: differences between advisory/soft/hard and whether override is allowed
  • Prefer tfplan/v2: evaluating after values are resolved is the safer bet
ApproachPrimary evaluation target/timingGovernance characteristics
Sentinel (built into TFC/E)Evaluates tfplan/tfconfig/tfstate/tfrun after planGates with advisory/soft/hard. Policy sets scoped to org or workspaces
Run Tasks (TFC feature)Calls external services to evaluate after planApplies external vendor rules. Configurable as mandatory or optional tasks
Static linters (e.g., validate, fmt)Static checks at code-authoring time through CIDetect syntax and best-practice issues. Runtime diffs are not evaluated

Check Your Understanding

Pro

問題 1

An organization wants Terraform Cloud to flag missing tags but allow apply to proceed only when an exception request is approved. Which combination is most appropriate?

  1. Implement the policy only with tfconfig/v2 and set it to hard-mandatory
  2. Implement the policy with tfstate/v2 and set it to advisory
  3. Implement the policy with tfplan/v2 and set it to soft-mandatory
  4. Implement the policy with tfrun and set it to advisory

正解: C

Detecting missing tags based on resolved values fits tfplan/v2. The requirement to continue only on an authorized exception matches soft-mandatory (override allowed on failure). Advisory always continues, and hard-mandatory cannot continue, so neither matches the requirement.

Frequently Asked Questions

Can Sentinel be used with Terraform OSS alone?

No. Sentinel policy evaluation is a feature built into Terraform Cloud/Enterprise. It does not run on standalone Terraform OSS executions.

How do I choose between tfconfig/v2 and tfplan/v2?

Use tfconfig/v2 for statically defined conventions such as variable definitions and module composition. Use tfplan/v2 for checks that need resolved values, such as final sizes/tags or whether something is being created or updated. When in doubt, evaluate against tfplan/v2 because it holds the values finalized before apply.

How should I approach testing Sentinel policies?

Set up unit tests with sentinel test and provide mocks for representative pass and fail cases. Pulling mocks from real Terraform Cloud runs is effective for preventing regressions with scenarios close to your actual data.

Check what you learned with practice questions

Practice with certification-focused question sets

無料で問題を解いてみる
Author

NicheeLab Editorial Team

NicheeLab editorial team focused on data engineering and cloud certification learning. Content is structured around practical study needs and official exam domains.


Related articles
Terraform

HCL Syntax: Terraform's Configuration Language (2026)

HCL2 fundamentals for Terraform — blocks, attributes, expres...

Terraform

Terraform Authoring & Operations Pro: Complete Guide (2026)

Tactics for the Terraform Pro exam — module authoring, works...

Terraform

Terraform Providers: Plugin Management Fundamentals (2026)

Provider mechanics — required_providers, versions, mirrors, ...

Terraform

Terraform Resource Blocks: Declarative Infra Units (2026)

Resource block fundamentals — addresses, references, common ...

Terraform

Terraform Data Sources: Read-Only External Data (2026)

Data source basics — declaration, refresh behavior, dependen...

Browse all Terraform articles (102)
© 2026 NicheeLab All rights reserved.