Search code examples
azureazure-virtual-machineazure-powershellazure-oms

Install extension on both Classic and ARM VMs with single PowerShell command


I have a script that installs OMS extensions to all ARM VMs in the subscription. The problem is that I have subscriptions that contain only ARM VMs, subscriptions that contain only Classic VMs, and subscription that have both types of VMs. How can I modify the script to work in all of the conditions? The script is:

#This script installs OMS Monitoring Agent to all VMs in the selected Subscription.
#Before running this script, the user must login to Azure account and select target subscription.
#Example:
#Login-AzureRmAccount
#Select-AzureRmSubscription 'SubscriptionName'

$WorkspaceID = 'Provide Workspace ID here'
$WorkspaceKey = 'Provide Workspace key here'
$VMs = Get-AzureRmVM

$VMs.where({$_.osprofile.windowsconfiguration}) | ForEach-Object {
    "Installing Microsoft.EnterpriseCloud.Monitoring.MicrosoftMonitoringAgent Extension: {0}" -f $_.id
    Set-AzureRmVMExtension -ResourceGroupName $_.ResourceGroupName -VMName $_.Name -Name omsAgent -Publisher 'Microsoft.EnterpriseCloud.Monitoring' `
    -ExtensionType 'MicrosoftMonitoringAgent' -AsJob -TypeHandlerVersion '1.0' -Location $_.Location -ForceRerun 'yesh' `
    -SettingString ( "{'workspaceId': '$WorkspaceID'}") `
    -ProtectedSettingString "{'workspaceKey': '$WorkspaceKey'}" | 
    Add-Member -Name VM -Value $_.Id -MemberType NoteProperty
}

Solution

  • Since you got both classic and ARM VMs, you got two different deployment models, hence two different PowerShell modules you are using.

    In other words, you need to log in separately for each and have separate scripts for using them.

    In the classic model you need to run the following cmdlet to login and access your VMs:

    Add-AzureAccount
    Get-AzureVM | Set-AzureVMExtension `` 
        -Publisher 'Microsoft.EnterpriseCloud.Monitoring' `` 
        -ExtensionName 'MicrosoftMonitoringAgent' `` 
        -Version '1.*' `` 
        -PublicConfiguration "<workspace id>" `` 
        -PrivateConfiguration "<workspace key>" `` 
    

    While searching for information I found this script. It's a script for on-boarding VMs from single, or multiple subscriptions, using both deployment models.