You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Terraform的local-exec中让命令输出显示在终端?

如何让Terraform local-exec的命令输出显示在终端里

完全可行,以下是几种实现方式:

  • 默认输出(无需额外配置)
    Terraform的local-exec provisioner默认会捕获命令的标准输出(stdout)和标准错误(stderr),并直接打印到终端。如果你的命令没有做输出重定向,执行Terraform部署时就能在终端看到结果。比如你提供的示例代码,执行后终端会显示machine1(因为--query 'deviceId'指定了输出内容)。

    如果你之前是通过重定向(比如>> output.txt)将输出写入文件,只需去掉重定向部分,就能让输出显示在终端。

  • 同时输出到终端和文件
    要是你既想保存输出到文件,又想实时在终端查看,可以通过命令行工具实现:

    • Linux/macOS环境(用tee命令):
      provisioner "local-exec" {
        command = "az iot hub device-identity create --device-id 'machine1' --edge-enabled --hub-name 'hub1' --query 'deviceId' | tee device_id.txt"
      }
      
    • Windows PowerShell环境(用Tee-Object):
      provisioner "local-exec" {
        command = "az iot hub device-identity create --device-id 'machine1' --edge-enabled --hub-name 'hub1' --query 'deviceId' | Tee-Object -FilePath device_id.txt"
      }
      
  • 通过Terraform Output块专门展示结果
    如果你希望在部署完成后,单独突出显示这个结果,可以捕获local-exec的输出,再用Terraform的output块展示:

    resource "azurerm_iothub" "service" {
      name                = "iot-hub-qnsie"
      resource_group_name = "my_rg_group"
      location            = "USA"
    
      provisioner "local-exec" {
        command = "az iot hub device-identity create --device-id 'machine1' --edge-enabled --hub-name 'hub1' --query 'deviceId' -o tsv"
        stdout = true
        output = "device_id"
      }
    }
    
    output "created_iot_device_id" {
      value = azurerm_iothub.service.provisioners.local-exec.device_id
      description = "已创建的IoT Edge设备ID"
    }
    

    这样部署过程中local-exec的输出会显示在终端,部署结束后还会专门打印created_iot_device_id的结果。

内容的提问来源于stack exchange,提问作者ForyszeP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:15:44