Bird
Raised Fist0
Terraformcloud~15 mins

Sentinel policy as code in Terraform - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Sentinel policy as code
What is it?
Sentinel policy as code is a way to write rules that control how cloud infrastructure is created and managed. These rules are written in a simple language and automatically check if your infrastructure setup follows your organization's standards. It helps prevent mistakes and enforces security by stopping bad configurations before they happen. Think of it as a smart gatekeeper for your cloud resources.
Why it matters
Without Sentinel policies, teams might create cloud resources that are insecure, costly, or not compliant with company rules. This can lead to security breaches, unexpected bills, or downtime. Sentinel policies help catch these issues early, saving time, money, and headaches. They make cloud management safer and more reliable by automating checks that humans might forget or miss.
Where it fits
Before learning Sentinel policies, you should understand basic cloud infrastructure and how Terraform manages resources. After mastering Sentinel, you can explore advanced governance, compliance automation, and integrating policies into continuous delivery pipelines. Sentinel sits between writing infrastructure code and deploying it safely.
Mental Model
Core Idea
Sentinel policy as code is like writing clear rules that automatically check and approve your cloud setup before it is created.
Think of it like...
Imagine you have a checklist for packing a suitcase before a trip. Sentinel is like a smart assistant that reads your checklist and stops you if you forget something important or pack something forbidden.
┌───────────────────────────────┐
│ Terraform Infrastructure Code  │
└──────────────┬────────────────┘
               │
               ▼
┌───────────────────────────────┐
│ Sentinel Policy as Code Rules  │
│ - Security checks             │
│ - Cost limits                 │
│ - Naming conventions          │
└──────────────┬────────────────┘
               │
               ▼
