This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentofu-kms-envelope-encryption-ephemeral-lease-standard

OpenTofu State KMS Envelope Encryption & Ephemeral Lease Standard

Enforces client-side envelope encryption for OpenTofu state files and execution plans using hardware-backed KMS customer-managed keys (CMK) alongside short-lived, workload-identity-federated runner leases. This eliminates plaintext state exposure in backend object storage and mitigates persistent credential theft risks across CI/CD execution pipelines.

Prohibited Anti-Pattern: Unencrypted State Backends Using Server-Side Fallbacks and Static IAM Pipeline Credentials

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTofu State KMS Envelope Encryption & Ephemeral Lease Standard - Enforces client-side envelope encryption for OpenTofu state files and execution plans using hardware-backed KMS customer-managed keys (CMK) alongside short-lived, workload-identity-federated runner leases. This eliminates plaintext state exposure in backend object storage and mitigates persistent credential theft risks across CI/CD execution pipelines.
globs: **/*.tofu, **/*.tf, **/*.tofu.json, .github/workflows/**/*.yml, .gitlab-ci.yml, infra/**/*.hcl
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentofu-kms-envelope-encryption-ephemeral-lease-standard"
---

# OpenTofu State KMS Envelope Encryption & Ephemeral Lease Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unencrypted State Backends Using Server-Side Fallbacks and Static IAM Pipeline Credentials

## System Constraints
You are a Principal Software Architect and Rules Author for AI Coding Agents enforcing OpenTofu State KMS Envelope Encryption & Ephemeral Lease Standard. OpenTofu state files and plan outputs inherently contain unmasked database passwords, private keys, cloud tokens, and sensitive infrastructure topologies. Relying solely on remote backend storage-level server-side encryption (SSE-S3/GCS default SSE) leaves state payloads vulnerable to bucket read compromises, cross-tenant bucket misconfigurations, and pipeline runners with broad storage access. You must mandate native OpenTofu client-side encryption blocks (`encryption {}`) using external KMS Key Management Service providers (AES-GCM-256) for all state and plan artifacts. Furthermore, you must reject static cloud access keys (AWS_ACCESS_KEY_ID, service account JSON files) in CI/CD pipelines, enforcing short-lived OIDC federated identity leases with maximum 1-hour durations strictly scoped to the repository and branch context.

## Strict Guidelines
- Engineers MUST ALWAYS configure OpenTofu native state encryption blocks (`terraform.encryption`) utilizing KMS Key Providers (`key_provider "aws_kms"` or `key_provider "gcp_kms"`) with PBKDF2/AES-GCM-256 for both `state` and `plan` stanzas.
- Engineers MUST set `enforced = true` on both `state` and `plan` blocks within the OpenTofu encryption configuration to reject unencrypted artifacts.
- Engineers MUST NOT persist long-lived CI/CD cloud credentials (e.g., static AWS Access Keys, permanent service account key pairs) in pipeline secrets or runner environments.
- CI/CD pipelines MUST acquire short-lived, ephemeral cloud session tokens using OIDC Workload Identity Federation (GitHub Actions OIDC, GitLab OIDC) with session duration constrained to maximum 3600 seconds (1 hour).
- KMS Key policies MUST enforce explicit cryptographic context checks (e.g., verifying `tofu-state-environment` and `repository` tags) to prevent unauthorized decryption by out-of-scope runners or roles.
- Engineers MUST configure remote object storage backends (S3, GCS, Azure Blob) with KMS Customer-Managed Keys (CMK) as a secondary defense layer in addition to OpenTofu client-side envelope encryption.

## Bad vs Good Implementations
### OpenTofu State Encryption & KMS Key Provider Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Backend-only encryption (SSE-S3/SSE-KMS at bucket level) leaves state payloads exposed to any IAM principal with s3:GetObject permissions on the bucket. OpenTofu generates intermediate plan files and state files that remain vulnerable in transit and cache without client-side envelope encryption.
```hcl
terraform {
  required_version = ">= 1.6.0"
  backend "s3" {
    bucket         = "corp-production-tfstate"
    key            = "networking/vpc.tfstate"
    region         = "us-east-1"
    # ANTI-PATTERN: Relies only on server-side S3 storage encryption without client-side envelope encryption
    encrypt        = true
  }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly utilizes OpenTofu 1.7+ client-side encryption. State and plan files are encrypted at the client level before network transmission using an envelope KMS data key via AES-GCM. Unencrypted states are strictly rejected via `enforced = true`.
```hcl
terraform {
  required_version = ">= 1.7.0"

  encryption {
    key_provider "aws_kms" "state_encryption_key" {
      kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d"
      region     = "us-east-1"
      key_spec   = "AES_256"
    }

    method "aes_gcm" "production_gcm" {
      keys = key_provider.aws_kms.state_encryption_key
    }

    state {
      method   = method.aes_gcm.production_gcm
      enforced = true
    }

    plan {
      method   = method.aes_gcm.production_gcm
      enforced = true
    }
  }

  backend "s3" {
    bucket         = "corp-production-tfstate"
    key            = "networking/vpc.tfstate"
    region         = "us-east-1"
    kms_key_id     = "arn:aws:kms:us-east-1:123456789012:key/a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d"
    encrypt        = true
  }
}
```

### CI/CD Ephemeral Runner Lease via OIDC vs Static IAM Secrets

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Static credentials stored in pipeline secrets are vulnerable to exfiltration, lack ephemeral lease constraints, and allow unauthorized out-of-band KMS access and state tampering.
```yaml
# .github/workflows/tofu-apply.yml
name: OpenTofu Deploy
on: [push]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      # ANTI-PATTERN: Using static, long-lived AWS secrets that cannot be audited or rotated per-execution
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1
```

#### Production Standard (Correct)
> **Standard**: Adopts OpenID Connect (OIDC) identity federation with an ephemeral session strictly restricted to 30 minutes (1800s). No static cloud credentials exist to leak or compromise.
```yaml
# .github/workflows/tofu-apply.yml
name: OpenTofu Deploy
on:
  push:
    branches: [main]
