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.
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
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
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.
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---
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.Keep SKILL.md instructions concise; agent context windows retain compact SOP steps much more effectively than long narrative documents.
Ensure fs_write permissions remain restricted to 'workspace' to prevent the agent from accidentally overwriting system-wide ~/.aws credentials.
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.
export AWS_REGION="us-east-1"
export AWS_PROFILE="terraform-deployer"
aws sts get-caller-identityresource "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"
}
}Rely on AWS IAM role delegation so that Codex or Claude Code operates completely without long-lived static credentials.
Failing to set force_destroy = false on the S3 bucket can allow careless destructive operations to wipe remote infrastructure state history.
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.
# In Claude Code CLI or Codex Chat:
claude "setup terraform remote s3 backend with dynamodb state locking and migrate current local state"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
}
}Explicitly include the key hierarchy (e.g., env/layer/terraform.tfstate) in the prompt to prevent root-level clutter in the S3 bucket.
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.
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.
terraform fmt -check && terraform validate && terraform init -migrate-state#!/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."Inspect git status immediately to confirm terraform.tfstate is untracked and excluded via .gitignore.
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
“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”
Runtime Troubleshooting & Failure Modes
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.
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-1Root Cause: A previous agent process terminated abruptly while holding the distributed lock, or another developer or CI runner is executing terraform apply concurrently.
terraform force-unlock <LOCK_ID> # Verify no active CI runs exist before executingFrequently 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.