Inferensys

Prompt

Terraform State Lock Conflict Retry Prompt Template

A practical prompt playbook for using Terraform State Lock Conflict Retry Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the operational context, required inputs, and safety boundaries for using the Terraform state lock conflict retry prompt in production infrastructure workflows.

This prompt is for infrastructure engineers and SRE teams who need an AI-assisted decision when a Terraform plan or apply fails with a state lock error. Instead of manually inspecting lock metadata and guessing whether to retry or force-unlock, this prompt produces a structured, safety-checked decision. Use it inside CI/CD pipelines, operator chatbots, or runbook automation where a lock conflict requires fast, auditable resolution. The prompt assumes you already have the raw error output and lock metadata available. It does not replace Terraform's native locking mechanism or your team's change management policy.

The ideal user has access to the full Terraform error output, the lock ID, lock creation timestamp, lock holder identity (user, CI runner, or machine identity), and the operation that triggered the conflict. The prompt requires these inputs to assess collision risk: Is the lock holder still active? Is the conflicting operation a plan (read-only) or an apply (mutating)? Has the lock exceeded a reasonable timeout threshold? Without this context, the model cannot distinguish between a stale lock that is safe to force-unlock and an active operation that must be allowed to complete. The prompt also requires a risk tolerance parameter—low for production state files, higher for ephemeral development environments—to calibrate the decision threshold.

Do not use this prompt when the lock holder is unknown, when the state backend is corrupted, or when multiple team members are actively applying changes to the same workspace. In those scenarios, automated decisions risk state file corruption or split-brain conditions. The prompt is also inappropriate for state files stored in backends without locking support, where the error may indicate a different class of problem. Always pair this prompt with a human-approval gate for production state files, and ensure your harness logs the full decision rationale for post-incident review. The next section provides the copy-ready prompt template you can adapt to your specific Terraform backend and operational policies.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Terraform State Lock Conflict Retry Prompt Template works, where it does not, and what you must provide before using it in a production harness.

01

Good Fit: CI/CD Pipeline Lock Contention

Use when: A CI/CD runner encounters a state lock held by a previous run, a concurrent plan, or a manual operation. The prompt helps decide whether to wait, force-unlock, or escalate. Guardrail: Always verify the lock holder's identity and operation status before issuing a force-unlock instruction.

02

Bad Fit: State File Corruption

Avoid when: The state file itself is corrupted, contains missing resources, or has been manually edited. This prompt assumes a healthy state file with a lock contention issue. Guardrail: Route state integrity failures to a manual recovery runbook before invoking any retry logic.

03

Required Inputs: Lock Metadata and Operation Context

Must provide: The full terraform plan or apply error output, lock ID, lock holder identity (user, pipeline, or IP), current operation type, and lock acquisition timestamp. Guardrail: Missing lock holder identity prevents safe force-unlock decisions; block the retry path until the holder is identified.

04

Operational Risk: Accidental State Corruption

Risk: A premature force-unlock while another operation is actively writing state can corrupt the state file and cause resource drift. Guardrail: Require a confirmation step with lock holder verification and a state backup before any force-unlock action is executed.

05

Operational Risk: Infinite Retry Loops

Risk: Repeatedly retrying a lock acquisition without backoff can exacerbate contention and waste CI/CD minutes. Guardrail: Enforce a retry budget with exponential backoff and a maximum wait time. Escalate to a human operator after the budget is exhausted.

06

Not a Replacement for Lock Management Tooling

Avoid when: You need a persistent lock management service, distributed locking, or state backend migration. This prompt is a decision aid for a single contention event. Guardrail: Use backend-native features like DynamoDB lock tables or GCS object versioning for systemic lock management.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that produces a retry-or-force-unlock decision for Terraform state lock conflicts, including lock holder identification and state integrity verification.

This prompt template is designed to be pasted directly into your AI harness when a Terraform operation fails due to a state lock conflict. It instructs the model to act as an infrastructure reliability engineer, analyzing the provided error context, lock metadata, and operation details to produce a safe, structured decision. The output is a strict JSON schema suitable for programmatic consumption by a retry orchestrator or a human approval queue. Replace every square-bracket placeholder with real data from your CI/CD pipeline or operator console before sending the request.

text
You are an infrastructure reliability engineer diagnosing a Terraform state lock conflict.
Your task is to analyze the provided error context and produce a structured decision.

# INPUT
- Error Output: [TERRAFORM_ERROR_OUTPUT]
- Lock ID: [LOCK_ID]
- Lock Holder Information: [LOCK_HOLDER_INFO]
- Current Operation: [CURRENT_OPERATION]
- Operation Timestamp: [OPERATION_TIMESTAMP]
- State File Path: [STATE_FILE_PATH]
- Recent State Changes: [RECENT_STATE_CHANGES]

# CONSTRAINTS
- Do not recommend `terraform force-unlock` unless the lock holder is confirmed dead, the operation has timed out beyond a safe threshold, and no conflicting writes are in progress.
- If the lock holder is active, recommend a retry with exponential backoff.
- Always verify state integrity before suggesting a force-unlock.
- If the state file shows signs of corruption or a partial write, escalate for manual recovery.

# OUTPUT_SCHEMA
Return a single JSON object with the following fields:
{
  "decision": "retry" | "force_unlock" | "escalate",
  "confidence": "high" | "medium" | "low",
  "reasoning": "A concise explanation of the decision.",
  "lock_holder_status": "active" | "dead" | "unknown",
  "collision_detected": true | false,
  "state_integrity_check": "clean" | "suspicious" | "corrupted",
  "recommended_action": "A specific next step, including backoff timing or escalation contact.",
  "risk_summary": "A brief description of the primary risk if the recommended action is taken."
}

To adapt this template, ensure the [TERRAFORM_ERROR_OUTPUT] includes the full, raw error message, as the model uses specific keywords like 'lock', 'timeout', and 'ID' to parse the situation. The [LOCK_HOLDER_INFO] should be populated by querying your backend (e.g., DynamoDB, GCS, or a Terraform Cloud API call) to determine if the holder process is still alive. If you cannot determine the holder's status, set the value to 'unknown' and the model will default to a safer retry posture. After receiving the JSON output, your application harness must validate the schema before acting on the decision field, especially for destructive force_unlock actions which should always require explicit human approval in a production environment.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Terraform State Lock Conflict Retry Prompt needs to produce a safe retry-or-force-unlock decision.

PlaceholderPurposeExampleValidation Notes

[LOCK_ERROR_OUTPUT]

Raw error text from the Terraform CLI or API response containing the lock conflict details.

Error: Error acquiring the state lock state blob is already locked Lock Info: ID: 8b1f2a3c-... Path: terraform.tfstate Operation: OperationTypeApply Who: user@host...

Must be a non-empty string. Validate that it contains a substring like 'already locked' or 'state lock'. If null or empty, the prompt should not be invoked.

[LOCK_HOLDER_ID]

The unique identifier of the entity holding the lock, extracted from the error output.

8b1f2a3c-4d5e-6f7a-8b9c-0d1e2f3a4b5c

Must be a non-empty string. Validate against a UUID regex pattern. If unparseable from [LOCK_ERROR_OUTPUT], set to 'unknown' and flag for manual review.

[LOCK_OPERATION]

The type of operation that currently holds the lock, extracted from the error output.

OperationTypeApply

Must be a non-empty string. Validate against a known set of Terraform operations: 'OperationTypeApply', 'OperationTypePlan', 'OperationTypeDestroy'. If unknown, set to 'UnknownOperation' and escalate.

[LOCK_HOLDER_INFO]

Human-readable identifier for who or what holds the lock, extracted from the error output.

user@workstation-hostname

Must be a non-empty string. Used for manual correlation. If unparseable, set to 'unknown'.

[PIPELINE_RUN_ID]

The unique identifier of the current CI/CD pipeline run or automation process requesting the lock.

pipeline-9876-build-123

Must be a non-empty string. Validate against an expected pipeline ID format (e.g., 'pipeline-\d+-build-\d+'). If not in an automated context, set to 'manual-run'.

[RETRY_COUNT]

The number of times a retry has already been attempted for this specific lock acquisition.

2

Must be a string representation of an integer >= 0. Validate by parsing to an integer. If the count exceeds a configured [MAX_RETRIES], the prompt should recommend escalation, not another retry.

[MAX_RETRIES]

The maximum number of retries allowed before forcing an escalation or a force-unlock decision.

3

Must be a string representation of an integer > 0. Validate by parsing to an integer. This is a policy parameter, not a dynamic input.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Terraform state lock conflict retry prompt into a CI/CD or operator workflow with validation, safety gates, and logging.

This prompt is designed to be invoked by an automation harness—typically a CI/CD pipeline, a runbook automation tool, or an operator CLI—immediately after a terraform apply or terraform plan command exits with a state lock acquisition error. The harness must capture the full stderr output, the current Terraform workspace, the lock ID if present, and any available lock metadata from terraform force-unlock -force-unlock <LOCK_ID> dry-run output. Do not call this prompt in isolation without the raw error context; the model needs the exact lock error message, the operation that was attempted, and the lock holder information to make a safe retry-or-force-unlock decision.

The implementation should follow a strict pre- and post-processing contract. Before calling the model, validate that the captured error output contains a recognizable state lock conflict string (e.g., Error acquiring the state lock, state blob is already locked). If the error does not match, route to a generic infrastructure error handler instead. After receiving the model's response, parse the structured decision object and enforce a hard gate: if the decision is force_unlock, the harness must require an explicit human approval step (e.g., a Slack notification with a reaction-based confirmation or a CI pipeline manual approval job) before executing terraform force-unlock. Log the full prompt, response, lock ID, and the human approver's identity to an audit trail. For retry decisions, implement the recommended backoff using an exponential backoff with jitter library, respecting a maximum retry budget of 3 attempts before escalating to a human operator.

Model choice matters here. Use a model with strong instruction-following and structured output capabilities (e.g., Claude 3.5 Sonnet, GPT-4o) and set temperature=0 to maximize deterministic decision-making. The prompt's output schema should be enforced via the model's JSON mode or a structured output API to prevent parsing failures. Implement a post-response validator that checks for the presence of required fields (decision, lock_id, reasoning, safety_checks_passed) and rejects malformed responses, triggering a single retry with a simplified fallback prompt that asks only for a binary retry or escalate decision. Never automatically execute a force_unlock based solely on the model's output; the cost of corrupting Terraform state far outweighs the latency of human review.

IMPLEMENTATION TABLE

Expected Output Contract

The model must return a structured JSON decision object. Use this contract to validate the response before executing any state lock action.

Field or ElementType or FormatRequiredValidation Rule

decision

enum: retry | force-unlock | escalate

Must be exactly one of the three allowed values. Reject any other string.

lock_holder_identity

object { user_id, session_id, ip_address, timestamp }

All sub-fields must be present and non-null. timestamp must be ISO 8601.

operation_collision_detected

boolean

Must be a boolean literal. Reject if null or string.

collision_operations

array of strings

If operation_collision_detected is true, this field must be present and contain at least one non-empty string.

retry_after_seconds

integer

Required if decision is retry. Must be a positive integer. Reject if negative or zero.

force_unlock_risk_assessment

enum: low | medium | high | critical

Required if decision is force-unlock. Must be one of the four allowed values.

state_integrity_checksum

string

Required if decision is force-unlock. Must match the regex pattern ^[a-f0-9]{64}$.

escalation_reason

string

Required if decision is escalate. Must be a non-empty string with a minimum length of 20 characters.

PRACTICAL GUARDRAILS

Common Failure Modes

Terraform state lock conflicts can halt CI/CD pipelines and block engineering teams. These cards identify the most common failure patterns in AI-generated retry decisions and provide concrete guardrails to prevent state corruption, force-unlock disasters, and infinite retry loops.

01

Force-Unlock Without Lock Holder Verification

What to watch: The model recommends terraform force-unlock without first identifying who holds the lock, what operation they're running, or whether that operation is still active. Blind force-unlock can corrupt state if the lock holder is mid-apply. Guardrail: Require the prompt to output lock holder identity, operation type, and a liveness check before any force-unlock recommendation. Add a human approval gate for force-unlock actions.

02

Infinite Retry Loop on Persistent Lock Contention

What to watch: The retry prompt keeps recommending retries without checking whether the lock holder is making progress or is stuck. If the lock holder is a long-running apply, retries will fail until the operation completes, wasting CI minutes and API calls. Guardrail: Include a maximum retry count and a lock-age threshold. If the lock exceeds the threshold, escalate to a human with lock holder details instead of retrying.

03

State Integrity Check Skipped After Lock Release

What to watch: The model recommends proceeding with terraform apply immediately after a lock is released without verifying state file integrity. A force-unlock during a partial write can leave the state file inconsistent. Guardrail: Require a terraform state list or state pull validation step after any lock resolution before allowing subsequent mutating operations. Flag any state file checksum mismatches.

04

Concurrent Operation Collision Undetected

What to watch: The prompt treats the lock conflict as a simple contention issue without detecting that two pipelines are trying to modify the same resources. Retrying without coordination can cause one pipeline to overwrite the other's changes. Guardrail: Include operation diff detection in the prompt. Compare the planned changes from the lock holder and the retrying operation. If they overlap, escalate for sequencing rather than retrying.

05

Backend Lock Metadata Misinterpretation

What to watch: The model misreads lock metadata from S3, GCS, or Azure backends, confusing DynamoDB lock IDs with object lock headers or misinterpreting HTTP 409 vs. 423 status codes. This leads to incorrect retry strategies for different backend types. Guardrail: Include explicit backend-type detection in the prompt. Map lock error signatures to backend-specific resolution paths and validate that the model correctly identifies the storage backend before recommending actions.

06

CI/CD Pipeline Context Lost on Retry

What to watch: The retry prompt generates a recovery instruction but loses the original pipeline context—branch, commit SHA, workspace, and planned resource changes. The retried operation applies to the wrong workspace or replays a stale plan. Guardrail: Require the prompt to echo back the original pipeline context in its retry recommendation. Include workspace name, plan file reference, and commit identifier in the output for verification before execution.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the Terraform State Lock Conflict Retry prompt before production deployment. Each criterion includes a pass standard, a failure signal, and a test method to validate output quality.

CriterionPass StandardFailure SignalTest Method

Lock Holder Identification

Output correctly identifies the lock holder (user, host, operation) from the [ERROR_LOG] input.

Lock holder is missing, incorrect, or hallucinated when not present in the log.

Parse output for lock_holder field; assert it matches a substring in the provided error log.

Operation Collision Detection

Output lists the conflicting operation and the pending operation with correct timestamps.

Operations are swapped, missing, or timestamps are fabricated.

Compare conflicting_operation and pending_operation fields against the parsed [ERROR_LOG] timestamps and operation names.

Force-Unlock Risk Assessment

Output includes a state_integrity_risk flag (true/false) and a justification grounded in the lock age and operation type.

Risk flag is missing, or justification is generic and not tied to the specific lock metadata.

Assert state_integrity_risk is a boolean; check that risk_justification contains a specific reference to lock duration or operation type from the input.

Retry Decision Logic

Output provides a clear decision (retry/wait/force-unlock/escalate) consistent with the lock age and retry count.

Decision contradicts the provided [RETRY_COUNT] and [LOCK_AGE] constraints (e.g., retrying after budget exhausted).

Parameterized test: feed inputs with retry budget exhausted; assert decision is 'escalate'.

State Integrity Verification

Output includes a verification_steps array with concrete commands (e.g., terraform state list) when force-unlock is recommended.

verification_steps is empty or contains only generic advice when decision is 'force-unlock'.

Schema check: assert verification_steps is a non-empty array of strings when decision equals 'force-unlock'.

Output Schema Compliance

Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present.

Output is malformed JSON, missing required fields, or contains extra unvalidated keys.

Validate output against the defined JSON Schema; assert no required fields are missing and no additional properties are present if schema forbids them.

Escalation Path Clarity

When escalation is recommended, output specifies the target team or system and the reason for escalation.

Escalation target is vague (e.g., 'admin') or missing when decision is 'escalate'.

Assert that when decision is 'escalate', the escalation_target field is populated with a specific role or system name.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add structured output schema validation, retry budget tracking, lock holder identity verification, and state integrity preflight checks. Wire into a harness that logs decisions and requires human approval for force-unlock.

code
System: You are a Terraform state lock conflict resolver operating in a production infrastructure pipeline. Given [LOCK_ERROR_OUTPUT], [TERRAFORM_PLAN_SUMMARY], [LOCK_HOLDER_IDENTITY], [STATE_BACKEND_TYPE], and [RETRY_COUNT], produce a retry-or-force-unlock decision.

Constraints:
- Never force-unlock without verifying the lock holder's operation has terminated
- Check for concurrent operation collision before retrying
- If retry_count exceeds [MAX_RETRIES], escalate to [ON_CALL_CHANNEL]
- Validate state file integrity before any force-unlock

Return JSON matching [OUTPUT_SCHEMA] with fields: decision, lock_holder, collision_detected, state_integrity_check, retry_backoff_seconds, escalation_required, reasoning

Watch for

  • Silent format drift in output schema
  • Missing human approval gate for force-unlock
  • Retry storm when multiple pipelines contend for the same lock
  • State backend type differences (S3 vs. GCS vs. Terraform Cloud)
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.