Keep specific log analytics workspace and Remove any other - azure

I have loads of migrated VMs which have got multiple Azure log analytic workspaces tagged/configured at VM level.
So what if I don't want to delete the LAW IDs configured at VM level (not in Azure portal) by giving the definite list as I don't have a pre-known list of those multiple LAW rather just keep needed one by matching it within list and delete rest. I don't find an option to do so in documentation! Only looking for doing this via powershell script
Thanks in advance!
By using a powershell script on Azure Doc. we are able to delete multiple LAW Ids by enlisting them, but then there are so many Vms and tenants that it is not possible to keep doing it like this.

After reproducing from my end, I could able to achieve your requirement using the below script.
$AllLaws=Get-AzureRmOperationalInsightsWorkspace
$Requiredlaws = "<Your_Required_LAW_1>","<Your_Required_LAW_2>"...
foreach($law in $AllLaws)
{
if($law.Name -NotIn $Requiredlaws)
{
Remove-AzOperationalInsightsWorkspace -ResourceGroupName $law.ResourceGroupName -Name $law.Name
}
}
RESULTS:

Related

How to delete resources of an Azure subscription level deployment

Is there a recommended and deterministic way to delete resources created by a subscription level deployment ?
So far I see a straightforward way only when the subscription level deployment contains a single resource group. In that case deleting the RG will correctly delete all the resources.
However, if there are several RG-s created by the subscription level deployment, the order of deleting them should be driven by dependency order, and discovering that is not easy.
Further on, the subscription level deployment may create other resources as well, listed here.
I could not find any good method for that so far.
Azure don't have any way to delete the resources that were deployed at subscription level deployment directly.
Alternative way that you can look for
Deployments-Get API will give you the resource ids that were deployed as part of deployment.
GET https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}?api-version=2021-04-01
collect all the resource ids from (1)
Use 'Resources - Delete By Id' API to delete resource ids (from 2)
DELETE https://management.azure.com/{resourceId}?api-version=2021-04-01
You can use above approach/logic to build a script or a piece of code to automate whole process.
The resources are generally stored in the order they were deployed. For example, the array of resources in the deployment object would be in the order the resources were deployed. If you delete the resources in the reverse order, This could prevent the deletion from failing.
As stated in the other answer, you can get the deployment, get the resources, reverse the order of the resources, and then delete them by their ID. This is not a foolproof method but it would work in many cases.
For example, here is a bash script that will delete all resources deployed in a subscription level deployment that has name 'deploymentName'. The array of resources is reversed, thus the resources are deleted in the reverse order that they were created (i.e. the last resource created is the first one deleted):
az deployment sub list --query "[? name=='deploymentName'].properties.outputResources[::-1].id" --output tsv | tr $'\t' $'\n' | xargs -d $'\n' -otl az resource delete --ids

[Azure Terraform]: Create Start/Stop VM Solution

I am using Terraform to create an Automation Account in Azure.
The following resource in Azure provider does the job: azurerm_automation_account.
Ok. So I got my AA created... here is when problems arise.
"Run As" account: there seems to be a way to create it from Terraform... but the process is cumbersome. I have lost hope, and will probably resort to enable it manually from Azure portal (it is just one click)... but it will brake my automation pipeline :(
"Start/Stop VM Solution": I need the powershell runbooks in this solution to start-stop VMs according to a given schedule. There is a resource in Azure provider called "azurerm_automation_runbook". It has 2 useful arguments to reference runbook scripts:
"content": with it I could "load" a local powershell script content. I know this would work (I could manually download the .ps1 script used by "Start/Stop VM Solution" and use "content" to load it), but I would be missing any fixes/updates made by Microsoft in its code)
"publish_content_link": by which I could point to the URI of a given powershell runbook. I have looked in the "Runbook Gallery" for the runbooks contained in the "Start/Stop VM Solution" (not found them). Anyone had any luck with this? A different approach could be to "create" the "Start/Stop VM Solution" from a Terraform script (this will automatically populate the desired runbooks in my Automation Account)... but not sure if this would be possible.
Thanks in advance.
For point 1: I also found it very challenging and while things have improved lately, there still doesn't seem to be an easy, straight forward way of creating the Run As Account. I eventually resorted to creating it manually from the Azure Portal but below are potential areas you can explore:
I'm not sure if you've considered using the external data source from terraform to execute the Powershell script from Microsoft. It's still a pain because of the last step where you have to authenticate manually, but it still brings you closer to having a blueprint of your environment. Although I'm not sure how it would behave if running this Terraform script a second time.
For point 2: Could you confirm that the script you want to use is a Powershell script and not a Powershell Workflow script? Also could you please elaborate on this approach (I have a feeling that might be the best approach):
A different approach could be to "create" the "Start/Stop VM Solution" from a Terraform script (this will automatically populate the desired runbooks in my Automation Account)
If you look at the Runbooks Gallery, you'll see most of these Powershell scripts have not been updated for many years and are still working fine. If this will be used in a production environment, it would be better if you have control over the changes and update then at your convenience. If you want to get the URI, you can just click on 'View Source Project' and it will lead you to the GitHub repo. E.g. for the Runbook Stop-Start-AzureVM (Scheduled VM Shutdown/Startup).
You'll also notice most of the scripts is submitted by external parties. If you link to a URI that's maintained by someone else and that person publishes malicious code in there or even accidentally messes up the code, it's not desirable. But again I'm not sure as to the extent of your automation (e.g. if you expect to execute the terraform script once a month to ensure the Runbook is up to date)
If I get the scripts from somewhere, I'll validate it prior to using them in my environment.
data "local_file" "start_vm_parallel" {
filename = "./scripts/start-vm-parallel.ps1"
}
resource "azurerm_automation_runbook" "start_vm_parallel" {
name = local.NAME
location = local.REGION
resource_group_name = local.RG
automation_account_name = azurerm_automation_account.automation_prod.name
log_verbose = "true"
log_progress = "true"
description = "This runbook starts VMs in parallel based on a matching tag value"
runbook_type = "PowerShellWorkflow"
content = data.local_file.start_vm_parallel.content
publish_content_link {
uri = "https://path.to.script/script.ps1"
}
}
If you're using a Powershell Workflow, you need to make sure that the Runbook name matches the workflow name inside the script.
One last thing to remember before you even start using your Runbooks, is to update the modules by creating a 'modules update' Runbook from the Azure Automation team and running it on schedule, once a month.

