Andrew Mercer
on this page

Preventing mismatches like azurerm_resource_group.rg-project-name-eus-dev referencing name = "project-name-weu-dev" from being checked in, using two complementary approaches. Background on the tools and layers: policy as code.

Updated for current tooling. The Rego uses OPA 1.0 syntax (if/contains), which current Conftest requires. Token matching splits names into segments instead of substring matching, so eus no longer matches inside eus2. The pre-commit script handles python-hcl2's real output shape and checks both resource and data blocks.

The problem

# BAD: label says "eus" (East US) but name says "weu" (West Europe)
data "azurerm_resource_group" "rg-project-name-eus-dev" {
  name = "project-name-weu-dev"
}

# GOOD: label and name are consistent
data "azurerm_resource_group" "rg-project-name-weu-dev" {
  name = "project-name-weu-dev"
}

The label (rg-project-name-eus-dev) and the name argument (project-name-weu-dev) contain different region tokens (eus vs weu), and possibly different environment tokens. Both approaches below catch this class of bug before it reaches remote state.

A design note before the tooling: this bug exists because the label repeats information the name already holds. Labels like data.azurerm_resource_group.this or .app (with region and environment coming from the directory and variables) remove the class of bug entirely. See hygiene: naming. The checks below are for codebases where descriptive labels are the convention.

Approach 1: Conftest + OPA

Conftest uses the Open Policy Agent policy language (Rego) to evaluate structured data, including Terraform plans and raw .tf files. It's good at expressing semantic rules across resource relationships.

How it works

.tf files ─(conftest --parser hcl2)──────────────┐
                                                  ├─► Rego policies ─► pass / fail
terraform show -json tfplan ─► tfplan.json ───────┘

Installation

# Fedora / Linux: set CONFTEST_VERSION to the latest release from
# https://github.com/open-policy-agent/conftest/releases (0.56+ uses OPA 1.x)
CONFTEST_VERSION=X.Y.Z
curl -LO "https://github.com/open-policy-agent/conftest/releases/download/v${CONFTEST_VERSION}/conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz"
tar xzf "conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz" conftest
sudo mv conftest /usr/local/bin/

# macOS
brew install conftest

# Container
podman run --rm -v "$PWD:/project:Z" docker.io/openpolicyagent/conftest test ...

conftest --version

Project layout

terraform-project/
├── main.tf
├── variables.tf
├── policy/
│   ├── helpers.rego          # shared token helpers
│   ├── naming.rego           # rules
│   └── naming_test.rego      # unit tests for the rules
├── .conftest.yaml            # optional defaults
└── Makefile                  # optional convenience targets

Step 1: helpers

policy/helpers.rego

package helpers

import rego.v1

# Known region tokens. Extend as you add regions.
region_tokens := {
    "eus", "eus2", "wus", "wus2", "cus", "ncus", "scus",
    "weu", "neu", "uks", "ukw",
    "sea", "ea",
    "cac", "cae",
    "aue", "ause", "jpe", "jpw", "brs",
}

# Known environment tokens.
env_tokens := {"dev", "tst", "test", "stg", "uat", "qa", "prd", "prod", "sbx", "mgmt"}

# Split a name or address into segments on - . _ and lowercase it.
# "data.azurerm_resource_group.rg-proj-eus-dev" → {"data", "azurerm", "resource", "group", "rg", "proj", "eus", "dev"}
segments(s) := {t | some t in regex.split(`[-._]`, lower(s))}

regions_in(s) := segments(s) & region_tokens

envs_in(s) := segments(s) & env_tokens

# conftest's hcl2 parser wraps each block body in a list; tolerate both shapes.
bodies(x) := x if is_array(x)

bodies(x) := [x] if is_object(x)

Matching whole segments (set intersection) rather than substrings avoids false positives: eus doesn't match eus2, and ea doesn't match inside weu.

Step 2: rules

policy/naming.rego

package main

import rego.v1

import data.helpers

checked_types := {"azurerm_resource_group"}