┌───────────────────────────────┐
│ Deployment Approval or Rejection│
└───────────────────────────────┘
Build-Up - 6 Steps
1
FoundationWhat is Sentinel Policy as Code
🤔
Concept: Introducing Sentinel as a tool to write rules that check cloud infrastructure before deployment.
Sentinel is a policy framework integrated with Terraform that lets you write rules in a simple language. These rules check your infrastructure plans to make sure they follow your organization's requirements. For example, a rule can block creating servers in certain regions or require tags for cost tracking.
Result
You understand Sentinel is a safety net that reviews your infrastructure plans automatically.
Knowing Sentinel acts as an automatic reviewer helps you see how it prevents mistakes before they happen.
2
FoundationBasic Structure of a Sentinel Policy
🤔
Concept: Understanding the parts of a Sentinel policy: rules, imports, and enforcement levels.
A Sentinel policy has rules written in a simple language. It can import data from Terraform plans and other sources. Each rule returns true or false. Policies can be set to enforce strictly or warn only. For example, a rule might check if all resources have a 'cost-center' tag.
Result
You can read and write simple Sentinel policies that check one condition.
Seeing the simple true/false nature of rules clarifies how policies decide to allow or block actions.
3
IntermediateUsing Sentinel with Terraform Plans
🤔Before reading on: do you think Sentinel checks happen before or after Terraform creates resources? Commit to your answer.
Concept: How Sentinel integrates with Terraform to check plans before deployment.
Terraform creates a plan showing what changes it will make. Sentinel reads this plan and applies policies to it. If any policy fails, Terraform can stop the deployment. This means Sentinel acts as a gatekeeper before any real changes happen in the cloud.
Result
You understand Sentinel prevents bad infrastructure changes by checking plans first.
Knowing Sentinel works on plans, not live resources, explains why it can stop problems early and cheaply.
4
IntermediateCommon Policy Examples and Patterns
🤔Before reading on: do you think policies should block all non-compliant changes or just warn? Commit to your answer.
Concept: Typical rules organizations use to enforce security, cost, and compliance.
Common policies include requiring tags on resources, limiting regions where resources can be created, restricting instance sizes, and preventing public IP addresses. Policies can either block changes or just warn users to review. This flexibility helps teams balance safety and speed.
Result
You can write policies that enforce real-world rules and understand when to block or warn.
Understanding policy patterns helps you design rules that fit your organization's risk tolerance and workflow.
5
AdvancedPolicy Testing and Version Control
🤔Before reading on: do you think policies should be tested like code? Commit to your answer.
Concept: How to write tests for Sentinel policies and manage them with version control.
Policies are code and should be tested to ensure they work as expected. Sentinel supports writing test cases with sample data. Storing policies in version control like Git allows tracking changes and collaboration. This practice prevents errors and keeps policies reliable over time.
Result
You know how to maintain high-quality policies that evolve safely.
Treating policies as code with tests and version control raises their quality and trustworthiness.
6
ExpertAdvanced Policy Logic and Data Sources
🤔Before reading on: do you think Sentinel can use external data to make decisions? Commit to your answer.
Concept: Using complex logic and external data in policies for dynamic enforcement.
Sentinel can import data from external sources like APIs or files to make decisions. For example, a policy can check a live list of approved IP addresses or cost budgets. It supports loops, conditionals, and functions to build complex rules. This allows policies to adapt to changing organizational needs.
Result
You can create powerful, context-aware policies that go beyond static checks.
Knowing Sentinel can use external data unlocks dynamic governance that reacts to real-time information.
Under the Hood
Sentinel runs as a separate evaluation engine that reads Terraform plans as JSON data. It parses the policy code and applies rules to the plan's resource definitions. Each rule returns a boolean result. Sentinel aggregates these results to decide if the plan passes or fails. This happens before Terraform applies changes, ensuring no disallowed changes reach the cloud.
Why designed this way?
Sentinel was designed to integrate tightly with Terraform's plan phase to catch issues early without changing Terraform's core. Using a separate policy language allows flexibility and security, as policies can be updated independently. The design balances power, safety, and ease of use, avoiding complex changes to Terraform itself.
Terraform Plan JSON ──▶ Sentinel Engine ──▶ Policy Rules Evaluation ──▶ Pass/Fail Decision
       │                          │                         │
       ▼                          ▼                         ▼
  Infrastructure           Policy Code (Rules)       Deployment Allowed?
    Changes                 (Boolean Logic)            Yes or No
