Verified SOP & TutorialAudited Score 98/100

The Complete Production SOP: How to Deploy and Run Terraform Remote S3 State & DynamoDB State Locking in Autonomous AI Agents

Step-by-step SOP to install and run Terraform Remote S3 State & DynamoDB State Locking in Codex, Claude Code, and Cursor. Verified prompts and runtimes.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

Technical Overview & Architectural Context

Autonomous coding agents like Codex, Claude Code, and Cursor frequently blunder when handling cloud infrastructure state. Without strict procedural guardrails, LLMs commonly commit raw terraform.tfstate files containing unencrypted secrets directly to version control, configure S3 buckets lacking server-side encryption or bucket versioning, or generate DynamoDB tables with incorrect partition keys—leading to immediate terraform init runtime failures and corrupted distributed locks. The terraform-state-s3-dynamodb skill enforces an ironclad, deterministic standard operating procedure. It restricts agent file modifications strictly to workspace infrastructure manifests, forces validation of S3 public access blocks, enforces strict LockID attribute naming on the DynamoDB locking table, and automates state migration via terraform init -migrate-state with zero secret leakage.

Prerequisites & Environment Requirements

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with skill discovery enabled
Terraform CLI v1.5+ or OpenTofu v1.6+ installed in path
AWS CLI v2 configured with IAM credentials granting S3 and DynamoDB management permissions

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install terraform-state-s3-dynamodb in cursor ide#claude code terraform-state-s3-dynamodb rules#codex desktop terraform-state-s3-dynamodb setup tutorial#how to fix terraform-state-s3-dynamodb agent execution error#deterministic devops agent SOP#terraform-state-s3-dynamodb sandbox permissions and security score#terraform remote s3 backend dynamodb lockid error fix

Step-by-Step Execution Playbook

1

Local Environment Setup & SKILL.md Mounting

Create the local skill manifest directory and inject verified procedural rules into the agent runtime path.

Autonomous runtimes parse directory trees under ~/.agents/skills or workspace-level .agents/skills. Placing the SKILL.md manifest into this hierarchy registers the trigger matches ('setup terraform remote s3 backend', 'migrate terraform state') so that Codex or Claude Code automatically selects this SOP when Terraform backend operations are requested.

Terminal Command
mkdir -p ~/.agents/skills/terraform-state-s3-dynamodb && curl -fsSL https://askills.dev/api/skills/terraform-state-s3-dynamodb/raw -o ~/.agents/skills/terraform-state-s3-dynamodb/SKILL.md
~/.agents/skills/terraform-state-s3-dynamodb/SKILL.md
---
name: "terraform-state-s3-dynamodb"
description: "Configure secure remote state storage with server-side encryption and distributed locking."
metadata:
  author: "HashiCorp"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "setup terraform remote s3 backend"
  - "enable dynamodb state locking terraform"
  - "migrate terraform state"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# Terraform Remote S3 State & DynamoDB State Locking SOP
1. S3 bucket must enforce AES256 or aws:kms encryption, versioning, and public_access_block.
2. DynamoDB lock table must have hash_key = "LockID" of type String.
3. backend.tf must declare backend "s3" with bucket, key, region, and dynamodb_table.
4. Migration must use terraform init -migrate-state.
Production Pro-Tip

Keep SKILL.md instructions concise; agent context windows retain compact SOP steps much more effectively than long narrative documents.

Sandbox Gotcha

Ensure fs_write permissions remain restricted to 'workspace' to prevent the agent from accidentally overwriting system-wide ~/.aws credentials.

2

Environment Secrets & AWS IAM Boundary Setup

Expose required AWS parameters securely without injecting static secret keys into conversational context.

Autonomous agents must never ingest plaintext AWS_SECRET_ACCESS_KEY values inside prompt contexts. Rely on environment variable pass-through or AWS IAM role assumption via AWS_PROFILE, verifying environment variable readiness before triggering execution.

Terminal Command
export AWS_REGION="us-east-1" export AWS_PROFILE="terraform-deployer" aws sts get-caller-identity
backend-bootstrap/main.tf
resource "aws_s3_bucket" "tf_state" {
  bucket        = "prod-corp-tfstate-${data.aws_caller_identity.current.account_id}"
  force_destroy = false
}

