使用Terraform local exec获取App Service发布配置文件失败
解决Terraform读取Azure App Service发布配置文件失败的问题
问题场景
尝试通过Terraform获取Azure App Service的发布配置文件,保存到本地后读取内容,用于后续存入Azure Key Vault并在Github Actions工作流中调用,但执行时出现文件找不到的错误。
用户代码
resource "null_resource" "get_publish_profile" { provisioner "local-exec" { working_dir = path.module command = <<EOT az webapp deployment list-publishing-profiles --name xxx --resource-group xxx --subscription xxx --xml >> ./output/publish_profile.xml EOT } } data "local_file" "publish_profile" { depends_on = [null_resource.get_publish_profile] filename = "./output/publish_profile.xml" } output "publish_profile_output" { value = data.local_file.publish_profile.content }
错误信息
│ Error: Read local file data source error │ │ with module.publish_profile.data.local_file.publish_profile, │ on modules/null_resource/main.tf line 12, in data "local_file" "publish_profile": │ 12: data "local_file" "publish_profile" { │ │ The file at given path cannot be read. │ │ +Original Error: open modules/null_resource/publish_profile.xml: no such │ file or directory
解决方法
确保output目录存在:
local-exec执行的命令会尝试写入./output目录,若目录不存在,az命令会执行失败导致文件未生成。可在命令中先创建目录:command = <<EOT mkdir -p ./output && az webapp deployment list-publishing-profiles --name xxx --resource-group xxx --subscription xxx --xml >> ./output/publish_profile.xml EOTWindows环境下替换为
mkdir .\output 2>nul && ...使用绝对路径替代相对路径:相对路径可能因Terraform工作目录或模块上下文出现偏差,改用
path.module拼接绝对路径:resource "null_resource" "get_publish_profile" { provisioner "local-exec" { working_dir = path.module command = <<EOT az webapp deployment list-publishing-profiles --name xxx --resource-group xxx --subscription xxx --xml >> "${path.module}/output/publish_profile.xml" EOT } } data "local_file" "publish_profile" { depends_on = [null_resource.get_publish_profile] filename = "${path.module}/output/publish_profile.xml" }验证
az命令执行状态:在local-exec中添加错误检查,确保命令执行失败时Terraform能捕获错误,避免后续步骤无效执行:command = <<EOT mkdir -p ./output az webapp deployment list-publishing-profiles --name xxx --resource-group xxx --subscription xxx --xml >> ./output/publish_profile.xml if [ $? -ne 0 ]; then exit 1; fi EOT检查权限与执行时机:确认当前执行Terraform的用户对
path.module/output目录有读写权限;可显式设置provisioner的when = "create"参数,明确仅在资源创建时执行命令。改用覆盖模式写入文件:避免追加模式(
>>)可能导致的空文件问题,改用覆盖模式(>)确保文件被正确生成:az webapp deployment list-publishing-profiles ... --xml > ./output/publish_profile.xml
内容的提问来源于stack exchange,提问作者Norbi
相关产品推荐
相关产品推荐

