Disconnect an Azure VM from a loganalytics workspace - azure

i'm looking for a powershell way to disconnect a virtual machine from an OMS workspace.
I wrote a powershell script to move a VM to an other subscription. So i have to re-connect this VM from 'source workspace' to 'destination workspace'.
Just removing OMS extension show me the virtual machine as "Not connected" into Azure portal "Log Analytics workspace >Workspace Data Sources>Virtual machines".
This cmdlet should do the tricks (the doc is not really clear), but i always have the same message
remove-AzureRmOperationalInsightsDataSource -Workspace $OmsWkspceITS -Name CentosMove
Confirm
Are you sure you want to remove data source 'CentosMove' in workspace 'itsoms'?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Yes"): yes
WARNING: DataSource 'CentosMove' does not exist in workspace 'itsoms'.
(CentosMove is my VM name).
Our ITSOMS workspace is used for years now with hundred of VM, many solutions, NSG logflows analytics,..
$OmsWkspceITS
Name : itsoms
ResourceGroupName : rg_its_exploit
ResourceId : /subscriptions/blablabla/resourcegroups/blabla/providers/microsoft.operationalinsights/workspaces/itsoms
Location : westeurope
Tags :
Sku : standalone
CustomerId : xx
PortalUrl : https://weu.mms.microsoft.com/Accou...
ProvisioningState : Succeeded
The only Datasources i can get with this cmdlet are those like this one
Get-AzureRmOperationalInsightsDataSource -WorkspaceName $OmsWkspceITS.Name -ResourceGroupName $OmsWkspceITS.ResourceGroupName -Name DataSource_LinuxSyslog_syslog
Name : DataSource_LinuxSyslog_syslog
ResourceGroupName : rg_its_exploit
WorkspaceName : itsoms
ResourceId : /subscriptions/xx/resourceGroups/rg_its_exploit/providers/Microsoft.OperationalInsights/workspaces/itsoms/datasources/DataSource_LinuxSyslog_syslog
Kind : LinuxSyslog
Properties : {"syslogName":"syslog".....}
I'm maybe not looking at the right cmdlet i think ...
Thanks for your help :)

To accomplish your requirement use cmdlets Remove-AzureRmVMExtension and Set-AzureRmVMExtension.
For illustration check below commands.
To disconnect Linux VM agent:
Remove-AzureRmVMExtension -ResourceGroupName RESOURCEGROUPNAME -VMName VMNAME -Name ‘OmsAgentForLinux’
To disconnect Windows VM agent:
Remove-AzureRmVMExtension -ResourceGroupName RESOURCEGROUPNAME -VMName VMNAME -Name ‘MicrosoftMonitoringAgent’
To connect Linux VM agent to a Log Analytics workspace:
$WorkspaceID = "xxxxxxxxxxxxxxxxxxxxxxxxx"
$WorkspaceKey = "xxxxxxxxxxxxxxxxxxxxxxxx"
Set-AzureRmVMExtension -ResourceGroupName RESOURCEGROUPNAME -VMName VMNAME -Name ‘OmsAgentForLinux’ -Publisher ‘Microsoft.EnterpriseCloud.Monitoring’ -ExtensionType ‘OmsAgentForLinux’ -TypeHandlerVersion ‘1.0’ -Location 'LOCATION' -SettingString "{‘workspaceId’: ‘$WorkspaceID’}" -ProtectedSettingString "{‘workspaceKey’: ‘$WorkspaceKey’}"
To connect Windows VM agent to a Log Analytics workspace:
$WorkspaceID = "xxxxxxxxxxxxxxxxxxxxxxxxx"
$WorkspaceKey = "xxxxxxxxxxxxxxxxxxxxxxxx"
Set-AzureRmVMExtension -ResourceGroupName RESOURCEGROUPNAME -VMName VMNAME -Name ‘MicrosoftMonitoringAgent’ -Publisher ‘Microsoft.EnterpriseCloud.Monitoring’ -ExtensionType ‘MicrosoftMonitoringAgent’ -TypeHandlerVersion ‘1.0’ -Location 'LOCATION' -SettingString "{‘workspaceId’: ‘$WorkspaceID’}" -ProtectedSettingString "{‘workspaceKey’: ‘$WorkspaceKey’}"
Hope this helps!! Cheers!! :)

