how to add LogAnalyticsWorkSpace extension to VM using Python SDK in Azure

Question:

I have created Log Analytics workspace in azure. Now to want to attach it as an extension to VM using Python sdk. I have followed the documentation and getting error as follow.

class ‘azure.core.exceptions.HttpResponseError’> occurred.

Can someone help me in this please.

Below is the approach I have tried using compute management client.

   extension = compute_client.virtual_machine_extensions.begin_create_or_update(
        "MyRG",
        "MyVMName",
        "MicrosoftMonitoringAgent", ##VMExtension name
        {
          "type": "Microsoft.Compute/virtualMachines/extensions",
          "location": "eastus",   
             "publisher": "Microsoft.EnterpriseCloud.Monitoring",         
             "type_handler_version": "1.0",            
             "auto_upgrade_minor_version": True,
             "settings": {
               "workspaceId": "XXXXX"
                },
             "protected_settings": {
                "workspaceKey": "XXXXX"
                }            
        }
    ).Result()

enter image description here

Asked By: sai siddhartha

||

Answers:

I tried in my environment and successfully created Log-Analytics-WorkSpace extension to VM using python:

Code:

I tried with ComputeManagementClient and DefaultAzureCredential method to begin_create_or_update. Make sure with parameters and resources are correct state.

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential


subscriptionid = "<subscription id>"
credential = DefaultAzureCredential()
compute_client=ComputeManagementClient(subscription_id=subscriptionid,credential=credential)
extension = compute_client.virtual_machine_extensions.begin_create_or_update(
   resource_group_name="<resource group>",
        vm_name="<vname>",vm_extension_name="MicrosoftMonitoringAgent",extension_parameters=
        {
             "publisher": "Microsoft.EnterpriseCloud.Monitoring",
             "location":"eastus",       
             "type_handler_version": "1.0",            
             "auto_upgrade_minor_version": True,
             "settings": {
               "workspaceId": "7c950e4f-5c9b-4205-ba79-278cd22bd220"
                },
             "protected_settings": {
                "workspaceKey": "TlLvMVn55RQEHtWBJUSvmbYyaVeev4srp1Vu5ZF/dh2paVI9qrQ/8P4rnEGjmPkHD8LbOpQHKUOhSHMz2r/v2A=="
                }               
        }
    )   

print("Extension is created")

Console:

I executed the above code it created log-analytics extension successfully in my environment.

enter image description here

Portal:

enter image description here

Reference:

azure-content/log-analytics-azure-vm-extension.md at master ยท uglide/azure-content (github.com).

Answered By: Venkatesan