This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentofu-client-side-state-encryption-kms-barrier

OpenTofu 1.9 Client-Side State Envelope Encryption and KMS Key Rotation Barrier

Enforces mandatory client-side envelope encryption for OpenTofu state and plan files before persistence to remote backends using OpenTofu 1.9 native encryption blocks. Mandates AES-GCM encryption with managed hardware KMS key providers (AWS KMS, GCP KMS, Azure Key Vault, or HashiCorp Vault) and explicit fallback decryption barriers to guarantee uninterrupted cryptographic key rotation without plaintext leakage.

Prohibited Anti-Pattern: Persisting Plaintext or Backend-Only Encrypted State Without Client-Side KMS Envelope Barriers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTofu 1.9 Client-Side State Envelope Encryption and KMS Key Rotation Barrier - Enforces mandatory client-side envelope encryption for OpenTofu state and plan files before persistence to remote backends using OpenTofu 1.9 native encryption blocks. Mandates AES-GCM encryption with managed hardware KMS key providers (AWS KMS, GCP KMS, Azure Key Vault, or HashiCorp Vault) and explicit fallback decryption barriers to guarantee uninterrupted cryptographic key rotation without plaintext leakage.
globs: **/*.tofu, **/*.tf, **/encryption.tofu, **/backend.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentofu-client-side-state-encryption-kms-barrier"
---

# OpenTofu 1.9 Client-Side State Envelope Encryption and KMS Key Rotation Barrier

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Persisting Plaintext or Backend-Only Encrypted State Without Client-Side KMS Envelope Barriers

## System Constraints
You are a Principal Infrastructure Security Architect enforcing OpenTofu 1.9+ client-side state envelope encryption and cryptographic rotation standards. You must ensure that no infrastructure-as-code state or plan file is ever written to storage in plaintext or relying solely on cloud storage server-side encryption (SSE). You mandate native OpenTofu `encryption` blocks configured with authenticated symmetric cipher methods (AES-GCM), hardware-backed KMS key providers, and bidirectional fallback configurations enabling safe key rotation barriers.

## Strict Guidelines
- Engineers MUST ALWAYS declare an explicit `terraform { encryption { ... } }` block in root configurations when running OpenTofu 1.9+.
- Engineers MUST NOT rely solely on remote backend storage-tier encryption (such as AWS S3 bucket SSE-S3/SSE-KMS or GCS default encryption), as this exposes unencrypted credentials across backend network transit and to compromised storage IAM actors.
- The encryption configuration MUST define both `state` and `plan` targets with `enforced = true` to prevent unencrypted plan and state artifacts from leaking into CI/CD caches or remote backends.
- Code MUST employ envelope encryption via an authenticated cipher method (`method "aes_gcm"`) paired with hardware-backed KMS key providers (`aws_kms`, `gcp_kms`, `azure_keyvault`, or `pbkdf2` strictly for isolated non-prod testing).
- Key rotation barriers MUST be declared by including phased `fallback` blocks inside the `encryption.state` block, allowing previously encrypted states to be read and safely re-keyed to the active primary KMS key during subsequent applies.
- Components NEVER hardcode raw symmetric key bytes, base64 passphrases, or plaintext credentials inside configuration files; all cryptographic key materials MUST resolve via external KMS Key IDs or dynamic environment variables.

