DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 Terraform 报错 plugin-cache-dir cannot be used 缓存竞争修复

排查 Terraform 执行 init 提示 Failed to install provider ... plugin-cache-dir cannot be used,解决高并发下的锁竞争与软链接配置。

问题现象

在 CI/CD 流水线中并发运行 terraform init 时,初始化失败中断:

Error: Failed to install provider

Error while installing hashicorp/aws: the configured plugin-cache-dir 
/root/.terraform.d/plugin-cache cannot be used because 
failed to copy file: file text busy / permission denied

触发根因

在 ~/.terraformrc 中配置了 plugin_cache_dir 全局缓存以节约下载流量。但在并发流水线中,多个 terraform init 进程同时尝试将同一个 Provider 插件压缩包解压或移动到该共享目录时,触发文件锁写冲突或覆盖竞态导致进程失败。

解决步骤

1. 确保缓存目录存在并设置正确归属权限

Terraform 不会自动递归创建不存在的父目录:

mkdir -p ~/.terraform.d/plugin-cache
chmod 755 ~/.terraform.d/plugin-cache

2. 在 CI 环境中使用隔离的临时缓存路径或禁用并发写

在并发作业前动态注入独立的缓存路径:

export TF_PLUGIN_CACHE_DIR=/tmp/tf-cache-${CI_JOB_ID:-default}
mkdir -p $TF_PLUGIN_CACHE_DIR
terraform init

验证确认

运行初始化验证:

terraform init

控制台打印 Terraform has been successfully initialized!,Provider 插件顺利从缓存挂载。