08-03 ended with an awkward question: between the two workflows, the IAM roles, the trust relationships, the plan artefact's encryption, the gate scripts, the issue deduplication and the SHA-pinned actions, building the machine costs several weeks of one person with good judgement, and maintaining it never ends. This lesson shows the alternative: buying it ready-made.
HCP Terraform — the product that for years was called Terraform Cloud — and its self-hosted sibling, Terraform Enterprise, are the platform HashiCorp built around Terraform. They are not another infrastructure-as-code tool: they are the pipeline, the state backend, the secret manager, the policy engine and the private registry, integrated and managed.
And this lesson settles two old debts. 06-01 dismissed CLI workspaces as an environment separator and wrote: "HCP Terraform workspaces have the same name and are something else; those do separate environments, and they are the subject of 08-04". And 07-04 introduced Sentinel in a two-paragraph overview, leaving the detail for here. Both are paid off.
Cost warning. HCP Terraform is billed per managed resource, and the bill grows with the infrastructure, not with usage. A state with 800 resources costs the same whether you touch it or not. Section 15 gives the real numbers and the honest table of when it pays off, which sometimes is that it does not.
- What HCP Terraform is and what Terraform Enterprise is
They are the same product with two delivery models.
| HCP Terraform | Terraform Enterprise | |
|---|---|---|
| Where it runs | HashiCorp's SaaS | Your infrastructure (Kubernetes, or a VM with Replicated) |
| Who operates it | HashiCorp | You: upgrades, backups, availability |
| Former name | Terraform Cloud | Terraform Enterprise (unchanged) |
| Features | The same, and first | The same, a version behind |
| Data | In HashiCorp's cloud | Inside your perimeter: it is its only reason to exist |
| Price | Per managed resource, with a free tier | An annual licence, negotiated, five figures and up |
| When | The normal case | A regulatory or network requirement that demands it |
The practical rule: start with HCP Terraform. Terraform Enterprise only makes sense if there is an explicit requirement — data that cannot leave the country, a network with no internet access, an audit demanding physical control — and even then, agent mode (§5) solves the private-network case without self-hosting anything.
A note about names, because the documentation and the forums mix all three: Terraform Cloud = HCP Terraform. It was renamed in 2024 when it was integrated into HashiCorp's HCP platform. The domain is still app.terraform.io, and the configuration block is called cloud.
- Which part of the machinery it replaces
This is the table that answers the question 08-03 closed with.
| Piece we built | Where it was | What HCP Terraform does | Does it fully replace it? |
|---|---|---|---|
| Remote state | An S3 bucket with encryption and versioning (03-03) | Managed, versioned state, with browsable history and diffs between versions | Yes, and better |
| State locking | DynamoDB (03-04) | Automatic locking per workspace, with a visible queue | Yes, and with no orphan locks |
| Running the plan and apply | A CI runner with an assumed role | Remote execution on the platform | Yes |
| Plan artefact | An encrypted .tfplan, 7-day retention (08-01 §6) |
The plan lives in the run; the apply uses that plan |
Yes, and the problem of a .tfplan full of secrets disappears |
| Approvals | Protected environments, input with submitter |
Manual confirmation of the run, with per-team permissions |
Yes |
| Variables and secrets | .tfvars + CI secrets |
Per-workspace variables and variable sets | Yes |
| Cloud credentials | OIDC with roles and trust relationships (08-03 §2) | Dynamic provider authentication, also via OIDC | Yes, with far less configuration |
| Policies over the plan | Conftest + Rego in the pipeline (07-04) | Sentinel, built into the run |
Yes, and OPA can be integrated too |
| Module registry | Tagged repositories (04-04) | The organisation's private registry | Yes |
| Auditing | CI logs + CloudTrail | A history of runs with who, when and what |
Yes |
| Cost estimation | We did not have it | Built in, and usable as a gate | New |
| The plan comment on the PR | github-script + a marker (08-03 §7) |
A status check on the PR linking to the run |
Partial: the plan is seen on the platform, not on the PR |
| Linters and scanners | tflint, Trivy, Checkov in the pipeline | It does not run them: you chain them with run tasks or keep the CI |
No |
terraform test |
A pipeline step | It does not run it in the run |
No |
| The modules' pipeline | A publish workflow triggered by a tag | The registry indexes tags; the tests are still yours | Partial |
The last three rows are the honest answer. HCP Terraform replaces the execution pipeline, not the verification one. You still need a CI that runs fmt, tflint, the scanners and terraform test on every PR. What disappears are the plan and apply workflows, the roles and their trust relationships, the encrypted artefact and half the scripts.
flowchart LR
subgraph BEFORE["Your own pipeline (08-01 to 08-03)"]
A1["CI: fmt, lint,<br/>scanner, test"] --> A2["CI: plan -out"]
A2 --> A3["CI: policies<br/>Conftest"]
A3 --> A4["CI: comment on PR"]
A4 --> A5["CI: encrypted<br/>artefact"]
A5 --> A6["CI: approval"]
A6 --> A7["CI: apply"]
A8["S3 + DynamoDB"]
A9["OIDC + 6 roles"]
end
subgraph AFTER["With HCP Terraform"]
B1["CI: fmt, lint,<br/>scanner, test"] --> B2["HCP: run"]
B2 --> B3["HCP: plan"]
B3 --> B4["HCP: Sentinel"]
B4 --> B5["HCP: cost"]
B5 --> B6["HCP: confirm"]
B6 --> B7["HCP: apply"]
B8["HCP: state<br/>and locking"]
B9["HCP: dynamic<br/>credentials"]
end
style A1 fill:#dbeafe,stroke:#1d4ed8
style B1 fill:#dbeafe,stroke:#1d4ed8
style AFTER fill:#f0fdf4,stroke:#15803d
The blue blocks are the same on both sides: that is what you do not buy.
- HCP workspaces: the debt from 06-01
06-01 left the comparison table and the conclusion: "an HCP Terraform workspace does solve the six problems in section 5, because it is not one more state but a unit with its own configuration, its own variables, its own credentials and its own permissions". It is time to spell out what one really is.
An HCP Terraform workspace is the full equivalent of a Terraform root directory running on your machine. It contains everything it needs to operate autonomously:
| Workspace component | Equivalent on your laptop |
|---|---|
| Configuration (repository + directory + branch) | The directory where you run terraform |
| Terraform variables | Your -var-file and your -var |
| Environment variables | Your AWS_PROFILE, your TF_LOG |
| Provider credentials | Your AWS profile |
| The state and its history | Your remote terraform.tfstate |
| Terraform version | Your binary |
| Run history | Your shell history, if you had one |
| Per-team permissions | No equivalent exists |
| Locking | Your backend's |
The definitive table, extending the one in 06-01
| Aspect | CLI workspace | HCP workspace |
|---|---|---|
| What it is | An additional state for the same directory | A complete unit of work |
| How many states | One per workspace, same backend | One, its own |
| Configuration | Shared: the same code for all of them | Its own: its repository, its directory, its branch |
| Variables | Shared; only terraform.workspace changes |
Its own, with reusable sets |
| Credentials | The same for all of them | Its own, per workspace |
| Terraform version | Whatever your binary is | Its own, per workspace |
| Permissions | They do not exist | Per team: read, plan, apply, administer |
| History | There is none | Every run with who, when, what plan and what output |
| Approval | There is none | Configurable: automatic or manual |
| Notifications | There are none | Webhook, Slack, email per event |
| Selected with | terraform workspace select |
You connect to it with the cloud {} block |
| Identified in code with | terraform.workspace |
terraform.workspace as well, but it is the HCP workspace's name |
| What it is for | Replicas of the same code (ephemeral PR environments) | Genuinely separating environments and components |
The difference that sums up all the others: a CLI workspace is a state; an HCP workspace is a deployment. That is why CLI ones did not separate environments — they share configuration, variables and credentials — and HCP ones do.
How they connect
With the cloud {} block, CLI workspaces are projected onto HCP ones. There are two modes:
# Mode 1: a single remote workspace. The simplest and the most common.
terraform {
cloud {
organization = "ecomarket"
workspaces {
name = "ecomarket-app-prod"
}
}
}
# With this there are no CLI workspaces: you always operate on that one.# Mode 2: several remote workspaces selected from the CLI.
terraform {
cloud {
organization = "ecomarket"
workspaces {
# tags selects ALL the workspaces carrying this tag.
tags = ["app", "eu-west-1"]
}
}
}
# Now "terraform workspace select prod" chooses among the HCP workspaces
# tagged like that. The CLI workspace becomes a SELECTOR of a remote
# workspace, not an additional state.Mode 2 is the reconciliation of the two concepts: the CLI workspace stops creating states and starts choosing which of the remote ones you use. It is the only situation where terraform workspace select is good practice for environments.
- EcoMarket's organisation in workspaces
With three environments and three components, EcoMarket has nine workspaces:
Organisation: ecomarket │ ├── ecomarket-network-dev ← infra/network · environments/dev.tfvars ├── ecomarket-network-staging ├── ecomarket-network-prod ├── ecomarket-data-dev ← infra/data ├── ecomarket-data-staging ├── ecomarket-data-prod ├── ecomarket-app-dev ← infra/app ├── ecomarket-app-staging └── ecomarket-app-prod
The name follows exactly the same partitioning as the S3 backend keys (ecomarket/<environment>/<component>/terraform.tfstate), because the state partitioning does not change when you migrate: it is the expensive decision from 07-01, and changing platform is no reason to revisit it.
The VCS connection and the triggers
Each workspace is connected to the ecomarket/ecomarket-infra repository:
| Setting | Value in ecomarket-app-prod |
What it does |
|---|---|---|
| Repository | ecomarket/ecomarket-infra |
The same for all nine |
| Branch | main |
What gets applied comes from the main branch |
working_directory |
infra/app |
Terraform runs there |
| Path trigger | infra/app/**, modules/**, environments/** |
It only triggers if its own things change |
| PR plans | Enabled | A status check on the PR |
auto_apply |
false in prod, true in dev |
The promotion from 08-01 §10 |
flowchart TD
PR["PR against ecomarket-infra<br/>touches infra/app/**"] --> H["HCP Terraform<br/>detects the change"]
H --> W1["Workspace app-dev<br/>trigger matches"]
H --> W2["Workspace app-staging<br/>trigger matches"]
H --> W3["Workspace app-prod<br/>trigger matches"]
H -. "no match" .-> W4["Workspaces network-* and data-*<br/>do NOT trigger"]
W1 --> R1["run: plan<br/>+ Sentinel + cost"]
W2 --> R2["run: plan"]
W3 --> R3["run: plan"]
R1 --> PRC["Status check<br/>on the PR, with a link"]
R2 --> PRC
R3 --> PRC
style W4 fill:#f3f4f6,stroke:#9ca3af
style R3 fill:#fef3c7,stroke:#b45309
Path triggers versus tag triggers
| Mode | How it works | When to use it |
|---|---|---|
By path (trigger_patterns) |
The run is created if the push touches those paths |
One repository with several components: EcoMarket's case |
By tag (trigger_prefixes + Git tags) |
The run is created when a tag matching a pattern is pushed |
Promotion by version (07-02): prod only moves when you tag |
| Manual / API | Nobody triggers it on its own | Workspaces that run on demand |
EcoMarket uses paths in dev and staging, and tags in prod. It is the literal implementation of the rule from 07-02: you promote by tag, not by copying. The production workspace triggers only when somebody pushes a release-* tag, and what it plans is the code at that exact tag.
- Execution modes: remote, local and agent
| Mode | Where Terraform runs | State | When it is used |
|---|---|---|---|
| Remote | On HCP's infrastructure | Managed | The normal case |
| Local | On your machine or your CI | Managed by HCP | When you need your own pipeline but want HCP's state and locking |
| Agent | On an agent you deploy inside your network | Managed | Private networks: the resource to manage is not reachable from the internet |
Agent mode in detail
It is the answer to the most common objection: "I cannot use a SaaS because my database is in a VPC with no egress".
flowchart LR
HCP["HCP Terraform<br/>(SaaS)"] -. "the agent INITIATES<br/>the outbound connection" .-> A
subgraph VPC["Your private VPC"]
A["HCP agent<br/>container"] --> DB[("private RDS")]
A --> K8S["private Kubernetes<br/>API"]
A --> VC["internal vSphere"]
end
style VPC fill:#eff6ff,stroke:#1d4ed8
The key property: the agent opens an outbound connection to HCP and waits for work. No inbound port has to be opened, nothing has to be exposed, and the database does not have to go on the internet. It is the same pattern as a self-hosted CI runner.
# Deploying an agent is a container and a token.
docker run -d --name tfc-agent \
-e TFC_AGENT_TOKEN="$(cat /run/secrets/tfc_agent_token)" \
-e TFC_AGENT_NAME="ecomarket-agent-eu-west-1-01" \
-e TFC_AGENT_AUTO_UPDATE=minor \
hashicorp/tfc-agent:latestSecurity warning. The agent runs Terraform code inside your private network, with whatever credentials you give it. It is the same threat model as a self-hosted runner (08-03 §10): a restricted network, no permissions it does not need, and never shared between teams with different trust levels. The agent token is a long-lived credential: manage it as such.
- The
cloud {} block and migrating from the S3 backend
cloud {} block and migrating from the S3 backendThe block
# infra/app/versions.tf
terraform {
required_version = "~> 1.9"
# The cloud block REPLACES the backend block. They cannot coexist.
cloud {
organization = "ecomarket"
workspaces {
# With tags, the same code serves all three environments and
# you select with terraform workspace select (§3, mode 2).
tags = ["app", "ecomarket"]
}
}
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
}
}One important difference from the backend: the cloud block does accept environment variables for some things (TF_CLOUD_ORGANIZATION, TF_WORKSPACE), unlike the backend block, which accepts no interpolation of any kind (03-03). That lets the same code serve several organisations without -backend-config.
CLI authentication
# Interactive: it opens the browser and stores the token in ~/.terraform.d/credentials.tfrc.json
terraform login
# In a pipeline: an environment variable. The host name goes in the
# variable name, with the dots turned into underscores.
export TF_TOKEN_app_terraform_io="$(cat /run/secrets/tfc_token)"
# For self-hosted Terraform Enterprise at tfe.ecomarket.example.com:
export TF_TOKEN_tfe_ecomarket_example_com="..."Migrating from S3, step by step
It is the most delicate operation in the lesson, because it moves the state. The procedure follows the same rigour 07-05 applied to the Terragrunt migration: a backup, verification and a zero plan.
# --- STEP 1: the backup. Before touching anything. ---
terraform -chdir=infra/app init -reconfigure \
-backend-config=backends/staging.hcl
terraform -chdir=infra/app state pull > backup-app-staging-$(date +%F).tfstate
jq '.resources | length' backup-app-staging-*.tfstate # 23, noted down
jq -r '.lineage, .serial' backup-app-staging-*.tfstate # noted down too
# --- STEP 2: create the workspace in HCP, EMPTY and not connected to VCS. ---
# The VCS is connected AFTER migrating: if it is connected first, a push
# can trigger a run on a workspace with no state, and the plan would
# propose creating the 23 resources that already exist.
# --- STEP 3: replace the backend block with the cloud block. ---
# (edit infra/app/versions.tf)
# --- STEP 4: the init that migrates. Terraform notices and asks. ---
terraform -chdir=infra/app init
# Initializing HCP Terraform...
# Do you wish to proceed? [yes/no]
# ↑ answer "yes". It copies the state from S3 to the HCP workspace.
# This init does NOT carry -input=false: it is a manual, supervised
# operation, done once per workspace.
# --- STEP 5: THE CHECK. A zero plan, or you stop. ---
terraform -chdir=infra/app plan -detailed-exitcode
echo "code: $?"
# 0 → no changes. CORRECT, the migration is good.
# 2 → there are changes. STOP and diagnose with the table below.| Plan symptom after migrating | Cause | Solution |
|---|---|---|
| It proposes creating the 23 resources | The state was not copied: the workspace is empty | Check with terraform state list | wc -l. If it says 0, repeat step 4 |
| It modifies tags on everything | The workspace variables do not reproduce the .tfvars |
Compare variable by variable against environments/staging.tfvars |
| It replaces some resource | A variable with a different value | jq '.variables' over the plan and compare |
| A credentials error | The workspace has no credentials configured | §7: environment variables or dynamic authentication |
| A different Terraform version | The workspace uses another version | Set it to the one in .terraform-version before planning |
# --- STEP 6: only with a ZERO plan, connect the VCS and retire the old. ---
# 1. Connect the workspace to the repository and the working_directory.
# 2. Delete backends/staging.hcl from the repository (no longer used).
# 3. The S3 bucket and its versioning are KEPT for a few months: they are
# the migration's backup. They go when nobody misses them.Step 6.3 deserves emphasis. Deleting the state bucket on the same day as the migration removes the only safety net. It is kept, with versioning on, and retired months later, in a conscious change of its own.
- Variables and variable sets
HCP Terraform has two categories of variable, and confusing them is the cause of 90% of "it cannot find the credentials".
| Terraform variable | Environment variable | |
|---|---|---|
| What it is | A value for a variable in the code |
An environment variable of the process |
| Equivalent to | -var or .tfvars |
export AWS_REGION=... |
| Example | environment = "prod", instance_size = "t3.large" |
AWS_ACCESS_KEY_ID, TF_LOG, ARM_USE_OIDC |
| Can be marked sensitive | Yes | Yes |
| Accepts HCL | Yes (maps, lists) | No: always a string |
How they replace the .tfvars
EcoMarket's environments/prod.tfvars becomes variables of the ecomarket-app-prod workspace:
| Variable | Category | Value | Sensitive | HCL |
|---|---|---|---|---|
environment |
Terraform | prod |
No | No |
environments |
Terraform | { prod = { size = "t3.large", replicas = 4 } } |
No | Yes |
db_password |
Terraform | •••••••• |
Yes | No |
AWS_REGION |
Environment | eu-west-1 |
No | — |
TF_IN_AUTOMATION |
Environment | 1 |
No | — |
The "sensitive" flag in HCP is stronger than sensitive in the code. A sensitive value in HCP cannot be read back, neither through the interface nor through the API: it can only be overwritten. That solves a real problem with the .tfvars model: the production password stops being in any file, any artefact and any log.
And it also solves the most serious warning in 08-01 §6: there is no .tfplan to store, because the plan lives inside the run and is only seen by those with permission over the workspace.
Variable sets
A variable set is a group of variables applicable to several workspaces at once.
Set: "aws-production" ├── AWS_REGION = eu-west-1 (environment) └── (dynamic credentials, §7) Applied to: the 3 *-prod workspaces Set: "common-tags" ├── project = "ecomarket" (Terraform) ├── owner = "[email protected]" └── repo = "ecomarket-infra" Applied to: ALL the organisation's workspaces Set: "sentinel-legacy-exceptions" └── allow_legacy_instances = true (Terraform) Applied to: only ecomarket-data-prod, with an expiry date noted
The common-tags set is the HCP version of common.auto.tfvars (07-01), and it feeds the local.common_tags we have been carrying since module 2.
Dynamic provider authentication
The functional gem of this section: HCP Terraform can be the OIDC issuer, exactly like GitHub in 08-03.
Workspace: ecomarket-app-prod
Environment variables:
TFC_AWS_PROVIDER_AUTH = true
TFC_AWS_RUN_ROLE_ARN = arn:aws:iam::123456789014:role/ecomarket-terraform-prodWith those two variables, the platform obtains temporary AWS credentials when the run starts. There is no AWS_ACCESS_KEY_ID anywhere.
# And the trust relationship in AWS, analogous to the one in 08-03 §2:
resource "aws_iam_role" "terraform_prod" {
name = "ecomarket-terraform-prod"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = "sts:AssumeRoleWithWebIdentity"
Principal = { Federated = aws_iam_openid_connect_provider.hcp.arn }
Condition = {
StringEquals = {
"app.terraform.io:aud" = "aws.workload.identity"
# The "sub" identifies ORGANISATION, PROJECT, WORKSPACE and PHASE.
# The phase (plan/apply) allows what 08-01 §4 asked for: different
# roles for plan and for apply, here with one role per phase or
# with two different roles if you prefer.
"app.terraform.io:sub" = "organization:ecomarket:project:platform:workspace:ecomarket-app-prod:run_phase:apply"
}
}
}]
})
}And the run_phase allows the exact separation from 08-01 §4:
TFC_AWS_PLAN_ROLE_ARN = arn:...:role/ecomarket-terraform-plan-prod # read-only TFC_AWS_APPLY_ROLE_ARN = arn:...:role/ecomarket-terraform-prod # write
Two variables replace the two workflows, the two hand-configured roles and the two trust relationships with their dangerous wildcards. That, concretely, is the value you are buying.
- The execution flow: what a
run is
run isA run is a complete execution over a workspace: the equivalent of the plan+apply pair from 08-01, but as a first-class object with its own identifier, history and status.
flowchart TD
D1["Push / PR in the VCS"] --> R
D2["An API call"] --> R
D3["terraform apply from the CLI"] --> R
D4["Manually from the interface"] --> R
R["run created"] --> P["PLAN<br/>remote terraform plan"]
P -->|"error"| X["run: errored"]
P --> S["POLICIES<br/>Sentinel + OPA"]
S -->|"hard-mandatory fails"| X2["run: policy_soft_failed<br/>BLOCKED"]
S --> C["COST<br/>estimate of the delta"]
C --> G{{"auto_apply?"}}
G -->|"yes (dev)"| A
G -->|"no (staging/prod)"| CONF{{"Manual confirmation<br/>by somebody with permission"}}
CONF -->|"discarded"| X3["run: discarded"]
CONF --> A["APPLY<br/>terraform apply of the plan"]
A --> F["run: applied<br/>state and outputs updated"]
style P fill:#dbeafe,stroke:#1d4ed8
style S fill:#fef3c7,stroke:#b45309
style A fill:#fee2e2,stroke:#b91c1c
The states of a run
| State | Means |
|---|---|
pending |
Queued: another run holds the workspace |
planning / planned |
Plan in progress / finished with changes |
planned_and_finished |
Plan with no changes: the run ends there |
cost_estimating |
Computing the estimate |
policy_checking |
Evaluating Sentinel |
policy_override |
A soft-mandatory policy failed: somebody with permission can override it |
policy_soft_failed |
Blocked: hard-mandatory |
confirmed / applying / applied |
Approved / applying / applied |
discarded |
Discarded without applying |
errored |
It failed |
planned_and_finished is the equivalent of -detailed-exitcode's code 0, and it is what you will see in the scheduled drift runs.
The four triggers
| Trigger | How | When |
|---|---|---|
| VCS | A push or PR touching the configured paths | The normal case |
| API | POST /runs |
External orchestration, promotion between workspaces |
| CLI | terraform apply with the cloud block |
Local development against dev |
| Interface | The "New run" button | Reapplying, manual drift checks |
The CLI trigger deserves a note, because it is surprising: with the cloud block, terraform apply from your laptop runs nothing on your laptop. It packages the directory, uploads it, creates a remote run and shows you the output in real time. The credentials used are the workspace's, not yours. It is one of the product's most useful properties: the same command does the right thing without you having production credentials.
Queue and locking
Locking stops being an operational problem. Each workspace has at most one active run; the others wait in a visible queue. There are no orphan locks from cancellation (08-01 §11): if a run is cancelled, the platform releases the workspace.
That wipes out force-unlock, the orphan-lock guard and the CI's concurrency groups in one stroke.
- Sentinel: what it is and where it runs
Here the second debt starts being paid. 07-04 said just enough about Sentinel to place it and pointed here.
Sentinel is HashiCorp's policy-as-code language and engine. It plugs into the run as a phase between the plan and the apply, and decides whether the run may continue.
flowchart LR
P["Plan finished"] --> S["Sentinel evaluates<br/>the set's policies"]
S -->|"everything passes"| OK["Continues to cost<br/>and approval"]
S -->|"advisory fails"| OK2["Continues<br/>with a WARNING"]
S -->|"soft-mandatory fails"| OV{{"Anybody with<br/>override permission?"}}
OV -->|"overrides"| OK3["Continues,<br/>with a record of who overrode"]
OV -->|"no"| X["run blocked"]
S -->|"hard-mandatory fails"| XX["run BLOCKED<br/>nobody can override it"]
style XX fill:#fee2e2,stroke:#b91c1c
style OK fill:#dcfce7,stroke:#15803d
The property that makes it a control and not a good intention — the sentence that structured 07-04 — is where it lives: Sentinel policies are attached to the organisation, not to the infrastructure repository. Whoever opens a PR in ecomarket-infra cannot touch them, disable them or skip them. Only somebody with policy administration permission in the organisation can.
| Sentinel | precondition / check |
terraform test |
|
|---|---|---|---|
| Where it lives | The HCP organisation | The repository's code | The repository |
| Who can disable it | An organisation administrator | Whoever makes the change | Whoever makes the change |
| Is it a control? | Yes | No | No |
sentinel.hcl, enforcement levels and imports
sentinel.hcl, enforcement levels and importsPolicies are grouped into a policy set, which is a directory in a repository with a configuration file:
# ci/sentinel/sentinel.hcl
# EcoMarket's policy set, connected to the organisation from a repository
# SEPARATE from the infrastructure one: whoever changes the
# infrastructure cannot change the policies.
# --- The imports the policies are going to use ---
import "tfplan/v2" {
# Version 2 of the plan import. Structured by resource address, with
# before/after and actions, very similar to the JSON from
# "terraform show -json" you already know from 07-04.
alias = "tfplan"
}
import "tfconfig/v2" { alias = "tfconfig" } # the CONFIGURATION, not the plan
import "tfstate/v2" { alias = "tfstate" } # the state BEFORE the apply
import "tfrun" { } # metadata: cost, workspace, who
# --- Our own helper modules ---
module "common" {
source = "./modules/common.sentinel"
}
# --- The policies and their ENFORCEMENT LEVEL ---
policy "mandatory-tags" {
source = "./policies/mandatory-tags.sentinel"
enforcement_level = "hard-mandatory"
}
policy "allowed-instances" {
source = "./policies/allowed-instances.sentinel"
enforcement_level = "soft-mandatory"
}
policy "maximum-cost" {
source = "./policies/maximum-cost.sentinel"
enforcement_level = "soft-mandatory"
}
policy "no-public-access" {
source = "./policies/no-public-access.sentinel"
enforcement_level = "hard-mandatory"
}
policy "naming" {
source = "./policies/naming.sentinel"
enforcement_level = "advisory"
}The three enforcement levels
| Level | If it fails | Who can continue | When to use it |
|---|---|---|---|
advisory |
A warning on the run; it continues |
Nobody has to do anything | Conventions, a new policy being bedded in |
soft-mandatory |
Blocks, but can be overridden | Anybody with override permission, and it is recorded | Rules with legitimate exceptions: instance types, cost |
hard-mandatory |
Blocks. Nobody can override it | Only by changing the policy | Security and compliance: encryption, public access, tags |
The level decision is the organisation's policy decision, and it deserves more discussion than the policy's code. The practical guidance:
hard-mandatoryfor anything whose breach is a security or compliance incident. If there is a legitimate case that breaches it, the exception goes written into the policy itself, not into the level.soft-mandatoryfor what is usually wrong but is sometimes right. Its value is in the friction and in the record: overriding leaves a trace of who and when.advisoryfor launching a new policy. You deploy it asadvisory, measure how manyrunswould breach it, fix the existing infrastructure, and then raise the level. Deploying a new policy straight tohard-mandatoryblocks every deployment on Monday morning.
The imports
| Import | What it contains | Example use |
|---|---|---|
tfplan/v2 |
The plan: resource_changes, variables, output_changes |
90% of policies |
tfconfig/v2 |
The configuration: resources, modules, providers, declared variables | "Ban provider X", "require every module to come from the private registry" |
tfstate/v2 |
The state before the apply | "Do not allow going below 3 replicas if there are 5 now" |
tfrun |
The run's metadata: estimated cost, workspace, who launched it |
Cost and schedule policies |
The difference between tfplan and tfconfig is the hardest one: tfplan sees resolved values and tfconfig sees expressions. "This instance_type is t3.large" is tfplan. "This instance_type is written as a reference to a variable and not as a literal" is tfconfig.
- Real EcoMarket policies, annotated
Policy 1: allowed instance types
# ci/sentinel/policies/allowed-instances.sentinel
# Level: soft-mandatory. There are legitimate cases (a one-off migration
# that needs a big instance), and overriding leaves a trace.
import "tfplan/v2" as tfplan
import "strings"
# --- The policy's configuration ---
# The allowed list. It comes from a cost and standardisation decision,
# not from a technical preference.
allowed_types = [
"t3.micro", "t3.small", "t3.medium", "t3.large",
"m6i.large", "m6i.xlarge",
"r6i.large", # only for the data tier
]
# Types that require justification because of their cost.
expensive_types = ["m6i.xlarge", "r6i.large"]
# --- Extraction: the instances being created or modified ---
# What is destroyed cannot violate anything, and what does not change
# already passed through here. Same criterion as the Rego in 07-04.
instances = filter tfplan.resource_changes as _, rc {
rc.type is "aws_instance" and
rc.mode is "managed" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
# --- The rule ---
# Sentinel walks the collection and accumulates the breaches into a list
# of violations, so that the message lists them ALL at once instead of
# stopping at the first. Whoever fixes the PR is grateful.
violations = []
for instances as address, rc {
type = rc.change.after.instance_type
if type not in allowed_types {
append(violations, address + ": type '" + type + "' not allowed")
print("BLOCKED:", address, "uses type", type)
print(" Allowed types:", strings.join(allowed_types, ", "))
print(" If you need another type, open a proposal in the policy")
print(" repository or write to [email protected].")
}
# Expensive types require the Justification tag. It is a cheap way of
# forcing somebody to write WHY, without blocking the legitimate case.
if type in expensive_types {
tags = rc.change.after.tags else {}
if "Justification" not in keys(tags) {
append(violations, address + ": expensive type with no justification")
print("BLOCKED:", address, "uses", type, "with no Justification tag.")
print(" Add tags = { Justification = \"...\" } explaining the sizing.")
}
}
}
# --- The main rule: the value Sentinel evaluates ---
# It must be called "main" and be a boolean. If it is false, the policy fails.
main = rule { length(violations) is 0 }Policy 2: mandatory tags
# ci/sentinel/policies/mandatory-tags.sentinel
# Level: hard-mandatory. Without Owner there is no way of knowing who to
# alert in an incident, and without Project the bill cannot be allocated.
# There is no legitimate exception, so no override is possible.
import "tfplan/v2" as tfplan
import "strings"
mandatory_tags = [
"Project", "Environment", "ManagedBy", "Owner", "Repo",
]
# Types that do NOT accept tags: demanding them would be a false block.
# It is the same list as the Rego in 07-04, and it has to be maintained.
types_without_tags = [
"aws_iam_role_policy_attachment",
"aws_security_group_rule",
"aws_route",
"aws_s3_bucket_versioning",
"aws_s3_bucket_public_access_block",
"aws_db_subnet_group",
"random_pet",
"terraform_data",
]
aws_resources = filter tfplan.resource_changes as _, rc {
rc.mode is "managed" and
strings.has_prefix(rc.type, "aws_") and
rc.type not in types_without_tags and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
violations = []
for aws_resources as address, rc {
# tags_all and NOT tags: tags_all includes the provider's default_tags
# (05-02). Using tags would produce a false block on almost every
# resource. It is the same nuance as in 07-04.
tags = rc.change.after.tags_all else {}
missing = []
for mandatory_tags as required {
if required not in keys(tags) {
append(missing, required)
}
}
if length(missing) > 0 {
append(violations, address)
print("BLOCKED:", address, "does not carry:", strings.join(missing, ", "))
print(" The common tags are applied with the provider's default_tags.")
print(" See local.common_tags in the repository.")
}
# Environment consistency: it catches the classic "I applied prod with
# dev.tfvars". Here it is an extra sanity check: with HCP workspaces the
# mistake is far less likely, but it is still possible if somebody moves
# variables between workspaces.
tag_environment = tags.Environment else ""
variable_environment = tfplan.variables.environment.value else ""
if tag_environment is not "" and variable_environment is not "" and
tag_environment is not variable_environment {
append(violations, address)
print("BLOCKED:", address, "would be tagged Environment=" + tag_environment)
print(" but the workspace's 'environment' variable is:", variable_environment)
print(" Check the workspace's variables.")
}
}
main = rule { length(violations) is 0 }Policy 3: maximum cost of the change
# ci/sentinel/policies/maximum-cost.sentinel
# Level: soft-mandatory. It uses the tfrun import, which carries the cost
# estimate the platform computes in the run itself (§14).
import "tfrun"
import "decimal"
# Thresholds for the monthly INCREASE, per environment. Not for total
# cost: what is controlled is the DELTA this change introduces.
thresholds = {
"dev": 50,
"staging": 200,
"prod": 1000,
}
# The workspace name ends in the environment: ecomarket-app-prod.
# Extracting it this way is fragile if somebody renames a workspace; the
# robust alternative is a workspace variable.
parts = strings.split(tfrun.workspace.name, "-")
environment = parts[length(parts) - 1]
threshold = thresholds[environment] else 50
# The estimate may not exist: unsupported providers, or the feature
# switched off. A policy that assumes it exists FAILS on Azure runs,
# and that failure looks like a cost problem.
cost_available = tfrun.cost_estimate.proposed_monthly_cost is not null
increase = 0
if cost_available {
increase = decimal.new(tfrun.cost_estimate.delta_monthly_cost).float
}
if cost_available and increase > threshold {
print("BLOCKED on cost.")
print(" Estimated monthly increase:", increase, "USD")
print(" Threshold for", environment + ":", threshold, "USD")
print(" Proposed monthly cost:", tfrun.cost_estimate.proposed_monthly_cost)
print("")
print(" The estimate does not include traffic, variable storage")
print(" or commitment discounts: it is an order of magnitude.")
print(" If the increase is intentional, ask the platform team for")
print(" an override, quoting the ticket.")
}
if not cost_available {
print("WARNING: there is no cost estimate for this run.")
print(" The policy cannot be evaluated and is allowed to pass.")
}
main = rule {
not cost_available or increase <= threshold
}Policy 4: no public access (the strictest)
# ci/sentinel/policies/no-public-access.sentinel
# Level: hard-mandatory. This is what prevents the front-page incident:
# a bucket or a database reachable from the internet.
import "tfplan/v2" as tfplan
internet_ranges = ["0.0.0.0/0", "::/0"]
allowed_public_ports = [80, 443]
exposed_roles = ["load-balancer", "cdn"]
violations = []
# --- Rule 1: databases are never public ---
databases = filter tfplan.resource_changes as _, rc {
rc.type in ["aws_db_instance", "aws_rds_cluster"] and
rc.mode is "managed" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
for databases as address, rc {
if rc.change.after.publicly_accessible else false {
append(violations, address)
print("BLOCKED:", address, "has publicly_accessible = true.")
print(" An EcoMarket database is NEVER reachable from the internet.")
print(" For external access: a bastion or a VPN. This policy is not overridden.")
}
# Encryption at rest: a compliance breach, and also immutable
# (changing it REPLACES the database, with its data).
if not (rc.change.after.storage_encrypted else false) {
append(violations, address)
print("BLOCKED:", address, "with no storage_encrypted.")
}
}
# --- Rule 2: buckets with no public access ---
bucket_acls = filter tfplan.resource_changes as _, rc {
rc.type is "aws_s3_bucket_public_access_block" and
rc.mode is "managed" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
for bucket_acls as address, rc {
after = rc.change.after
all_enabled = (after.block_public_acls else false) and
(after.block_public_policy else false) and
(after.ignore_public_acls else false) and
(after.restrict_public_buckets else false)
if not all_enabled {
append(violations, address)
print("BLOCKED:", address, "does not block all public access.")
print(" All four settings must be true.")
}
}
# --- Rule 3: security groups ---
# Only 80 and 443, and only on resources marked as exposed.
# It is the rule a generic scanner cannot express (07-04 §11).
groups = filter tfplan.resource_changes as _, rc {
rc.type is "aws_vpc_security_group_ingress_rule" and
rc.mode is "managed" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
for groups as address, rc {
after = rc.change.after
cidr = after.cidr_ipv4 else ""
if cidr in internet_ranges {
from = after.from_port else 0
to = after.to_port else 0
tags = after.tags else {}
role = tags.Role else "no-role"
if from is not to or from not in allowed_public_ports {
append(violations, address)
print("BLOCKED:", address, "opens", from, "-", to, "to", cidr)
print(" Allowed public ports:", allowed_public_ports)
} else if role not in exposed_roles {
append(violations, address)
print("BLOCKED:", address, "opens port", from, "to the internet")
print(" but its Role tag is '" + role + "'.")
print(" Only", exposed_roles, "may be exposed. Instances")
print(" receive traffic FROM THE LOAD BALANCER, by group reference.")
}
}
}
main = rule { length(violations) is 0 }
- Testing policies with
sentinel test
sentinel testA policy with no tests is a policy that blocks legitimate deployments the day you roll it out. Sentinel ships with a test framework that runs the policy against mock data.
ci/sentinel/
├── sentinel.hcl
├── policies/
│ ├── allowed-instances.sentinel
│ └── mandatory-tags.sentinel
└── test/
└── allowed-instances/
├── allowed.hcl ← must PASS
├── not-allowed.hcl ← must FAIL
├── expensive-unjustified.hcl ← must FAIL
├── expensive-justified.hcl ← must PASS
└── mock-tfplan-*.sentinel ← the mock data# test/allowed-instances/not-allowed.hcl
# A case that MUST fail. Without this kind of test, a policy can be
# returning true all the time and nobody notices.
mock "tfplan/v2" {
module {
source = "./mock-tfplan-not-allowed.sentinel"
}
}
test {
rules = {
main = false # the policy MUST block this plan
}
}# test/allowed-instances/mock-tfplan-not-allowed.sentinel
# The mock data: the minimum plan structure the policy reads.
# It can be generated from the real plan with "sentinel apply -trace" over
# a platform run, or written by hand as here.
resource_changes = {
"aws_instance.web": {
"address": "aws_instance.web",
"mode": "managed",
"type": "aws_instance",
"change": {
"actions": ["create"],
"after": {
"instance_type": "c5.24xlarge", # NOT in the list
"tags": {"Project": "ecomarket"},
},
},
},
}
variables = {
"environment": {"value": "prod"},
}# Run all the set's tests.
sentinel test
# PASS - policies/allowed-instances.sentinel
# PASS - test/allowed-instances/allowed.hcl
# PASS - test/allowed-instances/not-allowed.hcl
# PASS - test/allowed-instances/expensive-unjustified.hcl
# PASS - test/allowed-instances/expensive-justified.hcl
# A single policy, with a trace to debug why it decides what it decides.
sentinel test -run=allowed -verboseAnd these tests go in the policy repository's CI. It is the same reasoning as 07-03: a policy is code, it is deployed to production and it can break things. It deserves a PR, a review and tests.
- Sentinel versus OPA/Conftest
You already know both. The honest comparison:
| Dimension | Sentinel | OPA / Rego + Conftest |
|---|---|---|
| Who makes it | HashiCorp, proprietary | CNCF, open source |
| Where it runs | Inside the HCP run |
Wherever you want: CI, laptop, Kubernetes |
| Requires HCP | Yes (paid plans for policies) | No |
| Cost | Included in the higher plans | Free |
| Language | Imperative with rules: loops, if, variables |
Declarative, query-oriented over JSON |
| Learning curve | Gentler for somebody coming from programming | Steeper; the mental model is different |
| Input | Structured imports: tfplan/v2, tfconfig/v2, tfstate/v2, tfrun |
The JSON from terraform show -json |
| Access to the configuration | Yes, with tfconfig/v2 |
Not directly: the plan does not carry the expressions |
| Access to the cost estimate | Yes, with tfrun |
No: you have to compute it outside (Infracost) |
| Enforcement levels | Three, built in, with recorded overrides | You implement them: deny / warn and the exit code |
| Testing | sentinel test |
conftest verify with _test.rego files |
| External reuse | HashiCorp's policy library | Enormous: OPA is used in Kubernetes, APIs, CI |
| Who can disable them | An organisation administrator | Whoever can change the pipeline |
| Outside Terraform | Useless for anything else | Kubernetes (Gatekeeper), Envoy, APIs, CI |
The difference that really decides it
It is the second-to-last row, and it is the same one 07-04 used to define what a control is:
- Conftest lives in your pipeline. Whoever can modify the pipeline can skip it. With security
CODEOWNERSoverci/and branch protection, it is a reasonable control. But the key is in the same repository, just in another drawer. - Sentinel lives in the HCP organisation. Whoever changes the infrastructure has no access to that console. The key is in another building.
And a second practical difference that is underestimated: Sentinel sees the configuration, not just the plan. There are policies you can only write with tfconfig/v2:
# This CANNOT be expressed over the plan's JSON: the plan carries
# resolved values, not the module's provenance.
import "tfconfig/v2" as tfconfig
# Require every module to come from the private registry.
# A supply-chain defence (07-04 §15) that Conftest cannot provide.
external_modules = filter tfconfig.module_calls as _, mc {
not strings.has_prefix(mc.source, "app.terraform.io/ecomarket/")
and not strings.has_prefix(mc.source, "./")
and not strings.has_prefix(mc.source, "../")
}
main = rule { length(external_modules) is 0 }EcoMarket's recommendation
Both, in different layers, if HCP is adopted:
| Layer | Tool | What it checks | Why there |
|---|---|---|---|
| The PR, in CI | Conftest | Quick rules about the plan's shape and style | Feedback in seconds, inside the PR |
The run, in HCP |
Sentinel | Security, compliance, cost, module provenance | It is the control nobody on the product team can disable |
Keeping both has a real cost — two languages, two test suites — and it only pays off if the rules are different. Duplicating the same rule in both places is the worst of both worlds: they drift apart and people stop believing either.
- Cost estimation as a gate
HCP Terraform computes, on every run, the estimated monthly cost of the plan's resources and the delta against what exists.
Cost estimation Resources: 23 estimated / 4 not estimated Monthly cost (current): $1,847.20 Monthly cost (proposed): $2,103.60 Change: +$256.40 (+13.9%)
| What it DOES estimate | What it does NOT estimate |
|---|---|
| Instances, disks, databases, load balancers | Network traffic, which in an online store can be dominant |
| List price per hour and per month | Commitment discounts, reserved instances, Savings Plans |
| AWS, Azure and GCP (the main ones) | Other providers: they show as "not estimated" |
| The declared sizing | Real usage: an empty bucket and one with 40 TB cost the same in the estimate |
Read it as an order of magnitude, not as a bill. Its real value is not the number, it is the surprise: a PR that says "minor sizing adjustment" and produces +$3,400/month is caught in the review and not in the bill six weeks later.
The cost policy from §11 turns it into a gate. And there is a design nuance worth pointing out: the threshold is on the delta, not on the total. A threshold on the total would block every production run from the day the infrastructure grows, including the ones that do not change the cost.
- Private registry for modules and providers
04-04 explained the public registry and how EcoMarket publishes its modules with tags. HCP's private registry adds what was missing: access control and internal visibility.
| Public registry | HCP's private registry | |
|---|---|---|
| Who can see it | Everybody | Only the organisation |
| Source | A public repository with tags | A connected repository, public or private |
| Publication | Automatic on tagging | Automatic on tagging |
| Documentation | Generated from the README and the variables |
The same |
| Versions | Every SemVer tag | The same |
| Your own providers | Requires GPG signing and a process | Yes, internal providers too |
source in the code |
ecomarket/network/aws |
app.terraform.io/ecomarket/network/aws |
# Consuming it from EcoMarket's code, with the version constraint
# from 04-05 unchanged:
module "network" {
source = "app.terraform.io/ecomarket/network/aws"
version = "~> 3.0"
prefix = local.prefix
cidr = local.current.cidr
common_tags = local.common_tags
}The publication flow does not change: you push a v3.2.1 tag to the module's repository and the registry indexes it. What changes is that, with the CI from §12 of 08-03 in front of it, the tag is only created if the tests pass, the CHANGELOG has an entry and it points at main.
And the private registry enables a policy that was previously impossible: the tfconfig one from §13 that requires every module to come from app.terraform.io/ecomarket/. With the public registry there is no way of telling your own module from a stranger's with a similar name.
- Teams, permissions and
run tasks
run tasksTeams and permissions
| Permission over a workspace | What it allows |
|---|---|
| Read | See the workspace, its runs and the state |
| Plan | Create plan-only runs; it cannot apply |
| Write | Plan and apply, manage variables |
| Admin | Everything, permissions and deletion included |
EcoMarket's configuration:
| Team | *-dev |
*-staging |
*-prod |
|---|---|---|---|
| development | Write | Plan | Read |
| platform | Admin | Write | Write |
| security | Read | Read | Read + policy management |
| oncall | Write | Write | Write (for incidents) |
This implements the separation from 08-01 §4 at the level of people, complementing the machine-level role separation: the development team can see the production plan and cannot apply it.
And the policy override permission (manage-policy-overrides) is separate from Write: only platform has it. Somebody can apply to production and still be unable to override a soft-mandatory policy.
run tasks
A run task is an HTTP hook that runs at a phase of the run and can block it. It is the platform's extension mechanism.
| Phase | When it runs | What for |
|---|---|---|
| Pre-plan | Before the plan | Validate the configuration, check a window |
| Post-plan | After the plan, before the policies | The most useful: external scanners over the plan |
| Pre-apply | After approval, before the apply | Open a change ticket, notify a channel |
| Post-apply | After the apply | Record in a CMDB, notify |
flowchart LR
P["plan"] --> RT1["post-plan run task<br/>Infracost / Snyk / Checkov"]
RT1 --> S["Sentinel"]
S --> AP{{"approval"}}
AP --> RT2["pre-apply run task<br/>open a change ticket"]
RT2 --> A["apply"]
A --> RT3["post-apply run task<br/>record in the CMDB"]
It is the way of recovering what the table in §2 said HCP does not do: a post-plan run task can run Checkov, Trivy or Conftest over the plan and block the run. The cost is maintaining an HTTP service that speaks the run-task protocol, or using one of the built-in ones from the catalogue.
- The API and the
tfe provider
tfe providerNine workspaces, three variable sets, one policy set, four teams and their permissions: configuring that by hand in the interface is tedious, unreproducible and unreviewed.
The tfe provider manages HCP Terraform with Terraform. It is exactly the same argument that underpins the whole course, applied to the pipeline itself.
# infra/platform/workspaces.tf
# EcoMarket's platform, as code. This directory has its own workspace
# (ecomarket-platform) and its own state.
terraform {
required_providers {
tfe = { source = "hashicorp/tfe", version = "~> 0.60" }
}
}
locals {
# The matrix: 3 components x 3 environments = 9 workspaces.
# Defined once, applied nine times. If there is a fourth component
# tomorrow, it is one line.
components = ["network", "data", "app"]
environments = ["dev", "staging", "prod"]
workspaces = {
for pair in setproduct(local.components, local.environments) :
"${pair[0]}-${pair[1]}" => { component = pair[0], environment = pair[1] }
}
}
resource "tfe_workspace" "ecomarket" {
for_each = local.workspaces
name = "ecomarket-${each.key}"
organization = "ecomarket"
project_id = tfe_project.platform.id
working_directory = "infra/${each.value.component}"
terraform_version = file("${path.module}/../../.terraform-version")
# Path triggers: the workspace only reacts to its own things
# and to the shared files (08-01 §9).
trigger_patterns = [
"infra/${each.value.component}/**",
"modules/**",
"environments/**",
]
# auto_apply ONLY in dev. It is the promotion from 08-01 §10 as code.
auto_apply = each.value.environment == "dev"
# Manual confirmation in staging and prod is configured with
# auto_apply = false; the permissions for who may confirm come
# from the teams (§16).
# Protects against an accidental destroy of the whole workspace.
force_delete = false
vcs_repo {
identifier = "ecomarket/ecomarket-infra"
branch = each.value.environment == "prod" ? null : "main"
# In prod, the trigger is the TAG, not the branch (§4):
# promotion by version, not by merge (07-02).
tags_regex = each.value.environment == "prod" ? "^release-\\d+\\.\\d+\\.\\d+$" : null
oauth_token_id = var.vcs_token
}
tags = ["ecomarket", each.value.component, each.value.environment]
}
# --- Each workspace's variables ---
resource "tfe_variable" "environment" {
for_each = local.workspaces
workspace_id = tfe_workspace.ecomarket[each.key].id
key = "environment"
value = each.value.environment
category = "terraform"
description = "Deployment environment. It governs local.current and the tags."
}
# --- Dynamic authentication (§7): two variables per workspace ---
resource "tfe_variable" "aws_auth" {
for_each = local.workspaces
workspace_id = tfe_workspace.ecomarket[each.key].id
key = "TFC_AWS_PROVIDER_AUTH"
value = "true"
category = "env"
}
resource "tfe_variable" "plan_role" {
for_each = local.workspaces
workspace_id = tfe_workspace.ecomarket[each.key].id
key = "TFC_AWS_PLAN_ROLE_ARN"
value = "arn:aws:iam::${local.accounts[each.value.environment]}:role/ecomarket-terraform-plan-${each.value.environment}"
category = "env"
description = "READ-ONLY role for the plan phase (08-01 §4)."
}
resource "tfe_variable" "apply_role" {
for_each = local.workspaces
workspace_id = tfe_workspace.ecomarket[each.key].id
key = "TFC_AWS_APPLY_ROLE_ARN"
value = "arn:aws:iam::${local.accounts[each.value.environment]}:role/ecomarket-terraform-${each.value.environment}"
category = "env"
description = "WRITE role for the apply phase."
}
# --- The per-team permissions (§16) ---
resource "tfe_team_access" "development" {
for_each = local.workspaces
team_id = tfe_team.development.id
workspace_id = tfe_workspace.ecomarket[each.key].id
access = lookup({
dev = "write",
staging = "plan",
prod = "read",
}, each.value.environment, "read")
}
# --- The policy set, from a SEPARATE repository ---
resource "tfe_policy_set" "ecomarket" {
name = "ecomarket-policies"
description = "Sentinel. A separate repository: whoever changes the infra does not change them."
organization = "ecomarket"
kind = "sentinel"
policies_path = "ci/sentinel"
global = true # it applies to ALL workspaces
vcs_repo {
identifier = "ecomarket/ecomarket-policies"
branch = "main"
oauth_token_id = var.vcs_token
}
}The detail that closes the argument: the policy set points at ecomarket/ecomarket-policies, a repository different from the infrastructure one, with its own security CODEOWNERS. And this file itself (infra/platform/) also has CODEOWNERS, because whoever can change it can disable the policies by setting global = false.
- No-code provisioning and Stacks
Two recent capabilities, as brief notes on where the product is heading.
No-code provisioning. It lets you publish a module in the private registry marked as "no-code", and have somebody deploy it from the interface by filling in a form, without writing HCL or having access to the repository. The platform creates the workspace, the configuration and the run.
What it is really for: letting a product team ask for "a development database" without opening a PR or waiting for platform, inside a module platform has written with its own limits and policies. It is a self-service route with guard rails.
Its limit: it only works for repetitive, well-bounded cases. It does not replace writing infrastructure.
Stacks. It tackles the problem 07-05 solved with Terragrunt: orchestrating several components with dependencies between them, deployed across several environments. A Stack declares components, their dependencies and their deployments, and the platform works out the ordering and propagates the outputs.
It is HashiCorp's answer to the gap Terragrunt was filling. It is worth following its evolution before building on it: it is the part of the product that has changed the most recently.
- Self-hosted Terraform Enterprise
| When it makes sense | When it does not |
|---|---|
| An explicit regulatory data-residency requirement | "We would rather have it in-house" with no requirement |
| A network with no internet access at all | A reachable private network: agent mode solves it |
| An audit demanding physical control of the infrastructure | Generic fear of SaaS |
| A volume that makes the licence better value than consumption | Small teams |
Requirements and operational cost, which is what usually gets underestimated:
| Aspect | What it implies |
|---|---|
| Deployment | Kubernetes or a VM; external PostgreSQL, object storage, Redis |
| High availability | An active-active configuration, with its complexity |
| Backups | Of the database and the object storage, tested |
| Upgrades | Your own cycle; features arrive later |
| TLS and certificates | Yours, with their rotation |
| Monitoring | Yours |
| Disaster recovery | Yours: if it goes down, you cannot deploy anything |
| People | In practice, one person part-time, permanently |
The last row is the decisive one. Terraform Enterprise is not a product you install: it is a service you operate. The right question is not whether the licence fits the budget, but whether there is somebody who will still be looking after it in two years.
- Pricing, limits and when it pays off
The model
| Plan | What it includes | Model |
|---|---|---|
| Free | Up to 500 managed resources, remote execution, state, private registry, VCS | Free |
| Standard | More resources, teams and permissions, run tasks |
Per managed resource, monthly |
| Plus | Sentinel and OPA, cost estimation, drift detection, agents, auditing | Per managed resource, higher |
| Enterprise | Self-hosted, advanced SSO, support | A negotiated annual licence |
The detail that surprises the most and is most worth understanding before adopting: it is billed per managed resource, defined roughly as the state entries corresponding to billable infrastructure. Not per run, not per user, not per compute time.
Practical consequences:
- A
for_eachover 40 subnets is 40 managed resources, always, whether they are touched or not. - A workspace that never runs still costs what its resources cost.
- Refactoring to reduce resources reduces the bill.
- And the key feature for an organisation with security requirements — Sentinel — is in the Plus plan, which is the expensive one. If you are adopting HCP for the policies, budget for that plan.
The honest table
Picking up the comparison from 07-05 §alternatives, now with this module's data:
| Situation | Your own pipeline | HCP Terraform | Why |
|---|---|---|---|
| A team of 2-3 people, one environment, little infrastructure | Yes | Free, perhaps | Your own pipeline fits in a 60-line workflow |
| A team of 5-15, three environments, CI already built and working | Yes | Maybe | You have already paid the cost of building it; migrating costs and solves nothing new |
| A team of 5-15, without CI in place, starting out | It costs weeks | Yes | It is exactly the case HCP solves best |
| Several teams tripping over the state | It can be done | Yes | Per-workspace permissions and a visible queue are hard to replicate |
| A requirement for policies the team cannot disable | Conftest with CODEOWNERS |
Yes | Sentinel in the organisation is a stronger boundary |
| A need for cost estimation as a gate | Infracost in CI | Yes | Built in, with tfrun |
| Self-service for product teams | Very costly | Yes | No-code provisioning |
| A very tight budget, a lot of infrastructure | Yes | Expensive | It is billed per resource: a lot of infrastructure, a big bill |
| A data-residency requirement | Yes | Enterprise, or agents | It depends on the exact requirement |
| You already use Terragrunt with 12 environments and it works | Yes | Migrating costs | HCP and Terragrunt partly overlap; migrating is a project |
The recommendation for EcoMarket, said plainly: with nine workspaces, three environments, a small platform team and the pipeline from 08-03 already built and working, HCP Terraform does not pay off today. What would have paid off is adopting it from the start, before building anything.
And there are two things that would change it: if the number of teams touching infrastructure went from one to five — per-workspace permissions and the queue would stop being a luxury — or if a compliance requirement appeared demanding that the policies live out of reach of whoever makes the changes.
The lesson worth taking away is not "buy it" or "build it", but understanding exactly what you are buying: the state and its locking, execution, credentials, approvals, policies, the registry and auditing. And what remains yours: the linters, the scanners, the tests and the quality of the code.
Common Mistakes and Tips
Confusing CLI workspaces with HCP ones. They are different things with the same name. Tip: if you are coming from the CLI, think of an HCP workspace as "a root directory with its own variables and credentials", not as "one more state".
Connecting the VCS before migrating the state. A push triggers a run on an empty workspace, the plan proposes creating everything, and if auto_apply is on, it creates it. Tip: migrate the state first, verify a zero plan, and then connect the VCS.
Not verifying the zero plan after the migration. It is the check, just as in the Terragrunt migration in 07-05. A plan that proposes creating 23 resources means something is wrong, and carrying on "to see if it sorts itself out" produces duplicated infrastructure.
Deleting the state bucket on the same day you migrate. It removes the only safety net. Tip: keep it with versioning for a few months, and retire it in a change of its own.
Confusing Terraform variables with environment variables. Setting AWS_REGION as a Terraform variable configures nothing, and setting environment as an environment variable does not either. Tip: if the code has a variable "x" block, it is a Terraform one; if it is something you would export in your shell, it is an environment one.
Rolling out a new policy straight as hard-mandatory. Every deployment blocked on Monday morning, the urgent ones included. Tip: advisory first, measure how many runs would fail, fix the existing infrastructure, and then raise the level.
Writing policies with no tests. A policy that always returns true protects nothing and nobody notices. Tip: sentinel test with at least one case that must pass and one that must fail per rule.
Assuming the cost estimate always exists. There are unsupported providers and runs where it is not computed. A policy that does not allow for that fails with a cost message when the problem is something else. Tip: check is not null before using it.
Using tags instead of tags_all in tagging policies. A false block on every resource that relies on default_tags, which is nearly all of them. It is the same nuance as in Rego.
Duplicating the same rules in Sentinel and in Conftest. They drift apart, and when they diverge people stop believing either. Tip: different rules in different layers, or a single tool.
Putting the policy set in the same repository as the infrastructure. It stops being a control: whoever makes the change can relax the policy in the same PR. Tip: a separate repository, with security CODEOWNERS.
Forgetting that infra/platform/ is as critical as the policies. Whoever can change the tfe_policy_set can set global = false and disable them all. Tip: CODEOWNERS there too, and a mandatory security review.
Adopting Terraform Enterprise out of discomfort with SaaS. You swap a subscription for a service you have to operate indefinitely. Tip: if the problem is the private network, agent mode solves it without self-hosting anything.
Not budgeting for the Plus plan if you need Sentinel. It is the feature many organisations adopt HCP for and it is in the expensive plan. Tip: clarify it before the proof of concept, not afterwards.
Underestimating billing per managed resource. A for_each over 200 objects is billed even if it is never touched. Tip: estimate the bill against the current state before deciding.
Exercises
Exercise 1: the exceptions policy
EcoMarket's data team needs an r6i.4xlarge instance for a database migration that will last three weeks. The allowed-instances policy from §11 is soft-mandatory and that type is not on the list.
There are four ways of resolving it. Analyse them and choose, with justification:
- Add
r6i.4xlargetoallowed_types. - Override the policy on that specific
run. - Lower the policy to
advisorytemporarily. - Modify the policy to accept a bounded exception.
Then implement the option you choose, including whatever is needed so that the exception does not stay forever.
Exercise 2: migrating ecomarket-data-prod to HCP
You have the production data component in an S3 backend, with 31 resources in the state, including the RDS database with prevent_destroy. It has to be migrated to the ecomarket-data-prod workspace.
Write the complete procedure, including:
- The steps, in order, with the commands.
- The three points where you have to stop if something does not add up, with the exact criterion.
- Which variables have to be created in the workspace and of which category.
- The rollback plan if the migration goes wrong half-way.
Exercise 3: deciding for three organisations
For each of these three organisations, recommend your own pipeline, HCP Terraform (saying which plan) or Terraform Enterprise, with three concrete reasons and one objection to your own recommendation.
A. A 6-person startup, 2 of whom touch infrastructure. One production environment and one development environment, around 180 resources. They already use GitHub Actions for the application. No compliance requirements. A tight budget.
B. A mid-sized bank. 40 people in 6 teams touch infrastructure. 4 environments, around 9,000 resources. A regulatory requirement: the configuration data cannot leave the EU. An annual audit that requires demonstrating that the controls cannot be disabled. Budget available.
C. A 120-person company, 15 of whom touch infrastructure across 3 teams. 3 environments, around 2,500 resources. They have Jenkins with a Terraform pipeline that has worked for two years, maintained by one person who is leaving next month. No data-residency requirements.
Solutions
Solution 1
Analysis of the four options.
| Option | Effect | Problem |
|---|---|---|
| 1. Add it to the list | r6i.4xlarge allowed forever, in every workspace |
The temporary exception becomes permanent. In a year nobody remembers why it is there, and the next person who needs it already finds it |
2. Override the run |
It works today, and who overrode is recorded | Every subsequent run has to be overridden: any change in data puts that instance back in the plan. Three weeks of overrides is daily friction and ends up as option 3 |
3. Lower it to advisory |
The friction disappears | It disables the policy for the whole organisation for three weeks, including runs that have nothing to do with it. It is the worst: it solves the particular case by unprotecting the whole |
| 4. A bounded exception | Allows that type, in that workspace, until that date | More code, and you have to remember to clean up. But the expiry can be automated |
The choice: option 4, and the reason is the expiry. The first three create an exception that depends on somebody remembering to revert it, and that remembering is exactly what 07-04 identified as the difference between a control and a good intention.
# ci/sentinel/policies/allowed-instances.sentinel (version with exceptions)
import "tfplan/v2" as tfplan
import "tfrun"
import "time"
import "strings"
allowed_types = [
"t3.micro", "t3.small", "t3.medium", "t3.large",
"m6i.large", "m6i.xlarge", "r6i.large",
]
expensive_types = ["m6i.xlarge", "r6i.large"]
# --- TEMPORARY EXCEPTIONS ---
# Every entry MUST carry: workspace, type, expiry date, ticket and owner.
# Without all five fields it is not an exception: it is a hole with
# nobody's name on it.
#
# MAINTENANCE RULE: an expired exception makes the policy block again
# automatically. Nobody has to remember.
exceptions = [
{
"workspace": "ecomarket-data-prod",
"type": "r6i.4xlarge",
"expires": "2026-11-15T00:00:00Z",
"ticket": "INFRA-2841",
"owner": "[email protected]",
"reason": "PostgreSQL 16->17 migration: the reindex needs memory.",
},
]
now = time.now
# --- Exceptions in force for THIS workspace ---
active_exceptions = filter exceptions as _, e {
e.workspace is tfrun.workspace.name and
time.load(e.expires).unix > now.unix
}
exception_types = []
for active_exceptions as _, e {
append(exception_types, e.type)
}
# Warn about the exceptions being used: they must be visible on EVERY
# run, so nobody forgets them and the reviewer keeps them in mind.
for active_exceptions as _, e {
days = (time.load(e.expires).unix - now.unix) / 86400
print("ACTIVE EXCEPTION:", e.type, "in", e.workspace)
print(" Ticket:", e.ticket, "· Owner:", e.owner)
print(" Reason:", e.reason)
print(" Expires in", days, "days (" + e.expires + ")")
if days < 5 {
print(" WARNING: fewer than 5 days left. If it is still needed,")
print(" renew the exception with a PR to the policy repository.")
}
}
# --- Warn about the EXPIRED ones too, so they get cleaned out ---
expired_exceptions = filter exceptions as _, e {
time.load(e.expires).unix <= now.unix
}
for expired_exceptions as _, e {
print("CLEAN-UP PENDING: exception", e.ticket, "(" + e.type + ")")
print(" expired on", e.expires, "and is still in the file. Remove it in a PR.")
}
# --- The rule, with the effective list ---
effective_allowed = allowed_types + exception_types
instances = filter tfplan.resource_changes as _, rc {
rc.type is "aws_instance" and
rc.mode is "managed" and
(rc.change.actions contains "create" or rc.change.actions contains "update")
}
violations = []
for instances as address, rc {
type = rc.change.after.instance_type
if type not in effective_allowed {
append(violations, address)
print("BLOCKED:", address, "uses type", type)
print(" Allowed:", strings.join(allowed_types, ", "))
if length(exception_types) > 0 {
print(" Exceptions in force here:", strings.join(exception_types, ", "))
}
print(" For a temporary exception: a PR to ecomarket-policies with")
print(" workspace, type, expiry date, ticket, owner and reason.")
}
if type in expensive_types or type in exception_types {
tags = rc.change.after.tags else {}
if "Justification" not in keys(tags) {
append(violations, address)
print("BLOCKED:", address, "uses", type, "with no Justification tag.")
}
}
}
main = rule { length(violations) is 0 }Why this implementation closes the "exception that stays forever" problem:
- The expiry is what blocks, not a person. On 15 November, the policy starts blocking again on its own. Nobody has to remember.
- The warning appears on every
run. The exception is visible to anybody looking at a plan; it is not hidden away in a configuration. - The 5-day warning gives time to renew it if it really is still needed, through a PR that forces it to be justified again.
- Expired ones are announced until they are cleaned out, so the file does not accumulate silent rubbish.
- The five mandatory fields turn "adding an exception" into an act with an owner, a reason and a date.
And the accompanying test:
# test/allowed-instances/expired-exception.hcl
# The MOST important test: it verifies that a lapsed exception
# no longer allows anything. Without it, a bug in the date comparison
# would leave every exception open forever.
mock "tfplan/v2" { module { source = "./mock-tfplan-r6i4xl.sentinel" } }
mock "tfrun" { module { source = "./mock-tfrun-data-prod.sentinel" } }
mock "time" { module { source = "./mock-time-2027.sentinel" } } # year 2027
test { rules = { main = false } } # it MUST blockSolution 2
1. The procedure, in order.
# ============ PHASE 0: PREPARATION (touching nothing) ============
# 0.1 — Back up the state. ALWAYS first.
terraform -chdir=infra/data init -reconfigure \
-backend-config=backends/prod.hcl
terraform -chdir=infra/data state pull > backup-data-prod-$(date +%F).tfstate
# 0.2 — Note down the invariants that will have to be verified afterwards.
jq '.resources | length' backup-data-prod-*.tfstate # 31
jq -r '.serial' backup-data-prod-*.tfstate # e.g. 412
jq -r '.lineage' backup-data-prod-*.tfstate # the UUID
jq -r '.terraform_version' backup-data-prod-*.tfstate # 1.9.8
terraform -chdir=infra/data state list > resource-list-before.txt
# 0.3 — Keep the backup OUTSIDE the repository, encrypted.
age --encrypt --recipient-file ci/backup-key.pub \
-o backup-data-prod.tfstate.age backup-data-prod-*.tfstate
aws s3 cp backup-data-prod.tfstate.age \
s3://ecomarket-migration-backups/2026/ --sse aws:kms
rm -f backup-data-prod-*.tfstate # the plaintext does not stay on disk
# 0.4 — A zero plan BEFORE migrating. If the current state already has
# drift, it must be resolved FIRST: migrating with drift mixes
# two problems and makes diagnosis impossible.
terraform -chdir=infra/data plan -detailed-exitcode \
-var-file=environments/common.auto.tfvars -var-file=environments/prod.tfvars
echo "code: $?" # ← STOPPING POINT 1
# ============ PHASE 1: THE WORKSPACE, EMPTY ============
# 1.1 — Create ecomarket-data-prod in HCP:
# - WITHOUT connecting the VCS yet
# - terraform_version = 1.9.8 (the SAME as the state's)
# - execution_mode = remote
# 1.2 — Create the variables (see point 3 of this solution).
# 1.3 — Check that the credentials work with a manual PLAN-ONLY run
# over an empty directory... or better: wait for step 2.3,
# which already checks it.
# ============ PHASE 2: THE MIGRATION ============
# 2.1 — Replace the backend block with the cloud block.
cat > infra/data/versions.tf <<'HCL'
terraform {
required_version = "~> 1.9"
cloud {
organization = "ecomarket"
workspaces { name = "ecomarket-data-prod" }
}
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
}
}
HCL
# 2.2 — Authenticate and migrate. This init is MANUAL and supervised:
# no -input=false here.
terraform login
terraform -chdir=infra/data init
# Terraform notices the backend change and asks whether to migrate.
# Answer "yes".
# 2.3 — Verify that the state ARRIVED. ← STOPPING POINT 2
terraform -chdir=infra/data state list > resource-list-after.txt
diff resource-list-before.txt resource-list-after.txt
wc -l resource-list-after.txt # it must be 31
# ============ PHASE 3: THE CHECK ============
# 3.1 — THE check. ← STOPPING POINT 3
terraform -chdir=infra/data plan -detailed-exitcode
echo "code: $?" # it MUST be 0
# ============ PHASE 4: CONSOLIDATION (only with a zero plan) ============
# 4.1 — Connect the workspace to the VCS:
# repository ecomarket/ecomarket-infra
# working_directory = infra/data
# trigger_patterns = infra/data/**, modules/**, environments/**
# auto_apply = false
# tags_regex = ^release-\d+\.\d+\.\d+$ (promotion by tag)
# 4.2 — Retire backends/prod.hcl for this component and update the
# README and docs/deployment.md.
# 4.3 — A test run from the interface: a zero plan again, this time
# triggered by the platform and not by the CLI.
# 4.4 — The S3 bucket and its versioning are KEPT for 3 months. The
# retirement date is noted in docs/adr/0004-hcp-migration.md.2. The three stopping points.
| # | Moment | Criterion for continuing | If it is not met |
|---|---|---|---|
| 1 | Step 0.4, before migrating | plan -detailed-exitcode returns 0 |
Stop. There is pre-existing drift. Resolve it first: migrating with drift mixes two problems and makes it impossible to know whether a change in the later plan comes from the migration or from the drift |
| 2 | Step 2.3, after the init |
state list returns 31 resources and the diff is empty |
Stop. The state was not copied. Do not run any plan or apply: a plan over an empty state proposes creating the production database. Check the workspace's credentials and permissions, and repeat the init |
| 3 | Step 3.1, the plan | Code 0: no changes | Stop. Diagnose with the table in §6. The most likely cause is a missing variable or one with a value different from prod.tfvars. Apply nothing until the plan comes out at zero |
And an additional criterion at point 3 that is specific to this component: if the plan proposes replacing (delete+create) the aws_db_instance, it is an emergency. It has prevent_destroy, so Terraform will fail on the apply, but the fact that the plan proposes it means an immutable variable — the identifier, the encryption, the class — does not match. Diagnose before anything else:
terraform -chdir=infra/data show -json plan.tfplan | jq -r '
.resource_changes[]
| select(.change.actions == ["delete","create"] or .change.actions == ["create","delete"])
| "\(.address) ← \((.change.replace_paths // []) | flatten | join(", "))"'3. The workspace's variables.
| Key | Category | Value | Sensitive | HCL | Where it comes from |
|---|---|---|---|---|---|
environment |
terraform | prod |
No | No | environments/prod.tfvars |
environments |
terraform | { prod = { ... } } |
No | Yes | var.environments from prod.tfvars |
db_password |
terraform | •••• |
Yes | No | The real password; entered once and never read back |
project |
terraform | ecomarket |
No | No | The common-tags set |
owner |
terraform | [email protected] |
No | No | The common-tags set |
repo |
terraform | ecomarket-infra |
No | No | The common-tags set |
AWS_REGION |
env | eu-west-1 |
No | — | backends/prod.hcl |
TFC_AWS_PROVIDER_AUTH |
env | true |
No | — | Dynamic authentication (§7) |
TFC_AWS_PLAN_ROLE_ARN |
env | arn:...:role/ecomarket-terraform-plan-prod |
No | — | 08-03 §2 |
TFC_AWS_APPLY_ROLE_ARN |
env | arn:...:role/ecomarket-terraform-prod |
No | — | Likewise |
The last four are better placed in a variable set applied to the three *-prod workspaces, so they are not repeated.
Two warnings about db_password:
- Marking it sensitive means it cannot be read back. You need it to hand from somewhere else (the secret manager) before entering it.
- Better still: take the migration as an opportunity to remove it as a variable and have Terraform read it with
data "aws_secretsmanager_secret_version"(07-04). With the apply role assumed, it works without the password ever passing through HCP. But that is a code change, and it is not mixed with a migration: migrate first with a zero plan, then make the change, in a separate PR.
4. The rollback plan.
The good news: the migration does not destroy the source state. init copies it to the new workspace; the S3 object is still there, with its versioning.
| Failure in... | Rollback | Risk |
|---|---|---|
| Phase 0 or 1 | There is nothing to roll back | None |
Phase 2, the init fails half-way |
Restore versions.tf from Git, init -reconfigure with the S3 backend |
None: the S3 state has not been touched |
| Phase 3, the plan does not come out at zero | Do not roll back yet: diagnose. If it cannot be resolved, restore versions.tf, init -reconfigure, and delete the HCP workspace |
Low: nothing has been applied |
Phase 4, after connecting the VCS and with runs already executed |
More delicate: see below | Medium |
# --- ROLLBACK from phase 2 or 3 (the normal case) ---
git checkout infra/data/versions.tf # the backend block returns
terraform -chdir=infra/data init -reconfigure \
-backend-config=backends/prod.hcl
terraform -chdir=infra/data state list | wc -l # 31: intact
terraform -chdir=infra/data plan -detailed-exitcode # 0
# And delete the HCP workspace so that no orphan state is left
# that somebody could apply by mistake.
# --- ROLLBACK from phase 4, if there was already an APPLY in HCP ---
# Here the HCP state and the S3 one have DIVERGED: HCP's reflects
# reality and S3's is out of date. Going back to S3 without more
# would make Terraform propose undoing what was applied.
# 1. Download the CURRENT state from HCP.
terraform -chdir=infra/data state pull > current-hcp-state.tfstate
# 2. Restore the backend block and initialise against S3.
git checkout infra/data/versions.tf
terraform -chdir=infra/data init -reconfigure -backend-config=backends/prod.hcl
# 3. Push the HCP state to S3. The serial must be HIGHER than the one
# in S3, or Terraform will reject it.
terraform -chdir=infra/data state push current-hcp-state.tfstate
# 4. Verify a zero plan. If it does not come out at zero, STOP and ask
# for help: from here on you are doing surgery on the production
# state, which is the subject of module 9.
terraform -chdir=infra/data plan -detailed-exitcodeAnd the prevention that makes almost all of this rollback unnecessary: migrate dev first, then staging, and prod only once the other two have been running for a week. Every migration teaches you something, and learning it in dev is free.
Solution 3
A. A 6-person startup, 180 resources.
Recommendation: your own pipeline in GitHub Actions, with HCP Terraform Free for the state.
- 180 resources fit comfortably in the free tier (a 500 limit), so managed state, locking and remote execution come free. That eliminates the S3 bucket, the lock table and their configuration: less to set up and less to maintain.
- They already have GitHub Actions working for the application. Adding a Terraform workflow is familiar work, not a new tool to learn.
- With 2 people touching infrastructure, per-workspace permissions add nothing. The differentiating value of the paid plans — Sentinel, cost, teams — solves problems they do not have.
An objection to my own recommendation: the 500-resource limit is closer than it looks. A VPC with subnets in three zones, a Kubernetes cluster and its node groups add up fast. The day they exceed it, the bill appears all at once with no budgetary warning. It is worth setting an alert at 400 and deciding then, with time, rather than finding out from an invoice.
B. A mid-sized bank, 9,000 resources, data in the EU, an audit.
Recommendation: HCP Terraform on the Plus plan, in the European region; Terraform Enterprise only if the regulator rejects that option.
- The audit requirement — demonstrating that the controls cannot be disabled — is exactly what Sentinel in the organisation solves and what Conftest in the pipeline solves less well. In an audit, "the policies live in a console the infrastructure team has no access to, and changing a policy leaves a record" is a far more solid answer than "we have
CODEOWNERS". - 6 teams sharing infrastructure is the case where per-workspace permissions and a visible queue stop being a luxury. Replicating that in your own pipeline means building an authorisation system, which is a project in itself.
- The budget is available and 9,000 resources justify the Plus plan, whose features — Sentinel, auditing, drift detection, agents — are the ones the case needs.
An objection: I have assumed that HCP's data residency in the EU satisfies the regulator, and that has to be verified with the regulator and with the legal department, not assumed. "Configuration data" can be interpreted broadly: the Terraform state contains resource attributes that may count as sensitive architectural information. If the interpretation is strict, the recommendation changes to Terraform Enterprise, with all its operational cost — and then you have to budget for the person who will operate it, which in a mid-sized bank is probably not just one.
C. 2,500 resources, a Jenkins that works, and the person maintaining it is leaving.
Recommendation: HCP Terraform on the Standard plan, with a staged migration over 6 months; keep Jenkins for verification.
- The decisive factor is not technical, it is about people. A Jenkins pipeline maintained by one person who is leaving is technical debt with a due date. The realistic alternative is not "somebody else maintains it" — nobody else knows it — but that it degrades until it fails at the worst possible moment.
- 2,500 resources and 3 teams justify the cost, and the Standard plan covers what they need: state, execution, per-team permissions and
run tasks. There is no compliance requirement forcing Sentinel, so the jump to Plus can wait. - The migration is staged and low-risk:
devfirst, thenstaging, thenprod, component by component, with a zero plan at every step. And Jenkins is kept forfmt,tflint, the scanners andterraform test, which HCP does not run (§2). Jenkins's scope shrinks to something anybody can maintain.
An objection: I am solving a people problem with an architecture decision, and that carries an obvious risk. Migrating 2,500 resources and 3 teams to a new platform just as the person who knows the most is leaving is running a large project at the worst possible moment. The honest alternative — and one to evaluate before deciding — is to spend the two months of notice documenting the Jenkins setup and training two people, and then decide calmly whether to migrate.
If that option is not viable because the person has already disengaged or the notice is short, my recommendation stands: it is better to migrate to something managed than to inherit a system nobody understands. But it is a risk-management decision, not a technical recommendation, and it is worth saying so to whoever has to sign it off.
Conclusion
HCP Terraform and Terraform Enterprise replace a good part of the machinery from the previous three lessons, and not all of it.
- They replace the execution pipeline: the state and its locking, remote execution, the plan artefact with its secrets, the variables and credentials, the approvals, the policies, the private registry and the auditing. They do not replace the verification pipeline:
fmt,tflint, the scanners andterraform testremain yours, in your CI. - The debt from 06-01 is settled: a CLI workspace is a state; an HCP workspace is a deployment, with its own configuration, variables, credentials, Terraform version, permissions and history. That is why the former did not separate environments and the latter do. And with
tags, the CLI workspace stops creating states and starts selecting which of the remote ones is used. - EcoMarket is nine workspaces with the same partitioning as the S3 backend keys, because changing platform is no reason to revisit the expensive decision from 07-01. Path triggers in
devandstaging, tag triggers inprod, which is the promotion-by-version rule from 07-02 implemented on the platform. - Agent mode solves the private-network objection without self-hosting anything: the agent opens an outbound connection and waits for work. And it is the same threat model as a self-hosted runner.
- Migrating from S3 has a single success criterion: a zero plan. An encrypted backup outside the repository, the workspace not connected to the VCS until the end, verification that the 31 resources arrived, and the bucket kept for months as a safety net.
- Terraform variables and environment variables are different categories, and confusing them is the cause of almost every "it cannot find the credentials". The sensitive flag in HCP is stronger than
sensitive: the value cannot be read back, and the problem of a.tfplanfull of plaintext secrets disappears. TFC_AWS_PLAN_ROLE_ARNandTFC_AWS_APPLY_ROLE_ARNare two variables that replace two workflows, two hand-configured roles and two trust relationships with their dangerous wildcards. That, very concretely, is what you buy.- Sentinel is a control and not a good intention, for a reason that is not technical: the policies live in the organisation, not in the repository. Whoever makes the change does not hold the key. Three levels —
advisoryfor launching,soft-mandatoryfor what admits a recorded exception,hard-mandatoryfor security and compliance — and four imports, of whichtfconfig/v2allows policies that are impossible over the plan's JSON. - A policy with no
sentinel testis a policy that blocks legitimate deployments on Monday. At least one passing case and one failing case per rule, and the policy set in a repository of its own with its own CI. - Sentinel and OPA do not compete on quality, they compete on location. Conftest runs wherever you want and is free; Sentinel runs where the team cannot reach. If you use both, with different rules in different layers — duplicating the same rule in both is the worst of both worlds.
- Cost estimation is an order of magnitude, not a bill, and its value lies in the surprise: a PR that says "minor adjustment" and proposes
+$3,400/month. The threshold goes on the delta, not on the total. - The platform is managed with the
tfeprovider, which is the course's own argument applied to the pipeline itself: nine workspaces, their variables, their permissions and their policy set, in afor_eachover a matrix. WithCODEOWNERSthere too, because whoever can setglobal = falsedisables every policy. - Terraform Enterprise is not a product you install, it is a service you operate. The question is not whether the licence fits the budget, but whether somebody will be looking after it in two years.
- And the honest table: with a pipeline already built and working, HCP does not pay off; starting from scratch, it does; with several teams tripping over each other or with a compliance requirement about the policies, it clearly does; with a lot of infrastructure and little budget, billing per managed resource can be prohibitive.
There is one model left to see, and it is the one that changes the nature of the interaction. In everything so far — your own pipeline or a managed platform — the plan is something a machine generates and publishes somewhere for you to go and look at: a comment, a status check, a run page. The module's last lesson, GitOps flows with Atlantis, inverts that relationship: the repository becomes the only interface, terraform plan stops being a command somebody runs and becomes a PR comment, and the apply is requested by writing atlantis apply in the conversation. With it comes a fundamental question we have been dodging all module — whether you apply before or after merging — and the difference between GitOps by pull request and continuous reconciliation, which is a controller correcting drift on its own, with everything good and everything dangerous about that.
