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

FastAPI调用Azure CLI执行命令后Swagger无返回结果问题咨询

问题根因

你的代码存在几个核心问题导致无法获取输出:

  • 创建的tempfile.TemporaryFile()未绑定到Azure CLI的输出流,Azure CLI默认会将命令结果打印到服务端的标准输出(即终端),不会自动写入你创建的临时文件
  • get_default_cli().invoke()的返回值是命令的退出状态码(0代表执行成功,非0代表执行失败),并非命令执行的输出内容
  • 每次请求都执行一次服务主体登录,会导致不必要的性能损耗,且敏感信息硬编码存在泄露风险
修复代码

你需要在调用invoke时通过out_file参数指定输出流,同时调整临时文件的读写逻辑:

from fastapi import FastAPI
import tempfile
import json
import os
from azure.cli.core import get_default_cli

app = FastAPI()
# 应用启动时仅执行一次服务主体登录,敏感信息从环境变量读取
az_cli = get_default_cli()
az_cli.invoke([
    'login', '--service-principal',
    '-u', os.getenv('AZURE_CLIENT_ID'),
    '-p', os.getenv('AZURE_CLIENT_SECRET'),
    '--tenant', os.getenv('AZURE_TENANT_ID')
])

@app.get("/azure")
def run_az_cmd(args_str: str):
    # 追加json输出参数,方便后续解析为结构化数据
    args = args_str.split() + ['-o', 'json']
    with tempfile.TemporaryFile(mode='w+', encoding='utf-8') as temp_file:
        # 将CLI输出重定向到临时文件
        exit_code = az_cli.invoke(args, out_file=temp_file)
        # 移动文件指针到开头,读取写入的内容
        temp_file.seek(0)
        output_content = temp_file.read()
    
    # 尝试解析为JSON格式返回,解析失败则返回原始字符串
    try:
        output = json.loads(output_content)
    except json.JSONDecodeError:
        output = output_content
    
    return {
        "command_args": args,
        "exit_code": exit_code,
        "output": output
    }
验证方法

启动服务后在Swagger文档的args_str输入框填入group list,调用接口即可在响应体中看到订阅下所有资源组的结构化数据。

优化建议
  • 增加接口权限校验和命令参数校验,避免传入高危操作命令(如资源删除、配置修改类命令),防止接口被滥用
  • 如果仅需要操作Azure资源,优先使用Azure Python SDK(如azure-mgmt-resource),比调用Azure CLI的性能更高、错误处理更灵活
  • 生产环境不要硬编码服务主体凭证,建议通过环境变量、Azure密钥保管库等安全方式读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:39:00