This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentofu-state-lock-ephemeral-quarantine-guardrail

OpenTofu Cryptographic State Locking & Ephemeral Workspace Drift Quarantine

Guarantees deterministic declarative infrastructure provisioning by enforcing cryptographically validated state locks and continuous reconciliation isolation across parallel CI/CD lanes. Restricts write operations to ephemeral run-scoped workspaces governed by deterministic lock lease timeouts, and immediately quarantines any execution lane detecting unmanaged out-of-band state mutation.

Prohibited Anti-Pattern: Parallel Unlocked Execution and Unquarantined In-Place Apply on Drifted Shared State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTofu Cryptographic State Locking & Ephemeral Workspace Drift Quarantine - Guarantees deterministic declarative infrastructure provisioning by enforcing cryptographically validated state locks and continuous reconciliation isolation across parallel CI/CD lanes. Restricts write operations to ephemeral run-scoped workspaces governed by deterministic lock lease timeouts, and immediately quarantines any execution lane detecting unmanaged out-of-band state mutation.
globs: **/*.tf, **/*.tofu, **/*.tfvars, .github/workflows/**/*.{yml,yaml}, .gitlab-ci.yml, infra/**/*.{ts,js,py,sh}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentofu-state-lock-ephemeral-quarantine-guardrail"
---

# OpenTofu Cryptographic State Locking & Ephemeral Workspace Drift Quarantine

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Parallel Unlocked Execution and Unquarantined In-Place Apply on Drifted Shared State

## System Constraints
You are a Principal DevOps and Infrastructure Security Architect enforcing OpenTofu cryptographic state locking and ephemeral workspace drift quarantine. Mandate zero-trust state mutations, strict lease timeouts, immutable S3/DynamoDB or Consul backends with client-side KMS validation, and automated lane halting whenever drift or lock contention is detected.

## Strict Guidelines
- Engineers MUST ALWAYS configure robust backend locking mechanisms (e.g., AWS DynamoDB with encryption-at-rest or native OpenTofu encrypted state) with explicit `lock_timeout` parameters.
- Engineers MUST NOT allow automated CI/CD pipelines to execute `tofu apply` without acquiring a cryptographically secured lock and asserting workspace idempotency.
- CI/CD workflows MUST create isolated, ephemeral workspace contexts for pull requests and enforce read-only speculative plans (`tofu plan -detailed-exitcode`).
- Pipelines MUST immediately trigger a drift quarantine failure and halt downstream deployment if `detailed-exitcode` returns `2` (drift/pending changes) during reconciliation phases.
- Engineers MUST NEVER execute `tofu force-unlock` programmatically without manual multi-party cryptographic authorization.

## Bad vs Good Implementations
### Enforcing State Locking and Encryption Backend Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the `dynamodb_table` (or OpenTofu state locking mechanism) allows concurrent execution pipelines to write to the state simultaneously, causing race conditions, split-brain states, and corrupted infrastructure tracking.
```hcl
terraform {
  # VIOLATION: Insecure backend lacking explicit state locking table, client-side encryption, and strict version constraints
  backend "s3" {
    bucket = "corp-tofu-state"
    key    = "prod/terraform.tfstate"
    region = "us-east-1"
  }
}
```

#### Production Standard (Correct)
> **Standard**: Specifies DynamoDB for distributed state locking and leases, coupled with KMS client-side state encryption and transit encryption, preventing race conditions and unauthorized tampering.
```hcl
terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  # COMPLIANT: Enforces state locking via DynamoDB, encryption at rest, and TLS transport
  backend "s3" {
    bucket         = "corp-tofu-state-secure"
    key            = "prod/tofu.tfstate"
    region         = "us-east-1"
    encrypt        = true
    kms_key_id     = "arn:aws:kms:us-east-1:123456789012:key/tofu-state-key"
    dynamodb_table = "corp-tofu-state-locks"
  }
}
```

### Ephemeral Workspace Drift Detection and Quarantine Execution in CI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating shared workspaces directly without acquiring explicit timed locks, checking for existing drift, or creating an ephemeral plan causes blind overwrites and untracked changes across concurrent pull requests.
```bash
#!/usr/bin/env bash
# VIOLATION: Shared workspace mutation with unchecked lock collisions and blind apply
tofu workspace select production
tofu apply -auto-approve
```