Related

Azure VM templates

So, I exported a VM template and I'm trying to build more VMs based on that template.
How can I define the subscription, resource group and region in the template or in the parameters file?
You can use Azure Powershell to Deploy Virtual Machine, I have reproduced in my environment and followed Microsoft-Document :
Firstly if you donot have a resourcegroup create it using below cmdllet:
New-AzResourceGroup -Name 'rithwik' -Location 'EastUS'
(rithwik- Resourcegroup name)
Then you need to try below cmdlet for deploying VM:
New-AzVm `
-ResourceGroupName 'myResourceGroup' `
-Name 'myVM' `
-Location 'East US' `
-VirtualNetworkName 'myVnet' `
-SubnetName 'mySubnet' `
-SecurityGroupName 'myNetworkSecurityGroup' `
-PublicIpAddressName 'myPublicIpAddress' `
-OpenPorts 80,3389
After giving the command type your username and password as below:
Output:
References of Code taken from:
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-powershell#code-try-1
In Portal:

How to create a Linux AppService Plan with New-AzAppServicePlan?

What is the equivalient of this code using New-AzAppServicePlan?
az appservice plan create --resource-group $ServerFarmResourceGroupName `
--name $AppServicePlanName `
--is-linux `
--location $ResourceGroupLocation `
--sku $AppServicePlanTier `
--number-of-workers $NumberOfWorkers
Is there really no way to create an App Service Plan using Az Powershell? Why can it only be done via Azure CLI or ARM?
I only found this answer, which basically uses ARM directly: How do I use Powershell to create an Azure Web App that runs on Linux?
There are some issues about this, suppose for now this is not supported for New-AzureRmAppServicePlan, however you could use New-AzureRmResource to create a linux plan. You could try the below command.
New-AzureRmResource -ResourceGroupName <>group name -Location "Central US" -ResourceType microsoft.web/serverfarms -ResourceName <plan name> -kind linux -Properties #{reserved="true"} -Sku #{name="S1";tier="Standard"; size="S1"; family="S"; capacity="1"} -Force
I originally used my script to create a ConsumptionPlan (Y1) through PowerShell and AzureCLI because I don't like when Azure put a generated name when creating a ConsumptionPlan.
Please find my solution to create a Linux App Service Plan (B1) using New-AzResource:
$fullObject = #{
location = "West Europe"
sku = #{
name = "B1"
tier = "Basic"
}
kind = "linux"
properties = #{
reserved = $true
}
}
$resourceGroupName = "rg-AppServicePlanLinux"
$serverFarmName = "aspl-test"
Write-Host "Step 1: CREATING APP SERVICE PLAN B1:Basic named [$serverFarmName]"
# Create a server farm which will host the function app in the resource group specified
New-AzResource -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.Web/serverfarms" -Name $serverFarmName -IsFullObject -PropertyObject $fullObject -Force
So I used the ARM template to understand which information you need to provide on the -PropertyObject parameter
It also now seems possible to do an App Service Plan Linux with New-AzAppServicePlan command since Az PowerShell 4.3.0 (June 2020) with the parameter -Linux
Az.Websites
Added safeguard to delete created webapp if restore failed in 'Restore-AzDeletedWebApp'
Added 'SourceWebApp.Location' for 'New-AzWebApp' and 'New-AzWebAppSlot'
Fixed bug that prevented changing Container settings in 'Set-AzWebApp' and 'Set-AzWebAppSlot'
Fixed bug to get SiteConfig when -Name is not given for Get-AzWebApp
Added a support to create ASP for Linux Apps
Added exceptions for clone across resource groups
Release Note: https://learn.microsoft.com/en-us/powershell/azure/release-notes-azureps?view=azps-5.6.0&viewFallbackFrom=azps-4.3.0#azwebsites-7
New-AzAppServicePlan: https://learn.microsoft.com/en-us/powershell/module/az.websites/new-azappserviceplan?view=azps-5.6.0
If you get "The Service is unavailable" after deploying your new Function app (Consumption Plan) with Azure CLI, please make sure the following statement from Microsoft:
https://github.com/Azure/Azure-Functions/wiki/Creating-Function-Apps-in-an-existing-Resource-Group
I waste the whole day because I got another Function App (Premium Plan) in the same resource group I used to deploy the Consumption one.
This worked for me:
Adding -Linux as a parameter to my command
New-AzAppServicePlan -ResourceGroupName $RESOURCE_GROUP_NAME -Name $APP_SERVICE_PLAN_NAME -Location $RESOURCE_LOCATION -Linux -Tier $APP_SERVICE_PLAN_TIER -NumberofWorkers $APP_SERVICE_PLAN_WORKERS -WorkerSize $APP_SERVICE_PLAN_WORKER_SIZE
Example:
New-AzAppServicePlan -ResourceGroupName 'MyResourceGroup' -Name 'MyServicePlan' -Location 'northeurope' -Linux -Tier 'PremiumV2' -NumberofWorkers 2 -WorkerSize Medium
That's all.
I hope this helps

How can you upgrade Azure Upgrade A-Series VM to D-Series VM?

The most recent information I could find while scouring the net was a post 6 months old (back toward the original deployment of D-Series servers). How can you seamlessly upgrade an A-Series Azure VM to a D-Series Azure VM without a huge headache?
To find out what sizes are available in your Region (and see the InstanceSize naming sceheme to use in Powershell) use this PowerShell Cmdlet:
Get-AzureLocation | Where-Object {$_.DisplayName.Contains("<your-region>")}
View the VirtualMachineRoleSizes property to see what sizes you have access to.
To update a VM you can use the following set of commands:
Get-AzureVM -ServiceName <cloudservice> -Name <vmname> | Set-AzureVMSize -InstanceSize <sizevalue> | Update-AzureVM
If you run the above command on a running VM it will be restarted in order to provision it on the right host infrastructure to support your desired Series.
# To Upgrade or downgrade your Azure VM Plan you can use the following script
$ResourceGroupName = "CMLAB"
$VMName = "2007CMCEN"
$NewVMSize = "Standard_A5"
$vm = Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VMName
$vm.HardwareProfile.vmSize = $NewVMSize
Update-AzureRmVM -ResourceGroupName $ResourceGroupName -VM $vm

Error creating web app slot with Azure Powershell cmdlet

I can successfully create a new Azure Web App with this command (provided the resource group and app service plan exist, of course):
New-AzureWebApp `
-Name site-name `
-ResourceGroupName resource-group-name `
-Location 'North Central US' `
-AppServicePlan app-service-plan-name
But when I try to add a slot with a similar command it fails:
New-AzureWebApp `
-Name site-name `
-ResourceGroupName resource-group-name `
-Location 'North Central US' `
-AppServicePlan app-service-plan-name `
-SlotName dev # <--------------------------- this line is added
with the error:
New-AzureWebApp : MismatchingResourceName: The provided resource name 'site-name'
did not match the name in the Url 'site-name/dev'.
At line:1 char:1
+ New-AzureWebApp -SlotName "dev" -Name "site-name" -Location "North ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureWebApp], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.WebApp.Cmdlets.NewAzureWebAppCmdlet
What's going on here? Am I not going about making slots the right way?
Note: I'm using Azure Powershell in AzureResourceManager mode.
This AzureServiceManagement mode command does work so I'm not entirely lost:
New-AzureWebsite -Name "site-name" -Slot "dev" -Location "North Central US"
But why can't I get the former command to work?
What is your App Service plan mode? I hope this is already been taken care, and you should be in either Standard or Premium plan.
This seems to be a issue with the latest release of Azure modules. Will have to wait till the issue is fixed. Probably you might need to raise a Azure Support ticket to bump up the priority.

azure failed to add extension to virtual machine

I am trying to add the Antimalware extension to a virtual machine for protection but when i try to add the extension in the Azure portal i get the following error:
Failed to add extension to virtual machine. The virtual machine request is invalid The specified source image is a user image. The image must be a platform image.
I have installed the VMAgent.
As extra information i have tried using powershell commands to install the extension by using the following commands and getting the respective responses:
$vm = Get-AzureVM –ServiceName "MyServiceName" –Name "MyVMName"
VERBOSE: ... - completed operation: Get Deployment*
Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM
WARNING: The resource extension reference list is null or empty
AvailabilitySetName :
ConfigurationSets : {Microsoft.WindowsAzure.Commands.ServiceManagement.Model.NetworkConfigurationSet}
DataVirtualHardDisks : {"MyVMName"}
Label :
OSVirtualHardDisk : Microsoft.WindowsAzure.Commands.ServiceManagement.Model.OSVirtualHardDisk
RoleName : "MyVMName"
RoleSize : Large
RoleType : PersistentVMRole
WinRMCertificate :
X509Certificates :
NoExportPrivateKey : False
NoRDPEndpoint : False
NoSSHEndpoint : False
DefaultWinRmCertificateThumbprint : F4CF28C735C5E557C7B47742E4F16A08959272F1
ProvisionGuestAgent :
ResourceExtensionReferences : {IaaSAntimalware}
DataVirtualHardDisksToBeDeleted :
Update-AzureVM -Name "MyServiceName" -ServiceName "MyVMName" -VM $vm.VM
VERBOSE: 11:15:10 - Completed Operation: Get Deployment
VERBOSE: 11:15:10 - Begin Operation: Update-AzureVM
VERBOSE: 11:15:42 - Completed Operation: Update-AzureVM
OperationDescription OperationId OperationStatus
-------------------- ----------- ---------------
Update-AzureVM 387b77a2-c8fc-233a-913d-cd364c855429 Succeeded
After i run the commands i check and VMAgent is installed on the VM but no extension.
Does anyone have any ideas?
Thanks!!
The cause might be your first line
$vm = Get-AzureVM –ServiceName "MyServiceName" –Name "MyVMName"
When -servicename and -name are not specified, Get-AzureVM returns no VM object
Set-AzureVMextension only works with -VM input
Try this:
https://gist.github.com/andreaswasita/428fc5519b0ddac76b01
In my experience, this warning is due to the Azure Guest agent not being deployed on the VM, not running on the VM, or being out-of-date. If the VM doesn't have a healthy (and current) guest agent, you won't be able to deploy extensions.
You can check the guest agent status with:
$vm.GuestAgentStatus
You'd be looking for a "Status" of "Ready"; anything else and the extension is likely to fail. Extending Klaad's code then...
# Azure Cloud Service and Azure VM Name
$service= Read-Host -Prompt 'Azure Cloud Service:'
$name = Read-Host -Prompt 'Azure VM:'
# Get the Cloud Service and Azure VM
$vm = Get-AzureVM –ServiceName $service –Name $name
# Check for health of the agent
If ($vm.GuestAgentStatus.Status -ne "Ready") {
Write-Error "The VM agent appears to not be installed or is in an unhealthy state."
}
Else {
# Add Microsoft Antimalware Agent to the Azure VM
Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM
# Update the Azure VM and install the Antimalware Agent
Update-AzureVM -Name $name -ServiceName $service -VM $vm.VM
}
To check if the agent is there, you can look for the following three processes on the server:
WaAppAgent.exe
WindowsAzureGuestAgent.exe
WindowsAzureTelemetryService.exe
You can download the agent from here (current version at time of edit is 2.6.1198.718).
Installation requires two steps (Source: Zach Millis):
Install the agent. This requires you to run PowerShell as an Administrator and execute the installer from within the PowerShell prompt. (Do not run directly)
Update Azure so it knows about the agent. This requires the following code to be executed:
Code:
# Azure Cloud Service and Azure VM Name
$service= Read-Host -Prompt 'Azure Cloud Service:'
$name = Read-Host -Prompt 'Azure VM:'
# Get the Cloud Service and Azure VM
$vm = Get-AzureVM –ServiceName $service –Name $name
# Provision the guest agent so Azure knows about it
$vm.VM.ProvisionGuestAgent = $TRUE
# Update the Azure VM and install the Antimalware Agent
$vm | Update-AzureVM
# Refresh the connection to the VM to get the new status
$vm = Get-AzureVM –ServiceName $service –Name $name
# Check status - should now be "Ready"
$vm.GuestAgentStatus
That should be it.

Resources