gpt4 book ai didi

python - Azure Function - 触发包含 Azure CLI 命令的 Python 脚本

转载 作者:行者123 更新时间:2023-12-02 06:19:18 26 4
gpt4 key购买 nike

我有一个用于在 Azure 中配置基础设施的 python 脚本 - IaC。该脚本主要使用 Python SDK,但也运行多个 Azure CLI 命令 - 当我在 Python SDK 中找不到等效命令时,有时需要它。

我的目标是使用 Azure Functions 按需触发此脚本。在本地测试 Azure Function 时,一切正常,因为我的计算机上安装了 Azure CLI,但是,当我将其发布到 Azure Functions 时,我会遇到错误: /bin/sh: 1: az:未找到

下面是我在 Azure 函数中触发的示例 python 函数(请注意,脚本的其余部分工作正常,因此我可以创建 RG、SQL 服务器等,问题只是 az 命令)。我想知道是否以及如何在 Azure Function 上安装 Azure CLI 以便能够运行 CLI 命令?

这是导致错误的Python函数:

    # Loging to AZ
call("az login --service-principal -u '%s' -p '%s' --tenant '%s'" % (client_id, client_secret, tenant_id), shell=True)
b2c_id = check_output("az resource show -g '<rg_name>' -n '<b2c_name>' --resource-type 'Microsoft.AzureActiveDirectory/b2cDirectories' --query id --output tsv", shell=True)
print("The B2C ID is: %s" % b2c_id)```

最佳答案

我尝试使用 HttpTrigger 创建一个简单的 Azure Function,以通过不同方式调用 Azure CLI 工具,但发布后从未在云上运行。

似乎唯一的解决方案是将函数发布为 docker 镜像 --build-native-deps命令 func azure functionapp publish <your function app name> 的选项添加所需的包azure-cli后进入requirements.txt文件,如下图错误所示,

enter image description here

There was an error restoring dependencies.ERROR: cannot install antlr4-python3-runtime-4.7.2 dependency: binary dependencies without wheels are not supported. Use the --build-native-deps option to automatically build and configure the dependencies using a Docker container. More information at https://aka.ms/func-python-publish

由于我本地没有docker工具,所以没有成功运行func azure functionapp publish <your function app name> --build-native-deps .

同时,运行 Azure CLI 命令并不是使用 Azure CLI 功能的唯一方法。 az命令只是一个可运行的脚本文件,而不是二进制执行文件。我查看后az以及azure-cli的一些源代码包,我想你可以直接通过 from azure.cli.core import get_default_cli 导入包并使用它来执行与下面的代码相同的操作。

from azure.cli.core import get_default_cli

az_cli = get_default_cli()
exit_code = az_cli.invoke(args)
sys.exit(exit_code)

代码是引用azure/cli/__main__.py的源码编写的的azure-cli包,可以从 lib/python3.x/site-packages 看到您的虚拟环境的路径。

希望有帮助。

关于python - Azure Function - 触发包含 Azure CLI 命令的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com