#### Production Standard (Correct)
> **Standard**: Employs `-detailed-exitcode` with an explicit `-lock-timeout=600s` on plan generation. Detects out-of-band state divergence (exit code 2) and quarantines drift during periodic reconciliation.
```bash
#!/usr/bin/env bash
set -euo pipefail

# COMPLIANT: Ephemeral workspace isolation, timed lock acquisition, and drift quarantine
readonly RUN_ID="lane-${CI_PIPELINE_ID:-$(date +%s)}"
readonly PLAN_FILE="/tmp/tofu-plan-${RUN_ID}.tfplan"

tofu init -input=false

# Quarantine Check: Execute speculative plan with deterministic 10-minute lock timeout
echo "[INFO] Executing speculative plan with drift inspection..."
set +e
tofu plan \
  -lock=true \
  -lock-timeout=600s \
  -detailed-exitcode \
  -out="${PLAN_FILE}"
EXIT_CODE=$?
set -e

if [ "${EXIT_CODE}" -eq 2 ]; then
  echo "[WARN] Infrastructure drift detected or changes pending."
  if [ "${IS_RECONCILIATION_CRON:-false}" = "true" ]; then
    echo "[ALERT] Unmanaged drift quarantined! Halting pipeline to prevent destructive convergence."
    exit 2
  fi
elif [ "${EXIT_CODE}" -ne 0 ]; then
  echo "[ERROR] Lock acquisition failed or backend inaccessible. Aborting."
  exit "${EXIT_CODE}"
fi
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTofu Cryptographic State Locking & Ephemeral Workspace Drift Quarantine

OpenTofu Cryptographic State Locking & Ephemeral Workspace Drift Quarantine defines an industrial-grade behavioral standard for devops engineering. Guarantees deterministic declarative infrastructure provisioning by enforcing cryptographically validated state locks and continuous reconciliation isolation across parallel CI/CD lanes. Restricts write operations to ephemeral run-scoped workspaces governed by deterministic lock lease timeouts, and immediately quarantines any execution lane detecting unmanaged out-of-band state mutation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Parallel Unlocked Execution and Unquarantined In-Place Apply on Drifted Shared State Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftParallel Unlocked Execution and Unquarantined In-Place Apply on Drifted Shared StateCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS configure robust backend locking mechanisms (e.g., AWS DynamoDB with encryption-at-rest or native OpenTofu encrypted state) with explicit `lock_timeout` parameters.

Engineers MUST ALWAYS configure robust backend locking mechanisms (e.g., AWS DynamoDB with encryption-at-rest or native OpenTofu encrypted state) with explicit `lock_timeout` parameters.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT allow automated CI/CD pipelines to execute `tofu apply` without acquiring a cryptographically secured lock and asserting workspace idempotency.

Engineers MUST NOT allow automated CI/CD pipelines to execute `tofu apply` without acquiring a cryptographically secured lock and asserting workspace idempotency.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

CI/CD workflows MUST create isolated, ephemeral workspace contexts for pull requests and enforce read-only speculative plans (`tofu plan -detailed-exitcode`).

CI/CD workflows MUST create isolated, ephemeral workspace contexts for pull requests and enforce read-only speculative plans (`tofu plan -detailed-exitcode`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Pipelines MUST immediately trigger a drift quarantine failure and halt downstream deployment if `detailed-exitcode` returns `2` (drift/pending changes) during reconciliation phases.

Pipelines MUST immediately trigger a drift quarantine failure and halt downstream deployment if `detailed-exitcode` returns `2` (drift/pending changes) during reconciliation phases.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Engineers MUST NEVER execute `tofu force-unlock` programmatically without manual multi-party cryptographic authorization.

Engineers MUST NEVER execute `tofu force-unlock` programmatically without manual multi-party cryptographic authorization.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenTofu Cryptographic State Locking & Ephemeral Workspace Drift Quarantine critical for AI coding assistants?

Guarantees deterministic declarative infrastructure provisioning by enforcing cryptographically validated state locks and continuous reconciliation isolation across parallel CI/CD lanes. Restricts write operations to ephemeral run-scoped workspaces governed by deterministic lock lease timeouts, and immediately quarantines any execution lane detecting unmanaged out-of-band state mutation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Parallel Unlocked Execution and Unquarantined In-Place Apply on Drifted Shared State) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenTofu