Stage 7 · Master
ChatOps & On-Call Copilots
kubectl & Terraform Copilots
Natural-language ops with dry-run confirmation and read-only guardrails.
Natural-Language Operations
A kubectl copilot translates natural language into kubectl or Terraform commands. Instead of remembering exact flag syntax, the engineer describes what they want to do and the copilot generates the correct command.
The critical design constraint is safety. The copilot must never execute commands without human confirmation. It generates commands, shows them for review, and only executes after explicit approval.
Command Generation
KUBECTL_SYSTEM = """You are a kubectl command generator.
Given a natural language request, generate the correct kubectl command.
RULES:
- Only output the kubectl command, nothing else
- Use the correct flags and syntax
- If the request is ambiguous, ask for clarification
- If the request could be destructive, add a warning
- Default to the production namespace if not specified
Output format: JSON with command, explanation, and risk level."""
def generate_kubectl_command(user_request):
response = openai.ChatCompletion.create(
model="gpt-4",
temperature=0.0,
messages=[
{"role": "system", "content": KUBECTL_SYSTEM},
{"role": "user", "content": user_request}
]
)
return json.loads(response["choices"][0]["message"]["content"])
# Example
result = generate_kubectl_command("show me all pods that are crash looping in production")
print(result)
# {"command": "kubectl get pods -n production --field-selector=status.phase!=Running",
# "explanation": "Lists pods not in Running state in production namespace",
# "risk_level": "safe"}The model generates the command with metadata about risk level and explanation. This lets the application enforce different rules for safe vs risky commands.
Dry-Run Confirmation
def kubectl_copilot(user_request, channel_id):
"""Generate and confirm kubectl commands."""
# Generate command
result = generate_kubectl_command(user_request)
if result["risk_level"] == "safe":
# Auto-execute safe read-only commands
output = execute_kubectl(result["command"])
return f"Command: `{result['command']}`\n\n{output}"
else:
# Show for confirmation
confirmation_msg = f"""Proposed command:
```
{result['command']}
```
Explanation: {result['explanation']}
Risk: {result['risk_level']}
React with checkmark to execute, or X to cancel."""
# Post and wait for reaction
response = say(confirmation_msg, channel=channel_id)
wait_for_confirmation(response["ts"])
output = execute_kubectl(result["command"])
return f"Executed:\n\n{output}"Safe read-only commands like kubectl get can auto-execute. Write commands like kubectl delete require explicit human confirmation.
Read-Only Guardrails
| Command Type | Risk Level | Auto-Execute? |
|---|---|---|
| kubectl get | Safe | Yes |
| kubectl describe | Safe | Yes |
| kubectl logs | Safe | Yes |
| kubectl apply --dry-run | Low | Yes |
| kubectl scale | Medium | No, confirm |
| kubectl delete | High | No, confirm |
| kubectl exec | High | No, confirm |
SAFE_COMMANDS = ["get", "describe", "logs", "explain", "auth can-i"]
RISKY_COMMANDS = ["delete", "exec", "attach", "cp"]
MODIFY_COMMANDS = ["apply", "create", "patch", "scale", "rollout"]
def classify_command(command):
"""Classify a kubectl command by risk level."""
parts = command.split()
if len(parts) < 2:
return "unknown"
verb = parts[1]
if verb in SAFE_COMMANDS:
return "safe"
elif verb in RISKY_COMMANDS:
return "high"
elif verb in MODIFY_COMMANDS:
return "medium"
elif "--dry-run" in command:
return "low"
else:
return "medium" # Default to medium for unknown commandsClassification drives the approval workflow. Safe commands proceed, medium commands show a warning, and high-risk commands require explicit confirmation.
Terraform Copilot
def interpret_terraform_plan(plan_output):
"""Use an LLM to explain Terraform plan output."""
response = openai.ChatCompletion.create(
model="gpt-4",
temperature=0.0,
messages=[
{
"role": "system",
"content": "Explain this Terraform plan in plain English. List every resource that will be created, modified, or destroyed. Flag any risky changes."
},
{"role": "user", "content": plan_output}
]
)
return response["choices"][0]["message"]["content"]Terraform plan output is verbose and easy to misread. An LLM can summarize it in plain English, highlighting destructive changes.
Always require human confirmation for terraform apply. The copilot can interpret plans and suggest changes, but the human must approve execution.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.