# ─── Raw .tf files (conftest --parser hcl2) ──────────────────────────────────
# Checks both `data` and `resource` blocks.

blocks contains [kind, rtype, label, body] if {
    some kind in {"data", "resource"}
    some rtype, labels in input[kind]
    rtype in checked_types
    some label, raw in labels
    some body in helpers.bodies(raw)
}

deny contains msg if {
    some b in blocks
    [kind, rtype, label, body] := b
    is_string(body.name)
    not contains(body.name, "${")
    helpers.regions_in(label) != helpers.regions_in(body.name)
    msg := sprintf(
        "%s.%s.%s: region mismatch: label has %v but name '%s' has %v",
        [kind, rtype, label, helpers.regions_in(label), body.name, helpers.regions_in(body.name)],
    )
}

deny contains msg if {
    some b in blocks
    [kind, rtype, label, body] := b
    is_string(body.name)
    not contains(body.name, "${")
    helpers.envs_in(label) != helpers.envs_in(body.name)
    msg := sprintf(
        "%s.%s.%s: environment mismatch: label has %v but name '%s' has %v",
        [kind, rtype, label, helpers.envs_in(label), body.name, helpers.envs_in(body.name)],
    )
}

warn contains msg if {
    some b in blocks
    [kind, rtype, label, body] := b
    is_string(body.name)
    count(helpers.regions_in(body.name)) == 0
    msg := sprintf("%s.%s.%s: name '%s' has no recognised region token. Intentional?", [kind, rtype, label, body.name])
}

# ─── Plan JSON (terraform show -json) ────────────────────────────────────────
# Managed resources appear in resource_changes with resolved names,
# which catches names built from variables and locals.

deny contains msg if {
    rc := input.resource_changes[_]
    rc.mode == "managed"
    rc.type in checked_types
    name := rc.change.after.name
    is_string(name)
    helpers.regions_in(rc.name) != helpers.regions_in(name)
    msg := sprintf("%s: region mismatch: label has %v but planned name '%s' has %v",
        [rc.address, helpers.regions_in(rc.name), name, helpers.regions_in(name)])
}

deny contains msg if {
    rc := input.resource_changes[_]
    rc.mode == "managed"
    rc.type in checked_types
    name := rc.change.after.name
    is_string(name)
    helpers.envs_in(rc.name) != helpers.envs_in(name)
    msg := sprintf("%s: environment mismatch: label has %v but planned name '%s' has %v",
        [rc.address, helpers.envs_in(rc.name), name, helpers.envs_in(name)])
}

