Terraform 助手
- 作者仓库星标 1,187
- 叉子 185
- 作者更新于 2026年6月14日 10:01
- 作者仓库 claude-code-skills
- 领域
- 运维部署
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @daymade · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 需要 · Vendor-specific
- 兼容的系统
- macOS · Docker
- 底层运行要求
- Docker
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 读取环境变量
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: terraform-skill
description: > Failure patterns from real deployments. Every item caused an incident. Organized as: exact err…
category: 运维部署
runtime: Docker
---
# terraform-skill 输出预览
## PART A: 任务判断
- 适用问题:部署、CI、环境检查、发布或运维排障。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Provisioner traps (symptom → fix) / docker: not found in remote-exec / rsync: connection unexpectedly closed in local-exec”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于部署、CI、环境检查、发布或运维排障,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Provisioner traps (symptom → fix) / docker: not found in remote-exec / rsync: connection unexpectedly closed in local-exec”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、读取环境变量、会按任务需要访问外部网络、需要准备 Vendor-specific API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文出现了 `/tmp`、`/data` 这类斜杠命令;如果你的 Agent 支持命令触发,优先用命令开场,再补充目标和边界。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令、读取环境变量。
先用一个小任务确认它会围绕“Provisioner traps (symptom → fix) / docker: not found in remote-exec / rsync: connection unexpectedly closed in local-exec”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: terraform-skill
description: > Failure patterns from real deployments. Every item caused an incident. Organized as: exact err…
category: 运维部署
source: daymade/claude-code-skills
---
# terraform-skill
## 什么时候使用
- terraform-skill 是运维部署方向的技能,让 Agent 操作环境、改配置、跑发布流程 适合处理部署、CI、发布、回滚、环境检查和运维排障,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。…
- 面向部署、CI、环境检查、发布或运维排障,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Provisioner traps (symptom → fix) / docker: not found in remote-exec / rsync: connection unexpectedly closed in local-exec」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "terraform-skill" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Provisioner traps (symptom → fix) / docker: not found in remote-exec / rsync: connection unexpectedly closed in local-exec
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Docker | 读取文件、写入/修改文件、执行终端命令、读取环境变量 | 会按任务需要访问外部网络
安全层 -> 需要准备 Vendor-specific API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Terraform Operational Traps
Failure patterns from real deployments. Every item caused an incident. Organized as: exact error → root cause → copy-paste fix.
Provisioner traps (symptom → fix)
docker: not found in remote-exec
cloud-init still installing Docker when provisioner SSHs in.
provisioner "remote-exec" {
inline = [
"cloud-init status --wait || true",
"which docker || { echo 'FATAL: Docker not ready'; exit 1; }",
]
}
rsync: connection unexpectedly closed in local-exec
Terraform holds its SSH connection open; local-exec rsync opens a second one that gets rejected. Never use local-exec for file transfer to remote. Use tarball + file provisioner:
provisioner "local-exec" {
command = "tar czf /tmp/src.tar.gz --exclude=node_modules --exclude=.git -C ${path.module}/../../.. myproject"
}
provisioner "file" {
source = "/tmp/src.tar.gz"
destination = "/tmp/src.tar.gz"
}
provisioner "remote-exec" {
inline = ["tar xzf /tmp/src.tar.gz -C /data/ && rm -f /tmp/src.tar.gz"]
}
macOS BSD tar: --exclude must come BEFORE the source argument.
cloud-init status shows "running" forever
apt-get -y does not suppress debconf dialogs. Packages like iptables-persistent block on TTY prompts.
- |
echo iptables-persistent iptables-persistent/autosave_v4 boolean true | debconf-set-selections
echo iptables-persistent iptables-persistent/autosave_v6 boolean true | debconf-set-selections
DEBIAN_FRONTEND=noninteractive apt-get install -y iptables-persistent
Known offenders: iptables-persistent, postfix, mysql-server, wireshark-common.
EACCES: permission denied in container logs, container Restarting
Host volume dirs are root-owned; container runs as non-root (uid 1001). Fix before docker compose up:
mkdir -p /data/myapp/data /data/myapp/logs
chown -R 1001:1001 /data/myapp/data /data/myapp/logs
Find UID: grep adduser.*-u or USER in Dockerfile.
Provisioner fails but no diagnostic output
set -e exits on first error, hiding subsequent docker logs output. Use set -u without -e, put one verification gate at the end:
provisioner "remote-exec" {
inline = [
"set -u",
"docker compose up -d",
"sleep 15",
"docker logs myapp --tail 20 2>&1 || true",
"docker ps --format 'table {{.Names}}\\t{{.Status}}' || true",
"docker ps --filter name=myapp --format '{{.Status}}' | grep -q healthy || exit 1",
]
}
Container Restarting — database tables missing
DB migrations not in provisioner. PostgreSQL docker-entrypoint-initdb.d only runs on empty data dir. Explicitly create DB + run migrations:
# After postgres healthy:
docker exec pg psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname='mydb'" | grep -q 1 \
|| docker exec pg psql -U postgres -c "CREATE DATABASE mydb;"
# Idempotent migrations:
for f in migrations/*.sql; do
VER=$(basename $f)
APPLIED=$($PSQL -tAc "SELECT 1 FROM schema_migrations WHERE version='$VER'" | tr -d ' ')
[ "$APPLIED" = "1" ] && continue
{ echo 'BEGIN;'; cat $f; echo 'COMMIT;'; } | $PSQL
$PSQL -tAc "INSERT INTO schema_migrations(version) VALUES ('$VER') ON CONFLICT DO NOTHING"
done
docker compose build ignores env var override
Compose reads build args from .env file, not shell env. VAR=x docker compose build does NOT work.
# WRONG
DOCKER_WITH_PROXY_MODE=disabled docker compose build
# RIGHT
grep -q DOCKER_WITH_PROXY_MODE .env || echo 'DOCKER_WITH_PROXY_MODE=disabled' >> .env
docker compose build
TLS handshake fails: Invalid format for Authorization header
Caddy DNS-01 ACME needs a Cloudflare API Token (cfut_ prefix, 40+ chars, Bearer auth). A Global API Key (37 hex chars, X-Auth-Key auth) causes HTTP 400 Code:6003. Production may appear to work because it has cached certificates; fresh environments fail on first cert request.
# Verify token format before deploy:
TOKEN=$(grep CLOUDFLARE_API_TOKEN .env | cut -d= -f2)
echo "$TOKEN" | grep -q "^cfut_" || echo "FATAL: needs API Token, not Global Key"
Create scoped token via API:
curl -s "https://api.cloudflare.com/client/v4/user/tokens" -X POST \
-H "X-Auth-Email: $CF_EMAIL" -H "X-Auth-Key: $CF_GLOBAL_KEY" \
-d '{"name":"caddy-dns-acme","policies":[{"effect":"allow",
"resources":{"com.cloudflare.api.account.zone.<ZONE_ID>":"*"},
"permission_groups":[
{"id":"4755a26eedb94da69e1066d98aa820be","name":"DNS Write"},
{"id":"c8fed203ed3043cba015a93ad1616f1f","name":"Zone Read"}]}]}'
TLS fails on staging but works on production — hardcoded domains
Caddyfile or compose has literal domain names. Staging Caddy loads production config, tries to get certs for domains it doesn't own → ACME fails.
Caddyfile: Use {$VAR} — Caddy evaluates env vars at startup.
# WRONG
example.com { tls { dns cloudflare {env.CLOUDFLARE_API_TOKEN} } }
# RIGHT
{$LOBEHUB_DOMAIN} { tls { dns cloudflare {env.CLOUDFLARE_API_TOKEN} } }
Compose: Use ${VAR:?required} — fail-fast if unset.
# WRONG
- APP_URL=https://example.com
# RIGHT
- APP_URL=${APP_URL:?APP_URL is required}
Pass the env var to the gateway container so Caddy can read it:
environment:
- LOBEHUB_DOMAIN=${LOBEHUB_DOMAIN:?LOBEHUB_DOMAIN is required}
- CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN:?required for DNS-01 TLS}
OAuth login fails: Social sign in failed
Casdoor init_data.json contains hardcoded redirect URIs. --createDatabase=true only applies init_data on first-ever DB creation — not on restarts. Fix via SQL in provisioner:
# Replace production domain with staging in existing Casdoor DB
$PSQL -c "UPDATE application SET redirect_uris = REPLACE(redirect_uris,
'example.com', 'staging.example.com')
WHERE name='lobechat'
AND redirect_uris LIKE '%example.com%'
AND redirect_uris NOT LIKE '%staging.example.com%';"
Also check AUTH_CASDOOR_ISSUER — it must match the Casdoor subdomain (auth.staging.example.com), not the app root domain.
Multi-environment isolation
Before creating a second environment, grep .tf files for hardcoded names. See references/multi-env-isolation.md for the complete matrix.
Will fail on apply (globally unique):
| Resource | Scope | Fix |
|---|---|---|
| SSH key pair | Region | "${env}-deploy" |
| SLS log project | Account | "${env}-logs" |
| CloudMonitor contact | Account | "${env}-ops" |
DNS duplication trap: Two environments creating A records for the same name in the same Cloudflare zone → two independent record IDs → DNS round-robin → ~50% traffic to wrong instance. Fix: use subdomain isolation (staging.example.com) or separate zones. Remember to create DNS records for ALL subdomains Caddy serves (e.g., auth.staging, minio.staging).
Snapshot cross-contamination: Unfiltered data "alicloud_ecs_snapshots" returns ALL account snapshots. New env inherits old 100GB snapshot, fails creating 40GB disk. Gate with variable:
locals {
latest_snapshot_id = var.enable_snapshot_recovery && length(local.available_snapshots) > 0
? local.available_snapshots[0].snapshot_id : null
}
Do NOT add count to the data source — changes its state address, causes drift.
Pre-deploy validation
Run a validation script before terraform apply to catch configuration errors locally. This eliminates the deploy→discover→fix→redeploy cycle.
Key checks (see references/pre-deploy-validation.md):
terraform validate— syntax- No hardcoded domains in Caddyfiles or compose files
- Required env vars present (
LOBEHUB_DOMAIN,CLAUDE4DEV_DOMAIN,CLOUDFLARE_API_TOKEN,APP_URL, etc.) - Cloudflare API Token format (not Global API Key)
- DNS records exist for all Caddy-served domains
- Casdoor issuer URL matches
auth.*subdomain - SSH private key exists
Integrate into Makefile: make pre-deploy ENV=staging before make apply.
Zero-to-deployment
Fresh disks expose every implicit dependency. See references/zero-to-deploy-checklist.md.
Key items that break provisioners on fresh instances:
- Directories:
mkdir -p /data/{svc1,svc2}in cloud-init —fileprovisioner fails if target dir missing - Databases: Explicit
CREATE DATABASE— PG init scripts only run on empty data dir - Migrations: Tracked in
schema_migrationstable, applied idempotently - Provisioner ordering:
depends_onbetween resources sharing Docker networks - Memory: Stop non-critical containers during Docker build on small instances (≤8GB)
- Domain parameterization: Every domain in Caddyfile/compose must be
{$VAR}/${VAR:?required} - Credential format: Caddy needs API Token (
cfut_), not Global API Key
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核