Myth Busters - 4 Common Misconceptions
Quick: Does Sentinel change your cloud resources directly? Commit to yes or no.
Common Belief:Sentinel modifies or creates cloud resources to enforce policies.
Tap to reveal reality
Reality:Sentinel only reads Terraform plans and approves or blocks changes; it does not modify resources.
Why it matters:Thinking Sentinel changes resources can lead to confusion about its role and cause misuse or misplaced trust.
Quick: Can Sentinel policies run after deployment to fix issues? Commit to yes or no.
Common Belief:Sentinel can fix or correct infrastructure after deployment automatically.
Tap to reveal reality
Reality:Sentinel only evaluates plans before deployment; it cannot fix or change deployed resources.
Why it matters:Expecting automatic fixes can cause reliance on Sentinel for remediation, which it does not provide.
Quick: Are Sentinel policies always strict blockers? Commit to yes or no.
Common Belief:All Sentinel policies must block non-compliant changes.
Tap to reveal reality
Reality:Policies can be set to warn only, allowing flexibility in enforcement.
Why it matters:Assuming all policies block can lead to overly rigid workflows or ignoring warnings.
Quick: Can Sentinel policies use live external data during evaluation? Commit to yes or no.
Common Belief:Sentinel cannot access external data sources during policy evaluation.
Tap to reveal reality
Reality:Sentinel can import external data, enabling dynamic and context-aware policies.
Why it matters:Not knowing this limits policy design and misses opportunities for advanced governance.
Expert Zone
1
Sentinel policies run in a sandboxed environment to ensure security and prevent side effects during evaluation.
2
Policy failures can be scoped to specific workspaces or teams, allowing tailored governance without blocking all deployments.
3
Sentinel supports policy sets that combine multiple policies with different enforcement levels for flexible governance.
When NOT to use
Sentinel is not suitable for real-time monitoring or fixing deployed resources. For runtime security or remediation, use tools like cloud-native security services or configuration management agents.
Production Patterns
In production, teams integrate Sentinel policies into CI/CD pipelines to automatically check infrastructure changes. Policies are versioned and tested alongside Terraform code. Organizations use policy sets to enforce layered rules, such as security, cost, and compliance, with different enforcement levels per environment.
Connections
Access Control Lists (ACLs)
Both enforce rules to allow or deny actions based on defined policies.
Understanding ACLs helps grasp how Sentinel acts as a gatekeeper, deciding what infrastructure changes are permitted.
Unit Testing in Software Development
Sentinel policy testing is similar to writing unit tests to verify code correctness.
Knowing software testing principles helps appreciate why policies need tests to ensure reliable enforcement.
Quality Control in Manufacturing
Sentinel policies act like quality inspectors that check products before shipping.
Seeing Sentinel as a quality control step highlights its role in preventing defects before they reach customers.
Common Pitfalls
#1Writing policies that are too strict and block all changes without exceptions.
Wrong approach:main = rule { all resources must have a 'cost-center' tag and be in 'us-east-1' region }
Correct approach:main = rule { all resources must have a 'cost-center' tag and (resource.region is 'us-east-1' or resource.region is 'us-west-2') }
Root cause:Misunderstanding the need for flexibility in policies to accommodate valid exceptions.
#2Not testing policies before applying them, leading to unexpected deployment failures.
Wrong approach:Deploying new policies directly without test cases or validation.
Correct approach:Writing Sentinel test cases with sample data and running them before applying policies.
Root cause:Treating policies as informal rules rather than code that requires testing.
#3Assuming Sentinel can fix infrastructure issues automatically after deployment.
Wrong approach:Expecting Sentinel to remediate non-compliant resources post-deployment.
Correct approach:Using Sentinel only to block or warn before deployment and employing other tools for remediation.
Root cause:Confusing policy enforcement with automated remediation capabilities.
Key Takeaways
Sentinel policy as code lets you write automated rules that check your cloud infrastructure plans before deployment.
It acts as a gatekeeper, preventing mistakes and enforcing company standards early and cheaply.
Policies are simple true/false rules that can be tested and version-controlled like software code.
Sentinel integrates tightly with Terraform plans but does not modify resources or fix issues after deployment.
Advanced policies can use external data and complex logic to adapt governance dynamically.

Practice

(1/5)
1. What is the main purpose of a Sentinel policy in Terraform?
easy
A. To enforce rules that control changes to cloud infrastructure
B. To write Terraform configuration files
C. To deploy cloud resources automatically
D. To monitor cloud resource usage

Solution

  1. Step 1: Understand Sentinel policy role

    Sentinel policies are designed to enforce rules and guardrails on infrastructure changes.
  2. Step 2: Differentiate from other Terraform tasks

    Writing configs and deploying resources are Terraform tasks, not Sentinel's role.
  3. Final Answer:

    To enforce rules that control changes to cloud infrastructure -> Option A
  4. Quick Check:

    Sentinel policy = enforce rules [OK]
Hint: Sentinel = rules to control changes, not deployment [OK]
Common Mistakes:
  • Confusing Sentinel with Terraform configuration writing
  • Thinking Sentinel deploys resources
  • Assuming Sentinel monitors usage
