Search code examples
azureazure-virtual-machineazure-sdkazure-sdk-python

Python Azure SDK virtual_machines.run_command


Having trouble with the python azure sdk. When running a powershell command from portal.azure.com on the virtual machine "run command" section I am successfully able to execute New-Item C:\test2.txt

When I run it from the python azure sdk I am unable to perform this task. It completes and I can see a command was sent to the machine by looking in the activity log for the vm. Am I missing something?

def run_command(vm_name):
    compute_client = get_compute_connection()
    
    run_command_parameters = {
      'command_id': 'RunPowerShellScript',
      'script': [
          'New-Item C:\test2.txt'
      ]
    }
    
    command = compute_client.virtual_machines.run_command(
        resource_group,
        vm_name,
        run_command_parameters
    )
    
    r = command.result()
    print(r)

run_command('vm12345')

this returns

{'additional_properties': {}, 'value': [<azure.mgmt.compute.v2019_12_01.models._models_py3.InstanceViewStatus object at 0x0000029C15A7A108>, <azure.mgmt.compute.v2019_12_01.models._models_py3.InstanceViewStatus object at 0x0000029C15A7A648>]}

Solution

  • This is expected type as output RunCommandResult you can find the detail here: https://learn.microsoft.com/en-us/python/api/azure-mgmt-compute/azure.mgmt.compute.v2019_07_01.models.runcommandresult?view=azure-python

    For instance, to get stdout/stderr: r.value[0].message

    This other post might help as well: Run command in linux vm in azure using python sdk

    (I work at MS in the SDK team)