resource "aws_s3_bucket_versioning" "versioning" {
  bucket = aws_s3_bucket.tf_state.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "encryption" {
  bucket = aws_s3_bucket.tf_state.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_dynamodb_table" "tf_locks" {
  name         = "terraform-state-locks"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"
  attribute {
    name = "LockID"
    type = "S"
  }
}
Production Pro-Tip

Rely on AWS IAM role delegation so that Codex or Claude Code operates completely without long-lived static credentials.

Sandbox Gotcha

Failing to set force_destroy = false on the S3 bucket can allow careless destructive operations to wipe remote infrastructure state history.

3

Intent Matching & Backend Trigger Invocation

Dispatch deterministic execution prompts matching configured SKILL.md trigger phrases.

Provide the agent with a targeted request referencing S3 backend setup and DynamoDB state locking. The runtime matches trigger patterns and adheres to the SOP constraints during code generation and state migration.

Terminal Command
# In Claude Code CLI or Codex Chat: claude "setup terraform remote s3 backend with dynamodb state locking and migrate current local state"
backend.tf
terraform {
  required_version = ">= 1.5.0"
  backend "s3" {
    bucket         = "prod-corp-tfstate-123456789012"
    key            = "production/vpc/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-state-locks"
    encrypt        = true
  }
}
Production Pro-Tip

Explicitly include the key hierarchy (e.g., env/layer/terraform.tfstate) in the prompt to prevent root-level clutter in the S3 bucket.

Sandbox Gotcha

Running terraform init without the -migrate-state flag when local state exists will fail with a state lock/mismatch prompt that hangs non-interactive agents.

4

Verification, Linting & Output Quality Gate

Run structural validation, terraform formatting, and backend migration verification.

Once the agent completes file modifications, trigger automated verification. Terraform validates syntax, ensures locks can be acquired, and checks that state is removed locally.

Terminal Command
terraform fmt -check && terraform validate && terraform init -migrate-state
verify-backend.sh
#!/usr/bin/env bash
set -euo pipefail

echo "Validating Terraform configurations..."
terraform fmt -check
terraform validate

echo "Checking for residual uncommitted local state..."
if [ -f "terraform.tfstate" ]; then
  echo "ERROR: Local state file still exists! Ensure migration completed successfully." >&2
  exit 1
fi
echo "Remote S3 and DynamoDB locking verification passed."
Production Pro-Tip

Inspect git status immediately to confirm terraform.tfstate is untracked and excluded via .gitignore.

Sandbox Gotcha

Do not delete terraform.tfstate.backup prematurely until terraform state list is verified against the remote backend.

Real-World Scenario: Migrating Core Networking Terraform from Local State to Remote S3 & DynamoDB

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“setup terraform remote s3 backend for our core VPC stack using bucket prod-corp-tfstate-123456789012, table terraform-state-locks in us-east-1, and migrate terraform state”

Deterministic Agent Verification Pipeline:
Inspect current workspace to locate main.tf, variables.tf, and local terraform.tfstate.
Create or update backend.tf declaring backend 's3' with encrypt = true, bucket, key, region, and dynamodb_table parameters.
Ensure .gitignore contains *.tfstate, *.tfstate.*, and .terraform/ to prevent accidental secret leaks.
Execute terraform init -migrate-state non-interactively and verify the successful state relocation into the S3 bucket.
Confirm that distributed locking via DynamoDB LockID table operates correctly without dangling locks.

Runtime Troubleshooting & Failure Modes

Error: Error: DynamoDB table not found or missing LockID attribute

Root Cause: The agent provisioned the DynamoDB table with a custom primary key or without the strict case-sensitive primary key 'LockID' of type String required by HashiCorp's S3 backend provider.

Resolution Command / Fix:
aws dynamodb create-table --table-name terraform-state-locks --attribute-definitions AttributeName=LockID,AttributeType=S --key-schema AttributeName=LockID,KeyType=HASH --billing-mode PAY_PER_REQUEST --region us-east-1
Error: Error: Error acquiring the state lock: ConditionalCheckFailedException

Root Cause: A previous agent process terminated abruptly while holding the distributed lock, or another developer or CI runner is executing terraform apply concurrently.

Resolution Command / Fix:
terraform force-unlock <LOCK_ID> # Verify no active CI runs exist before executing

Frequently Asked Questions (Terraform Remote S3 State & DynamoDB State Locking SOP)

Q:Can I use Terraform Remote S3 State & DynamoDB State Locking across Codex, Claude Code, and Cursor simultaneously?

Yes. The skill conforms to the universal SKILL.md specification. When placed in ~/.agents/skills or the root of your project workspace, it is recognized natively across Codex, Claude Code, Cursor, and Windsurf.

Q:How does Terraform Remote S3 State & DynamoDB State Locking prevent context window overflow during long agent sessions?

The skill provides concise SOP directives instead of sprawling guides. It instructs the agent to inspect only backend.tf, .gitignore, and migration outputs rather than loading hundreds of lines of existing infrastructure resources into the context window.

Q:Does this skill require escalated root or container permissions?

No. The skill runs with fs_read enabled, fs_write scoped to the workspace directory, shell_exec set to false, and net_access set to false. All AWS operations are performed through standard local CLI credentials without elevated system access.

Ready to equip your autonomous agent with Terraform Remote S3 State & DynamoDB State Locking?

Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.

Get 1-Click Install Spec