2. Which of the following is the correct way to start a Sentinel policy block?
easy
A. sentinel policy example {
B. policy "example" {
C. policy example {
D. policy "example" = {

Solution

  1. Step 1: Recall Sentinel policy syntax

    Sentinel policies start with the keyword 'policy' followed by the policy name in quotes and curly braces.
  2. Step 2: Compare options

    policy "example" { matches the correct syntax: policy "example" { ... }
  3. Final Answer:

    policy "example" { -> Option B
  4. Quick Check:

    Correct Sentinel block start = policy "name" { [OK]
Hint: Policy name must be in quotes after 'policy' keyword [OK]
Common Mistakes:
  • Omitting quotes around policy name
  • Using '=' instead of '{' to start block
  • Adding extra keywords like 'sentinel'
3. Given this Sentinel policy snippet:
policy "check_tags" {
  main = rule {
    all tfplan.resource_changes as _, rc {
      rc.change.after.tags contains "environment"
    }
  }
}

What does this policy check?
medium
A. All resources must have a tag named "environment"
B. At least one resource must have a tag named "environment"
C. No resource should have a tag named "environment"
D. Resources can have any tags without restriction

Solution

  1. Step 1: Analyze the 'all' keyword usage

    The policy uses 'all' to check every resource change in the plan.
  2. Step 2: Understand the condition

    It requires each resource's tags to contain the key "environment".
  3. Final Answer:

    All resources must have a tag named "environment" -> Option A
  4. Quick Check:

    all resources have "environment" tag = All resources must have a tag named "environment" [OK]
Hint: 'all' means every resource must meet condition [OK]
Common Mistakes:
  • Confusing 'all' with 'any' keyword
  • Thinking it checks only one resource
  • Ignoring the 'contains' check on tags
4. Identify the error in this Sentinel policy snippet:
policy "check_region" {
  main = rule {
    all tfplan.resource_changes as _, rc {
      rc.change.after.region is "us-east-1"
    }
  }
}
medium
A. The 'main' rule must be a function, not a rule
B. Missing 'all' or 'any' keyword before the loop
C. Policy name must not be in quotes
D. Incorrect use of 'is' instead of '==' for comparison

Solution

  1. Step 1: Check comparison operator

    Sentinel uses '==' for equality, not 'is'. 'is' causes syntax error.
  2. Step 2: Verify other parts

    The loop uses 'all' correctly. Policy name requires quotes. 'main = rule { }' is standard syntax.
  3. Final Answer:

    Incorrect use of 'is' instead of '==' for comparison -> Option D
  4. Quick Check:

    Use '==' for equality in Sentinel [OK]
Hint: Use '==' for equality, not 'is' in Sentinel [OK]
Common Mistakes:
  • Using 'is' instead of '==' for comparisons
  • Thinking policy name cannot be quoted
  • Confusing rule and function syntax
5. You want to write a Sentinel policy that blocks any Terraform plan which tries to create an AWS EC2 instance without a tag named "owner". Which approach correctly enforces this?
hard
A. Use 'any' to check if any resource has 'owner' tag and allow plan if true
B. Check only the first resource's tags for 'owner' and ignore others
C. Use 'all' to check every resource of type 'aws_instance' has 'owner' tag in 'after' changes
D. Allow plan if no resources are of type 'aws_instance'

Solution

  1. Step 1: Identify the requirement

    Policy must block plans creating EC2 instances missing 'owner' tag.
  2. Step 2: Choose correct logic

    'all' ensures every EC2 instance resource has the 'owner' tag in the planned changes.
  3. Step 3: Evaluate other options

    'any' would allow plans if just one has the tag, which is unsafe. Checking only first resource misses others. Allowing plans with no EC2 instances is unrelated to the requirement.
  4. Final Answer:

    Use 'all' to check every resource of type 'aws_instance' has 'owner' tag in 'after' changes -> Option C
  5. Quick Check:

    All EC2 instances must have 'owner' tag = Use 'all' to check every resource of type 'aws_instance' has 'owner' tag in 'after' changes [OK]
Hint: 'all' enforces every EC2 instance has the tag [OK]
Common Mistakes:
  • Using 'any' instead of 'all' allowing missing tags
  • Checking only one resource instead of all
  • Ignoring resource type filtering