Notes:

  • In HCL mode, names containing ${ (interpolation) are skipped because the raw text isn't the real name. Plan mode covers those.
  • In plan JSON, rc.name is the label (rg-project-eus-dev) and rc.address is the full address. Data sources read during plan aren't in resource_changes, so data-source checks rely on HCL mode.
  • To check more types, add them to checked_types.

Step 3: unit tests

policy/naming_test.rego

package main_test

import rego.v1

import data.main

# conftest's hcl2 parser shape: block bodies wrapped in lists
good := {"data": {"azurerm_resource_group": {"rg-project-weu-dev": [{"name": "project-weu-dev"}]}}}

bad_region := {"data": {"azurerm_resource_group": {"rg-project-eus-dev": [{"name": "project-weu-dev"}]}}}

bad_env := {"resource": {"azurerm_resource_group": {"rg-project-weu-dev": [{"name": "project-weu-prd", "location": "westeurope"}]}}}

eus2_not_eus := {"data": {"azurerm_resource_group": {"rg-project-eus2-dev": [{"name": "project-eus2-dev"}]}}}

interpolated := {"data": {"azurerm_resource_group": {"rg-project-eus-dev": [{"name": "project-${var.region}-dev"}]}}}

plan_bad := {"resource_changes": [{
    "address": "azurerm_resource_group.rg-project-eus-dev",
    "name": "rg-project-eus-dev",
    "type": "azurerm_resource_group",
    "mode": "managed",
    "change": {"actions": ["create"], "after": {"name": "project-weu-dev"}},
}]}

test_good_naming_passes if {
    count(main.deny) == 0 with input as good
}

test_region_mismatch_denied if {
    count(main.deny) > 0 with input as bad_region
}

test_env_mismatch_denied_for_resources if {
    count(main.deny) > 0 with input as bad_env
}

test_eus2_is_not_eus if {
    count(main.deny) == 0 with input as eus2_not_eus
}

test_interpolated_names_skipped_in_hcl_mode if {
    count(main.deny) == 0 with input as interpolated
}

test_plan_mode_catches_resolved_names if {
    count(main.deny) > 0 with input as plan_bad
}
conftest verify --policy policy/

Step 4: running Conftest

Raw .tf files (fast, no credentials):

conftest test --parser hcl2 --policy policy/ $(git ls-files '*.tf')

Plan JSON (accurate, catches computed names; needs credentials and backend access):

terraform init -input=false
terraform plan -out=tfplan -input=false
terraform show -json tfplan > tfplan.json
conftest test tfplan.json --policy policy/

Example failure:

FAIL - main.tf - main - data.azurerm_resource_group.rg-project-eus-dev: region mismatch:
       label has {"eus"} but name 'project-weu-dev' has {"weu"}

2 tests, 1 passed, 0 warnings, 1 failure, 0 exceptions

Step 5: optional .conftest.yaml

policy: policy/
parser: hcl2
output: table

Step 6: CI

GitLab CI

naming-policy:hcl:
  stage: validate
  image: { name: docker.io/openpolicyagent/conftest:latest, entrypoint: [""] }
  script:
    - conftest verify --policy policy/
    - conftest test --parser hcl2 --policy policy/ $(find . -name '*.tf' -not -path '*/.terraform/*')

naming-policy:plan:
  stage: plan
  image: { name: docker.io/openpolicyagent/conftest:latest, entrypoint: [""] }
  needs: ["plan:dev"]            # job that produced tfplan.json as an artifact
  script:
    - conftest test tfplan.json --policy policy/

GitHub Actions

# .github/workflows/policy.yml
name: Terraform policy
on: [pull_request]
jobs:
  conftest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Conftest
        env:
          CONFTEST_VERSION: X.Y.Z   # pin
        run: |
          curl -sLO "https://github.com/open-policy-agent/conftest/releases/download/v${CONFTEST_VERSION}/conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz"
          tar xzf conftest_*.tar.gz conftest && sudo mv conftest /usr/local/bin/
      - run: conftest verify --policy policy/
      - run: conftest test --parser hcl2 --policy policy/ $(git ls-files '*.tf')

Pros and cons

✅ Expressive: complex rules are easy to read and compose
✅ Testable: conftest verify runs the Rego unit tests
✅ Plan mode catches names built from variables and locals
✅ Policies shareable via OCI bundles (conftest push/pull) or Git
❌ Rego has a learning curve
❌ Plan mode needs cloud credentials in CI
❌ HCL mode sees raw text, not evaluated values

Approach 2: pre-commit + custom script

A Python script wired up as a pre-commit hook. It parses .tf files with python-hcl2, extracts labels and name values for resource and data blocks, and blocks the commit on token mismatches.

Installation

pipx install pre-commit
# python-hcl2 is installed into the hook's own virtualenv via additional_dependencies
pre-commit install

Step 1: the validation script

Save as scripts/check_tf_naming.py:

#!/usr/bin/env python3
"""
check_tf_naming.py

Validates that the labels of selected resource and data blocks share the same
region and environment tokens as their `name` argument.

Usage:
    check_tf_naming.py [file1.tf file2.tf ...]
    With no arguments, checks every *.tf file under the current directory.
"""

from __future__ import annotations

import glob
import re
import sys
from pathlib import Path

try:
    import hcl2
except ImportError:
    print("ERROR: python-hcl2 is required: pip install python-hcl2")
    sys.exit(2)

CHECKED_TYPES = {"azurerm_resource_group"}

REGION_TOKENS = {
    "eus", "eus2", "wus", "wus2", "cus", "ncus", "scus",
    "weu", "neu", "uks", "ukw",
    "sea", "ea",
    "cac", "cae",
    "aue", "ause", "jpe", "jpw", "brs",
}

ENV_TOKENS = {
    "dev", "tst", "test", "stg", "stage", "staging", "uat", "qa",
    "prd", "prod", "production", "sbx", "sandbox", "int", "mgmt",
}

SPLIT = re.compile(r"[-._]")


def unquote(value):
    """Some python-hcl2 versions keep the quotes on labels and string values."""
    if isinstance(value, str) and len(value) >= 2 and value[0] == value[-1] == '"':
        return value[1:-1]
    return value


def tokens(text: str, vocab: set[str]) -> set[str]:
    return set(SPLIT.split(text.lower())) & vocab


def iter_blocks(config: dict):
    """Yield (kind, type, label, body) for resource and data blocks.

    python-hcl2 returns {"resource": [{"type": {"label": {...}}}, ...], "data": [...]}.
    """
    for kind in ("resource", "data"):
        entries = config.get(kind, [])
        if isinstance(entries, dict):
            entries = [entries]
        for entry in entries:
            for rtype, labels in entry.items():
                rtype = unquote(rtype)
                if rtype not in CHECKED_TYPES or not isinstance(labels, dict):
                    continue
                for label, body in labels.items():
                    if isinstance(body, list):          # tolerate list-wrapped bodies
                        body = body[0] if body else {}
                    if isinstance(body, dict):
                        yield kind, rtype, unquote(label), body


def check_file(path: str) -> list[str]:
    try:
        with Path(path).open(encoding="utf-8") as fh:
            config = hcl2.load(fh)
    except Exception as exc:  # noqa: BLE001 - report any parse failure
        return [f"{path}: failed to parse HCL: {exc}"]

    problems = []
    for kind, rtype, label, body in iter_blocks(config):
        name = unquote(body.get("name"))
        if not isinstance(name, str) or "${" in name:
            continue  # computed names can only be checked against a plan

        where = f"{path}: {kind}.{rtype}.{label}"
        lr, nr = tokens(label, REGION_TOKENS), tokens(name, REGION_TOKENS)
        le, ne = tokens(label, ENV_TOKENS), tokens(name, ENV_TOKENS)

        if lr != nr:
            problems.append(f"{where}\n    → region mismatch: label {sorted(lr) or 'none'} vs name '{name}' {sorted(nr) or 'none'}")
        if le != ne:
            problems.append(f"{where}\n    → environment mismatch: label {sorted(le) or 'none'} vs name '{name}' {sorted(ne) or 'none'}")
        if not lr and not nr:
            print(f"  WARN  {where}: no region token in label or name '{name}'")

    return problems


def main() -> int:
    files = sys.argv[1:] or [f for f in glob.glob("**/*.tf", recursive=True) if "/.terraform/" not in f]
    if not files:
        print("No .tf files found.")
        return 0

    problems = [p for f in files for p in check_file(f)]
    if problems:
        print("\n❌ Terraform naming violations:\n")
        print("\n\n".join(problems))
        print(f"\n{len(problems)} violation(s). Commit blocked.\n")
        return 1

    print(f"✅ Naming check passed ({len(files)} file(s)).")
    return 0


if __name__ == "__main__":
    sys.exit(main())
chmod +x scripts/check_tf_naming.py

Step 2: wire it into pre-commit

.pre-commit-config.yaml:

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.96.1                 # pin; `pre-commit autoupdate` to bump
    hooks:
      - id: terraform_fmt
      - id: terraform_validate

  - repo: local
    hooks:
      - id: check-tf-naming
        name: "Terraform: label/name token consistency"
        language: python
        entry: python scripts/check_tf_naming.py
        files: \.tf$
        additional_dependencies: [python-hcl2]
        pass_filenames: true

Step 3: running it

pre-commit run check-tf-naming                 # staged files (what the hook does)
pre-commit run check-tf-naming --all-files     # whole repo
python scripts/check_tf_naming.py modules/networking/*.tf

Example output:

❌ Terraform naming violations:

modules/networking/main.tf: data.azurerm_resource_group.rg-project-eus-dev
    → region mismatch: label ['eus'] vs name 'project-weu-dev' ['weu']

1 violation(s). Commit blocked.

Step 4: extending it

More resource types: add them to CHECKED_TYPES:

CHECKED_TYPES = {
    "azurerm_resource_group",
    "azurerm_virtual_network",
    "azurerm_subnet",
    "azurerm_storage_account",
    "azurerm_key_vault",
}

Strict segment positions (if your convention is always prefix-project-region-env):

def check_positions(label: str, name: str) -> list[str]:
    issues = []
    for text, source in ((label, "label"), (name, "name")):
        parts = text.split("-")
        if len(parts) < 2:
            issues.append(f"{source} '{text}' has fewer than 2 segments")
            continue
        if parts[-2] not in REGION_TOKENS:
            issues.append(f"{source} segment -2 '{parts[-2]}' is not a known region")
        if parts[-1] not in ENV_TOKENS:
            issues.append(f"{source} segment -1 '{parts[-1]}' is not a known environment")
    return issues

Step 5: CI

Run the same hooks in CI so --no-verify doesn't get around them:

# GitLab CI
pre-commit:
  stage: validate
  image: python:3.12
  variables:
    PRE_COMMIT_HOME: ${CI_PROJECT_DIR}/.cache/pre-commit
  cache:
    paths: [.cache/pre-commit]
  script:
    - pip install pre-commit
    - git fetch origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - pre-commit run --from-ref "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" --to-ref HEAD
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

The terraform_validate hook needs the terraform binary in the image; use an image that has both, or drop that hook from the CI job.

Step 6: bypassing (emergency only)

git commit --no-verify -m "docs: update README"

Bypasses only the local hook. CI still runs it.

Pros and cons

✅ Instant local feedback; no plan or credentials
✅ Plain Python; easy to extend
✅ Checks both resource and data blocks
❌ Static parse only: names built with ${...} are skipped
❌ Bypassable locally with --no-verify (not in CI)
❌ python-hcl2's output shape has changed between versions; pin it if the hook starts misbehaving

If you'd rather not depend on Python, the same logic is a small Rust binary with the hcl-rs crate, distributed like your other CLI tools and called from the hook with language: system.

Using both together

Developer workstation            CI pipeline
─────────────────────            ──────────────────────────────────────
pre-commit hook                  conftest (HCL mode)    conftest (plan mode)
  fast, no credentials             all files, every MR    resolved names
  blocks bad commits               can't be skipped       catches ${...} names
  1. pre-commit on every commit: fast feedback, no cloud auth.
  2. Conftest, HCL mode in CI on every MR: catches anything committed with --no-verify.
  3. Conftest, plan mode in CI after terraform plan: catches computed names.

Makefile

.PHONY: check-naming check-naming-plan policy-test

policy-test:
    conftest verify --policy policy/

check-naming: policy-test
    pre-commit run check-tf-naming --all-files
    conftest test --parser hcl2 --policy policy/ $$(git ls-files '*.tf')

check-naming-plan:
    terraform plan -out=tfplan -input=false
    terraform show -json tfplan > tfplan.json
    conftest test tfplan.json --policy policy/
    rm -f tfplan tfplan.json

Summary

Conftest + OPA pre-commit script
Best for CI enforcement, cross-resource rules Local developer feedback
Setup effort Medium Low
Accuracy High (plan) / medium (HCL) Medium (static)
Needs cloud auth Plan mode only Never
Extensibility Rego, OCI policy bundles Plain Python
Bypassable Not in CI Locally, with --no-verify

Both catch the eus/weu class of mismatch. Use the pre-commit script to shift feedback as far left as possible, and Conftest in CI as the gate that can't be bypassed.