permissions:
  id-token: write
  contents: read
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      # SECURE: Ephemeral OIDC federation with short session expiry
      - name: Assume Ephemeral Cloud IAM Role via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/tofu-production-runner-role
          aws-region: us-east-1
          role-duration-seconds: 1800
          audience: sts.amazonaws.com
      - name: Setup OpenTofu
        uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: "1.7.2"
      - name: Plan and Apply
        run: |
          tofu init
          tofu plan -out=tfplan.binary
          tofu apply -auto-approve tfplan.binary
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTofu State KMS Envelope Encryption & Ephemeral Lease Standard

OpenTofu State KMS Envelope Encryption & Ephemeral Lease Standard defines an industrial-grade behavioral standard for devops engineering. Enforces client-side envelope encryption for OpenTofu state files and execution plans using hardware-backed KMS customer-managed keys (CMK) alongside short-lived, workload-identity-federated runner leases. This eliminates plaintext state exposure in backend object storage and mitigates persistent credential theft risks across CI/CD execution pipelines. 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: Unencrypted State Backends Using Server-Side Fallbacks and Static IAM Pipeline Credentials 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 DriftUnencrypted State Backends Using Server-Side Fallbacks and Static IAM Pipeline CredentialsCritical
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 OpenTofu native state encryption blocks (`terraform.encryption`) utilizing KMS Key Providers (`key_provider "aws_kms"` or `key_provider "gcp_kms"`) with PBKDF2/AES-GCM-256 for both `state` and `plan` stanzas.

Engineers MUST ALWAYS configure OpenTofu native state encryption blocks (`terraform.encryption`) utilizing KMS Key Providers (`key_provider "aws_kms"` or `key_provider "gcp_kms"`) with PBKDF2/AES-GCM-256 for both `state` and `plan` stanzas.

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 set `enforced = true` on both `state` and `plan` blocks within the OpenTofu encryption configuration to reject unencrypted artifacts.

Engineers MUST set `enforced = true` on both `state` and `plan` blocks within the OpenTofu encryption configuration to reject unencrypted artifacts.

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

Engineers MUST NOT persist long-lived CI/CD cloud credentials (e.g., static AWS Access Keys, permanent service account key pairs) in pipeline secrets or runner environments.

Engineers MUST NOT persist long-lived CI/CD cloud credentials (e.g., static AWS Access Keys, permanent service account key pairs) in pipeline secrets or runner environments.

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

CI/CD pipelines MUST acquire short-lived, ephemeral cloud session tokens using OIDC Workload Identity Federation (GitHub Actions OIDC, GitLab OIDC) with session duration constrained to maximum 3600 seconds (1 hour).

CI/CD pipelines MUST acquire short-lived, ephemeral cloud session tokens using OIDC Workload Identity Federation (GitHub Actions OIDC, GitLab OIDC) with session duration constrained to maximum 3600 seconds (1 hour).

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

KMS Key policies MUST enforce explicit cryptographic context checks (e.g., verifying `tofu-state-environment` and `repository` tags) to prevent unauthorized decryption by out-of-scope runners or roles.

KMS Key policies MUST enforce explicit cryptographic context checks (e.g., verifying `tofu-state-environment` and `repository` tags) to prevent unauthorized decryption by out-of-scope runners or roles.

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

Engineers MUST configure remote object storage backends (S3, GCS, Azure Blob) with KMS Customer-Managed Keys (CMK) as a secondary defense layer in addition to OpenTofu client-side envelope encryption.

Engineers MUST configure remote object storage backends (S3, GCS, Azure Blob) with KMS Customer-Managed Keys (CMK) as a secondary defense layer in addition to OpenTofu client-side envelope encryption.

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 State KMS Envelope Encryption & Ephemeral Lease Standard critical for AI coding assistants?

Enforces client-side envelope encryption for OpenTofu state files and execution plans using hardware-backed KMS customer-managed keys (CMK) alongside short-lived, workload-identity-federated runner leases. This eliminates plaintext state exposure in backend object storage and mitigates persistent credential theft risks across CI/CD execution pipelines. 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 (Unencrypted State Backends Using Server-Side Fallbacks and Static IAM Pipeline Credentials) 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