Posted on Leave a comment

Find resource groups that contain tags on Azure using az cli

Sometimes you may need to massively search for resource groups or resources on Azure that have tags set. For example you may have some tags like temp resource that you want to delete with cron jobs. I myself wanted such a script and the first thing to do was to ask chatGPT about this. Although the provided answer is a good starting point I wanted a version that will bring all the resources that have a tag, and not a specific tag. I was searching for tags in general and not for a specific tag.

For such case I created my own script using az cli. In order to use it you will need to first login inside azure with your credentials.

az login

and then set your subscription

az account set --subscription "ID"

The script which brings resource-groups with tags can be found below.

$rgroups = az group list | ConvertFrom-Json
Write-Host Total Resource groups: $rgroups.Count  

$tags = @()
foreach ($item in $rgroups)
{
 if ( -not [string]::IsNullOrEmpty($item.tags)  ) { $tags+= $item } 
}
Write-Host Resource groups with Tags: $tags.Count  

echo $tags

When you run the script you can get the total number of resource groups and the ones that contain tags. You can then use the tags object to loop through the items with tags.

You can use the same logic to find also resources with tags inside an azure subscription

$resources = az resource list | ConvertFrom-Json
Write-Host Total Resources: $resources.Count  

$tags = @()
foreach ($item in $resources)
{
 if ( -not [string]::IsNullOrEmpty($item.tags)  ) { $tags+= $item } 
}
Write-Host Resources with Tags: $tags.Count  

echo $tags

Youtube video:

Posted on Leave a comment

Monitoring Windows service on Azure with Event Viewer and Log Analytics

A Log Analytics workspace is a unique environment for log data from Azure Monitor and other Azure services, such as Microsoft Sentinel and Microsoft Defender for Cloud. Expect from that it can be used also for monitoring combined with Azure alerts given that you create the appropriate query.

The below query can be used to monitor a windows server service by querying log analytics. In more detail it searches for eventID=7036 which indicates the service stopped status.

Query code in Kusto language will return the service name, state and time of the event.

Event
| where TimeGenerated >ago(1h)
| where EventLog  == "System" and EventID ==7036 and Source == "Service Control Manager" 
| parse kind=relaxed EventData with * '<Data Name="param1">' Windows_Service_Name '</Data><Data Name="param2">' Windows_Service_State '</Data>'*
| sort by TimeGenerated desc
| where Windows_Service_Name startswith "Docker Desktop" and Windows_Service_State contains "stopped"
| project Computer, Windows_Service_Name, Windows_Service_State, TimeGenerated

You can use the above query to create a azure alert when a service is found as stopped. As I want to monitor the Docker Desktop service, I will need to use that in the where clause of the query where Windows_Service_Name. The alert logic should indicate when a result is returned as a row in a given timeframe then an alert should be generated. This happens because a row is returned only when the event is captured on the event viewer. This means that the service stopped during the TimeGenerated interval of the query. The frequency of evaluation will be the time on which we want to repeat the log analytics query. For example if we need to search every 5 minutes for a stopped service then we should add 5 minutes there.

Finally the alert will be triggered and inform you about windows stopped services.

Posted on Leave a comment

Inherit tags on Azure resources

Tags are metadata elements that you apply to your Azure resources. They’re key-value pairs that help you identify resources based on settings that are relevant to your organization. For example, If you want to track the deployment environment for your resources, add a key named Environment.

Tag names are case-insensitive for operations. A tag with a tag name, regardless of the casing, is updated or retrieved.

Although tags are very useful for categorization and help quickly identify the resource existence, many forget to use them and resources remain untagged. For this reason one can apply an inherit policy for resources so that tags automatically filled. For example you can append a tag on your subscription and create a policy to inherit this tag on resource groups if it is not added during the creation. Additionally you can create a policy to inherit tags on resources from resource groups. The second scenario will be examined below.

First you should need to create a new policy under Azure policy

You can press on an existing policy and create a duplication definition

Then you should select the Definition location that will be your subscription and then you should edit the Policy Rule. You can leave the policy as it is and change only the displayName of the tag. This policy will inherit the Team tag from the resource group on resources.

{
  "mode": "Indexed",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "[concat('tags[', parameters('tagName'), ']')]",
          "notEquals": "[resourceGroup().tags[parameters('tagName')]]"
        },
        {
          "value": "[resourceGroup().tags[parameters('tagName')]]",
          "notEquals": ""
        }
      ]
    },
    "then": {
      "effect": "modify",
      "details": {
        "roleDefinitionIds": [
          "/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
        ],
        "operations": [
          {
            "operation": "addOrReplace",
            "field": "[concat('tags[', parameters('tagName'), ']')]",
            "value": "[resourceGroup().tags[parameters('tagName')]]"
          }
        ]
      }
    }
  },
  "parameters": {
    "tagName": {
      "type": "String",
      "metadata": {
        "displayName": "Team",
        "description": "example: DevOps"
      }
    }
  }
}

You can read more about Azure policies in the below documentation link.

https://learn.microsoft.com/en-us/azure/governance/policy/samples/

Then you should save the policy and go on assignments to assign it on a particular resource.

In the policy assignment you can exclude components that will override the policy. Additionally you can specify a resource group instead of the whole subscription.

The important part would be to provide the Tag Name. This would be the parameter on which you will perform the actions. As we specified that we want the Team tag to be inherited then we will give this as an input.

When you apply tags on resources, you add some metadata on them as a result you will need to have contributor role. When we specify this action automatically, we will need a service principal that will do the job. We can select one automatically using managed identity from the remediation tab of the policy creation.

Finally we can create our assignment and try what we created. I have a test resource group with the tag Team inside my subscription.

When I need to create a new resource under the resource group, this should automatically inherit the tag Team. In order to test I will create a Log Analytics workspace without Tags on the resource group.

we can notice that after the creation this resource will have the tag Team automatically filled.

Posted on Leave a comment

Curl slack webhook with powershell

The below powershell can be used to trigger a webhook URL for slack. Inside the powershell you can dynamically get variables from powershell using the json notation that is used.

$json = @"
{
    "text": "I am inside $($Env:ComputerName)"
}
"@


if (-not((Get-Service -Name "Appinfo").Status -eq "Running") -or -not((Get-Service -Name "Dhcp").Status -eq "Running")) 
{ 
curl -X POST -H 'Content-type: application/json' --data $json https://hooks.slack.com/services/XXXX/XXXX/XXXX 
}