Azure Function - Trigger Python Script Containing Azure Cli Commands
Solution 1:
I tried to create a simple Azure Function with HttpTrigger to invoke Azure CLI tools by different ways, but never works on cloud after published.
It seems the only solution is to publish the function as docker image with --build-native-deps option for the command func azure functionapp publish <your function app name> after add the required package azure-cli into the requirements.txt file, as the figure with error below said,
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
Due to there is not docker tools in my local, I did not successfully run func azure functionapp publish <your function app name> --build-native-deps.
Meanwhile, running Azure CLI commands is not the only one ways to use the functions of Azure CLI. The az command is just a runnable script file, not a binary execute file. After I reviewd az and some source codes of azure-cli package, I think you can directly import the package via from azure.cli.core import get_default_cli and to use it to do the same operations like the code below.
from azure.cli.core import get_default_cli
az_cli = get_default_cli()
exit_code = az_cli.invoke(args)
sys.exit(exit_code)
The code is written by referring to the source code of azure/cli/__main__.py of azure-cli package, you can see it from the lib/python3.x/site-packages path of your virtual environment.
Hope it helps.
Solution 2:
Thanks, Peter, I used something similar in the end and got it working. I have this function which will run the AZ CLI commands and return results if we need to (like for example if I need to run the cli command but also store the output, for example if I want to know what an object ID of a service principal is, I can get the results like in this example:
defaz_cli (args):
cli = get_default_cli()
cli.invoke(args)
if cli.result.result:
return cli.result.result
elif cli.result.error:
raise cli.result.error
returnTrueNow, I can make the call like this (client_id is the ServicePrincipal ID):
ob_id = az_cli(['ad', 'sp', 'show', '--id', client_id])
print(ob_id["objectId"])

Post a Comment for "Azure Function - Trigger Python Script Containing Azure Cli Commands"