core/Resources/Scripts/enable_detailed_monitoring.ps1
|
Param( [string]$EnvironmentName ) $vms = [System.Collections.ArrayList]@() $resource = $null function GetResourceGroup { $resource = Get-AzResourceGroup -ErrorAction Stop | Where-Object { $_.Tags -and $_.Tags.Contains("EnvironmentName") -and $_.Tags["EnvironmentName"] -eq $EnvironmentName } if (-not $resource) { throw "No such environment exists" } } function GetUploadedVms { param( [string]$ResourceGroup ) $vms = @(Get-AzVM -ErrorAction Stop -ResourceGroupName $ResourceGroup | Where-Object { $_.Tags.ContainsKey("InstallMode") } | ForEach-Object { [PSCustomObject]@{ VmId = $_.Id Name = $_.Name Location = $_.Location VmSize = $_.HardwareProfile.VmSize OsType = $_.StorageProfile.OsDisk.OsType Zone = ($_.Zones[0]) Publisher = $_.StorageProfile.ImageReference.Publisher Offer = $_.StorageProfile.ImageReference.Offer Sku = $_.StorageProfile.ImageReference.Sku Version = $_.StorageProfile.ImageReference.Version NIC = $_.NetworkProfile.NetworkInterfaces.id StorageAccountType = $_.StorageProfile.OsDisk.ManagedDisk.StorageAccountType Disk = $_.StorageProfile.OsDisk.Name Tags = $_.Tags } } ) return , $vms } function CheckIfDetailedLoggingAlreadyEnabled { if ($resource.Tags.ContainsKey("EnableDetailedMonitoring")) { $enableDetailedMonitoring = [System.Convert]::ToBoolean($resource.Tags["EnableDetailedMonitoring"]) if ($enableDetailedMonitoring) { throw "Detailed monitoring is already enabled" } } } function EnableDetailedMonitoring { InstallMonitoringResources InstallMonitoringOnVm } function AddTagToVm { foreach ($vm in $vms) { $vm.Tags["EnabledMonitoring"] = $true Update-AzTag -ResourceId $vm.VmId -Tag $vm.Tags -Operation Merge | Out-Null } } function InstallMonitoringResources { Install-NcAzMonitoringResources -ResourceGroupName $nc_resource_group } function InstallMonitoringOnVm { if ($EnableDetailedMonitoring) { foreach ($vm in $arrayList) { Install-NcAzMonitoringOnVM -ResourceGroupName $nc_resource_group -VmName $vm } } } function ExceuteCommand { GetResourceGroup CheckIfDetailedLoggingAlreadyEnabled GetUploadedVms -ResourceGroup $($resource.ResourceGroupName) EnableDetailedMonitoring } try { if (-not (Get-AzContext)) { Connect-AzAccount if (Get-AzContext) { ExecuteCommands } } else { ExecuteCommands } } catch { Write-Error $($_.Exception.Message) } |