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

标签 python azure azure-functions azure-cli

我有一个用于在 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/

相关文章:

azure - 是否可以像 DB 对象一样编写 Azure 警报脚本

azure - 在Azure FunctionsStartup的Configure中运行一些启动任务

python - MySQL-Python 代码无法正常工作,每次我尝试修复时都会生成各种错误

python - 如何访问 Robot Framework 中的对象变量?

java - 针对目标用户和组的 Azure 应用程序配置功能标记不起作用

azure - 如何在同一资源组中的 Azure Function 应用程序中设置 Key Vault secret ?

c# - 命名空间 'Azure' 中不存在类型或命名空间 'Microsoft' - Visual Studio 2022

python - 处理列表并输出为列表

Python SQLAlchemy 查询使用带有 ORM 的标记 OVER 子句

azure - 好的Azure存储客户端库?