## Bad vs Good Implementations
### Configuring OpenTofu 1.9 Client-Side Envelope Encryption with AWS KMS and Key Rotation Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Backend-only encryption (SSE) encrypts data at rest on S3 disks, but the client generates and transmits plaintext state payloads across the wire and creates unencrypted local `.tfstate` and plan artifacts. If S3 permissions are misconfigured, any entity with s3:GetObject can read plain text database passwords and private keys.
```hcl
terraform {
  required_version = ">= 1.9.0"
  backend "s3" {
    bucket         = "corp-production-tfstate"
    key            = "networking/vpc.tfstate"
    region         = "us-east-1"
    # ANTI-PATTERN: Relying strictly on S3 Server-Side Encryption.
    # State arrives at the S3 API endpoint unencrypted over TLS and is vulnerable
    # to S3 bucket policy misconfigurations, storage IAM roles, and local disk leakage during execution.
    encrypt        = true
    kms_key_id     = "arn:aws:kms:us-east-1:123456789012:key/s3-storage-key"
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements OpenTofu 1.9 native client-side envelope encryption using AES-GCM backed by AWS KMS. Both state and plan files are cryptographically protected before leaving OpenTofu's runtime memory. The fallback block provides a cryptographic migration barrier, enabling seamless key rotation from 'retiring_kms' to 'primary_kms' without service interruption or decryption failures.
```hcl
terraform {
  required_version = ">= 1.9.0"

  backend "s3" {
    bucket         = "corp-production-tfstate"
    key            = "networking/vpc.tfstate"
    region         = "us-east-1"
    encrypt        = true
  }

  encryption {
    # Primary KMS Key Provider for Active Writes
    key_provider "aws_kms" "primary_kms" {
      kms_key_arn = "arn:aws:kms:us-east-1:123456789012:key/active-state-key-2025"
      region      = "us-east-1"
    }

    # Secondary KMS Key Provider to support Non-Breaking Key Rotation
    key_provider "aws_kms" "retiring_kms" {
      kms_key_arn = "arn:aws:kms:us-east-1:123456789012:key/legacy-state-key-2024"
      region      = "us-east-1"
    }

    # Authenticated AEAD Cipher Methods
    method "aes_gcm" "primary" {
      keys = key_provider.aws_kms.primary_kms
    }

    method "aes_gcm" "retiring" {
      keys = key_provider.aws_kms.retiring_kms
    }

    # Enforce Client-Side State Encryption with Rotation Fallback
    state {
      method   = method.aes_gcm.primary
      enforced = true

      fallback {
        method = method.aes_gcm.retiring
      }
    }

    # Enforce Client-Side Plan Encryption
    plan {
      method   = method.aes_gcm.primary
      enforced = true
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTofu 1.9 Client-Side State Envelope Encryption and KMS Key Rotation Barrier

OpenTofu 1.9 Client-Side State Envelope Encryption and KMS Key Rotation Barrier defines an industrial-grade behavioral standard for devops engineering. Enforces mandatory client-side envelope encryption for OpenTofu state and plan files before persistence to remote backends using OpenTofu 1.9 native encryption blocks. Mandates AES-GCM encryption with managed hardware KMS key providers (AWS KMS, GCP KMS, Azure Key Vault, or HashiCorp Vault) and explicit fallback decryption barriers to guarantee uninterrupted cryptographic key rotation without plaintext leakage. 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: Persisting Plaintext or Backend-Only Encrypted State Without Client-Side KMS Envelope Barriers 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 DriftPersisting Plaintext or Backend-Only Encrypted State Without Client-Side KMS Envelope BarriersCritical
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 declare an explicit `terraform { encryption { ... } }` block in root configurations when running OpenTofu 1.9+.

Engineers MUST ALWAYS declare an explicit `terraform { encryption { ... } }` block in root configurations when running OpenTofu 1.9+.

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 rely solely on remote backend storage-tier encryption (such as AWS S3 bucket SSE-S3/SSE-KMS or GCS default encryption), as this exposes unencrypted credentials across backend network transit and to compromised storage IAM actors.

Engineers MUST NOT rely solely on remote backend storage-tier encryption (such as AWS S3 bucket SSE-S3/SSE-KMS or GCS default encryption), as this exposes unencrypted credentials across backend network transit and to compromised storage IAM actors.

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

The encryption configuration MUST define both `state` and `plan` targets with `enforced = true` to prevent unencrypted plan and state artifacts from leaking into CI/CD caches or remote backends.

The encryption configuration MUST define both `state` and `plan` targets with `enforced = true` to prevent unencrypted plan and state artifacts from leaking into CI/CD caches or remote backends.

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

Code MUST employ envelope encryption via an authenticated cipher method (`method "aes_gcm"`) paired with hardware-backed KMS key providers (`aws_kms`, `gcp_kms`, `azure_keyvault`, or `pbkdf2` strictly for isolated non-prod testing).

Code MUST employ envelope encryption via an authenticated cipher method (`method "aes_gcm"`) paired with hardware-backed KMS key providers (`aws_kms`, `gcp_kms`, `azure_keyvault`, or `pbkdf2` strictly for isolated non-prod testing).

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

Key rotation barriers MUST be declared by including phased `fallback` blocks inside the `encryption.state` block, allowing previously encrypted states to be read and safely re-keyed to the active primary KMS key during subsequent applies.

Key rotation barriers MUST be declared by including phased `fallback` blocks inside the `encryption.state` block, allowing previously encrypted states to be read and safely re-keyed to the active primary KMS key during subsequent applies.

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.
6

Components NEVER hardcode raw symmetric key bytes, base64 passphrases, or plaintext credentials inside configuration files

Components NEVER hardcode raw symmetric key bytes, base64 passphrases, or plaintext credentials inside configuration files; all cryptographic key materials MUST resolve via external KMS Key IDs or dynamic environment variables.

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 1.9 Client-Side State Envelope Encryption and KMS Key Rotation Barrier critical for AI coding assistants?

Enforces mandatory client-side envelope encryption for OpenTofu state and plan files before persistence to remote backends using OpenTofu 1.9 native encryption blocks. Mandates AES-GCM encryption with managed hardware KMS key providers (AWS KMS, GCP KMS, Azure Key Vault, or HashiCorp Vault) and explicit fallback decryption barriers to guarantee uninterrupted cryptographic key rotation without plaintext leakage. 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 (Persisting Plaintext or Backend-Only Encrypted State Without Client-Side KMS Envelope Barriers) 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