Policy enforcement for Stacks
This topic describes how policy enforcement works with Terraform Stacks. Policies let you validate that Terraform plans comply with security rules and best practices before infrastructure changes are applied.
For general information about policies, policy sets, and policy frameworks, refer to the Policy enforcement overview.
Overview
HCP Terraform enforces policies on Stacks configurations during each deployment operation. When you configure a policy set to target a Stack, HCP Terraform evaluates the policies against the Terraform plan for each deployment in the Stack. When a deployment has deferred changes, policies evaluate during each plan-and-apply cycle. Policies can access Stack and deployment metadata through the policy meta arguments.
Current limitations
Terraform policy support for Stacks currently has the following limitations:
- Policies cannot evaluate before the plan phase.
- Policies cannot evaluate after the apply phase completes.
- Users cannot override mandatory overridable policy failures.
- Policy evaluation is only supported for Stacks running Terraform 1.17alpha or later.
Policy evaluation workflow
HCP Terraform performs the following actions when you run a deployment in a Stack with policy sets configured:
- Generates a plan for each deployment in the Stack.
- Evaluates all applicable policy sets after each deployment's plan completes successfully.
- Halts the deployment if policies with mandatory or soft mandatory enforcement levels fail.
If a deployment has deferred changes, the steps repeat for each subsequent plan-and-apply cycle.
Configure policy sets for Stacks
To configure a policy set for Stacks, it must use Terraform policy as its policy evaluation engine.
- Create or edit a Terraform policy set. Refer to Create and manage policy sets for details.
- In the Scope section, select one of the following options:
- Policies enforced on all Stacks and workspaces: Applies to all Stacks and workspaces in the organization.
- Policies enforced on selected Stacks and workspaces: Applies to specific Stacks, projects, or workspaces.
- If you selected specific Stacks, choose the Stacks where you want to enforce the policy set.
Policy sets can target:
- All Stacks and workspaces in an organization
- All Stacks and workspaces in a specific project
- Individual workspaces or Stacks
Deferred changes and policy evaluation
When a deployment in a Stack has deferred changes, Terraform requires multiple plan-and-apply cycles to fully apply the configuration.
During the first plan-and-apply cycle, HCP Terraform evaluates policies after the initial plan. In subsequent cycles, HCP Terraform evaluates policies after each additional plan until no deferred changes remain.
Each policy evaluation is independent. A policy that passes in one cycle may fail in a subsequent cycle if the plan changes.