Azure RM Powershell find a particular file in all Resource Groups or App Services

Background
Currently we are trying to trace the environment of a particular static site. (URL, Repo, Resource Group, etc.)
Question
Is there an existing cmdlet or aparticular way
to find a particular file in all our available Resource Groups or App Services?
For example, in all resource groups, find particularfile.html
What we've tried
We first tried to identify the location of our file by trying to identify here
At first we tried to identify all urls of all our sites by running the following command : Get-AzureRmWebApp | foreach-object {$_} | select-object SiteName, DefaultHostName, ResourceGroup
While we were able to get the urls, we realized that some redirected to different urls and was thus inaccurate. We still can't tell which resource group has our site..
so we are trying the approach where we look for the file itself. We know that particularfile.html itself exists in one of the resource groups or App Services.
Is there a command for it? or another approach to get the exact location of that file?
If you're just trying to look around, and see the various directories and files in your deployment, you can enter the site's "Kudu" dashboard, using the url format http://.scm.azurewebsites.net
This will give you a web-based dashboard, including a debug console (web-based) where you can explore your various directories (and the directories will show up visually as well).
you can check here for further information.

How to get the creation date of Azure RM Resources including all resources from Azure

I need to use the command Get-AzureRMResource and return resources created after a particular date . Is it possible to filter the resources w.r.t creation date. Can someone please help?
The Get-AzureRMResource could not get the creation date of Azure RM Resources. It seems there is no other way to get the creation date except the Activity log.
But still it can return only the items created on past 90 days.
For this issue, you could try to Archive the Azure Activity Log, this option is useful if you would like to retain your Activity Log longer than 90 days (with full control over the retention policy) for audit, static analysis, or backup.
Update:
If you want to get resources created after a particular date, try the command below, it returns the resources created after 11/20/2018 1:57:19 AM.
Get-AzureRmResourceGroupDeployment -ResourceGroupName "<ResourceGroupName>" | Where-Object {$_.Timestamp -gt '11/20/2018 1:57:19 AM'}
This information is available via ARM, but you have to call the API directly rather than the PS Get-AzureRMResource (or Get-AzResource) cmdlets.
See Deleting all resources in an Azure Resource Group with age more than x days.
Essentially, you need to add the $expand=createdTime to your query parameters, ie.:
GET
https://management.azure.com/subscriptions/1237f4d2-3dce-4b96-ad95-677f764e7123/resourcegroups?api-version=2019-08-01&%24expand=createdTime
Like #kwill suggested, this site can also help run the command interactively via your browser and return these results for you:
https://learn.microsoft.com/en-us/rest/api/resources/resources/list#code-try-0
Steps below:
Click on the try it now button
Enter your subscription ID
For a key value name use: $expand
For the key value value use: createdTime
Then run the query and it should produce a JSON file for you
Example

Create an ARM template from an existing Azure object (e.g. a VM or VNET)

Here is what could be a dumb question but being somewhat new to Azure.
I created a virtual network and a number of RM/ARM virtual machines using the new portal. I have a gateway with two site-to-site connections. Now I discover (at least this is my perception at this time) that the certificate information needed for point-to-site capability can only be supplied when creating the network. I would also like to adjust the sub net sizes.
I think what this means is that I have to delete everything but the VHD files recreate the virtual network (providing the certificate, etc.) and then recreate the connections and VMs. It's a lot more work than I care to do in the portal (I keep dosing off waiting for things to finish, one-at-a-time). So here is the question.
Is there a tool or technique that can be used to create templates using existing Azure resources as input so that the resulting template can be used to easily restore the resources after deletion?
Any help you might offer would be greatly appreciated...
P.S. Before you bring it up, I know about azure quick start templates but flawlessly keying in parameters is not something I do well.
Fortunately, there is!
Check out this:
http://capturegroup.azurewebsites.net
It takes a snapshot of an existing setup, and produces an ARM template :)
There is also a different tool that allows you to visually construct ARM templates, and then download them. It comes with a bunch of pre-configured templates for good measure too:
http://Armviz.io
Hope either of these helps you :)
You can export ARM templates from the Portal or PowerShell:
Export-AzureRmResourceGroup -ResourceGroupName <String> [-Path <String>] [-IncludeParameterDefaultValue [<SwitchParameter>]] [-IncludeComments [<SwitchParameter>]]
See https://azure.microsoft.com/en-us/blog/export-template/
Try https://resources.azure.com/. It should take the same credentials as the account you're using with Azure. You Expand the trees in the left-hand portion of the window to find the specific item you want to view. In your case, it's probably one of the following:
Subscriptions -> your subscription name -> providers -> Microsoft.Network -> virtualnetworks
Subscriptions -> your subscription name -> resourceGroups -> your resource group -> providers -> Microsoft.Network -> virtualnetworks -> your virtual network
Once you find the item you are interested in, you should see the JSON data on the right side of the screen. There are tabs above the URL, try selecting them to familiarize yourself with the different sets of information available. I usually find the Data tab to be pretty useful, but if I'm working in powershell, then selecting the PowerShell tab can be very useful.

Resources