How to run Azure CLI commands using Python

      

Azure CLI is a command line interface which helps in creating and managing Azure resources.

Python provides a package called az.cli which can be used to run Azure CLI commands from a Python file. This is helpful because Python provides lot more flexibility to store and parse the CLI command outputs.

Below snippet shows how az.cli can be used to run CLI commands in a Python file.

 from az.cli import az  
   
 def execute_cmd(cmd):  
   try:  
     exit_code, result, logs = az(cmd)  
     if exit_code == 0:  
       return result  
     else:  
       print(logs)  
   except Exception as e:  
     print("Error occured!! While running the CLI command. {}".format(e))  
   
 example_cmd = "vm boot-diagnostics disable \  
                    --name {} \  
                    --resource-group {}".format(vm, resource_group)  
    
 boot_diagnostics = execute_cmd(example_cmd)    
   

Post a Comment

0 Comments