Why Not? Logic Apps + Home Assistant to Automate Your Cats Treat Dispenser

Alright, buckle up, folks – we’re diving into the absurd side of automation. Sure, Home Assistant can make your home smarter, but what if it could make your cat happier and financially savvy? Let’s build a system that dispenses treats based on stock market performance. Because why not tie your feline friend’s snack schedule to the whims of Wall Street?

This is overkill. It’s ridiculous. It’s everything you didn’t know you needed.

The Plan: Cats, Treats, and Capitalism

Here’s what we’re doing:

  1. Stock Price Check – Use Azure Logic Apps to pull daily stock prices for your favorite company (or your cat’s favorite, obviously). I prefer something like Alpha Vantage – it’s got a free tier and it’s easy to setup. https://www.alphavantage.co/
  2. Treat Dispensing Logic – Determine whether the stock is up or down and decide if treats should rain upon your furry roomate.
  3. Home Assistant Integration – Trigger a smart treat dispenser via a webhook.

Let’s get started!

If you don’t have a smart treat dispenser, DIY it. A smart plug attached to a motorized dispenser (or a cheap automatic feeder) works perfectly. I prefer these TPLink Matter Plugs. Connect it to Home Assistant and set up an automation:

alias: "Dispense Treats"
trigger:
  - platform: webhook
    webhook_id: "dispense_treats"
action:
  - service: switch.turn_on
    target:
      entity_id: switch.treat_dispenser
  - delay: "00:00:05"  # Dispense treats for 5 seconds
  - service: switch.turn_off
    target:
      entity_id: switch.treat_dispenser

Make sure you note the “webhook_id” – you will need it soon.

Create the Logic App

In Azure Portal, create a new Logic App (Consumption). Call it something fun, like WallStreetKitty. Add a Reoccurrance Trigger – maybe every 5 minutes or something like that. If you use a different API for the stock prices, make sure you know the number of calls you can make on your pricing tier. These sample below just checks once a day at 5pm (after the market closes).

{
  "recurrence": {
    "frequency": "Day",
    "interval": 1,
    "schedule": {
      "hours": [17],
      "minutes": [0]
    }
  }
}

Fetch Stock Prices

Add an HTTP action to call a stock API (e.g., Alpha Vantage). Example setup:

  1. Method: GET
  2. URI: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=YourAPIKey

Replace MSFT with the ticker symbol of your choice – or your cat’s favorite stock. The actual json you get from Alpha Vantage might be something like this:

{
  "Meta Data": {
    "1. Information": "Intraday (1min) open, high, low, close prices and volume",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2024-05-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2024-05-01 16:00:00": {
      "1. open": "309.6200",
      "2. high": "310.0000",
      "3. low": "309.1500",
      "4. close": "309.9200",
      "5. volume": "1234567"
    },
    "2024-05-01 15:59:00": {
      "1. open": "309.5000",
      "2. high": "309.8000",
      "3. low": "309.1000",
      "4. close": "309.6200",
      "5. volume": "987654"
    }
  }
}

So your next step is to parse the json – add a parse JSON step and use this schema:

{
  "type": "object",
  "properties": {
    "Meta Data": {
      "type": "object",
      "properties": {
        "2. Symbol": { "type": "string" },
        "3. Last Refreshed": { "type": "string" }
      }
    },
    "Time Series (1min)": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "1. open": { "type": "string" },
          "2. high": { "type": "string" },
          "3. low": { "type": "string" },
          "4. close": { "type": "string" },
          "5. volume": { "type": "string" }
        }
      }
    }
  }
}

We want 4 – the CLOSE value. We just need to extract it from the JSON –

@body('Parse_JSON')?['Time Series (1min)']?[body('Parse_JSON')?['Meta Data']?['3. Last Refreshed']]?['4. close']

Now we need to add a condition – we don’t want Tabby to get fat if the stocks aren’t doing well, right??

@greater(float(body('Extract_Stock_Price')),float(variables('Previous_Price')))

If True – continue. If False, well someones going to not be happy. Let’s assume that the stocks are going to do well, so let’s call out to Home Assistant.

Call Home Assistant

In the True branch, add an HTTP action to trigger the treat dispenser:

  1. Method – POST
  2. URI – https://your-homeassistant-instance/api/webhook/<<that webhook id I told you to remember>>. For example – https://your-homeassistant-instance/api/webhook/dispense_treats
  3. Headers – Add your Home Assistant authentication token.

Bonus Round: Go Big or Go Home

  • Track Multiple Stocks – Add a loop to monitor multiple ticker symbols and dispense extra treats for each one in the green.
  • Add Notifications – Send a Teams message or email with the stock performance and treat status.
  • Cat Mood Analytics – Track treat frequency and correlate it with your cat’s nap times in a Power BI dashboard.

Did we need to do this? Nope. Is this useful? Also No. Do I currently have a cat? Also No. Do I have too much time on my hands? I will let you decide.

Why Not? Automating Coffee Break Notifications with Azure Logic Apps

Let’s face it, folks: productivity peaks when caffeine flows. But how often do you lose track of time, only to realize you’ve been glued to your screen without your essential coffee break? Enter Azure Logic Apps, your caffeine accountability buddy.

Yes, we’re automating coffee break reminders. Is it silly? Absolutely. Is it also a fantastic way to show off your Logic Apps skills? You betcha. Let’s build it—with full code, because you deserve it.

The Plan

Here’s what we’re building:

  1. Trigger: The Logic App runs every workday at a specific time.
  2. Check Your Calendar: Ensure you’re not in a meeting during coffee time.
  3. Send a Reminder: Notify yourself to take a break and caffeinate responsibly.

Create the Logic App

First, create a Logic App in the Azure Portal (Consumption Plan) and name it something clever like CoffeeBreakBuddy. We are building a caffeine ally here afterall.


Full Code: Coffee Break Reminder Logic App

Here’s the complete code for your new caffeine buddy in JSON. Save it as a .json file and import it into the Azure Logic Apps designer

{
"definition": {
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
"actions": {
"Check_Calendar": {
"inputs": {
"host": {
"connection": {
"name": "@parameters('$connections')['office365']['connectionId']"
}
},
"method": "get",
"path": "/v2/calendars/me/events",
"queries": {
"$filter": "start/dateTime ge '@{utcNow()}' and start/dateTime lt '@{addMinutes(utcNow(),30)}'"
}
},
"runAfter": {
"Recurrence": [
"Succeeded"
]
},
"type": "ApiConnection"
},
"Condition": {
"actions": {
"Send_Reminder": {
"inputs": {
"body": {
"Content": "It's coffee o'clock! Take a break and enjoy your brew. ☕"
},
"host": {
"connection": {
"name": "@parameters('$connections')['office365']['connectionId']"
}
},
"method": "post",
"path": "/v2/emails",
"headers": {
"Subject": "Coffee Break Reminder"
}
},
"type": "ApiConnection"
}
},
"expression": {
"and": [
{
"equals": [
"@empty(body('Check_Calendar')?['value'])",
true
]
}
]
},
"runAfter": {
"Check_Calendar": [
"Succeeded"
]
},
"type": "If"
}
},
"triggers": {
"Recurrence": {
"recurrence": {
"frequency": "Day",
"interval": 1,
"schedule": {
"hours": [
10
],
"minutes": [
0
]
}
},
"type": "Recurrence"
}
}
},
"parameters": {
"$connections": {
"defaultValue": {},
"type": "Object"
}
}
}

How It Works

Trigger: Recurrence

  • Runs every day at 10:00 AM. Adjust the time in the schedule property under Recurrence.

Check Your Calendar

  • Uses the Office 365 Outlook connector to check for events in the next 30 minutes.

Condition: Is It Coffee Time?

  • If your calendar is empty during the coffee break window, it sends a reminder.
  • If busy, skips the reminder because productivity comes first (sometimes).

Send Reminder

  • Sends an email through the Office 365 connector. You can change this to a Teams message or even a text with Twilio.

How to Deploy

  1. Import the JSON:
    • In the Logic Apps designer, click Import Logic App and upload the JSON file.
  2. Set Up Connections:
    • Add an Office 365 Outlook connection for email and calendar integration.
  3. Save and Run:
    • Save your Logic App and test it by running it manually or waiting for the next scheduled run.

Bonus Ideas

  • Add weather data to suggest iced or hot coffee.
  • Hook up Spotify to start a “Coffee Break” playlist.
  • Track your breaks in Azure Table Storage to analyze your caffeine habits.

Now go forth and caffeinate like a boss. And remember, this isn’t just about coffee—it’s about showing the world that no problem is too small to automate. Cheers!

Azure Communication Services: March 2024 Updates You Need to Know

Alright, folks, buckle up because Azure Communication Services (ACS) just dropped a batch of updates that’ll make your dev life a little smoother and your apps a lot smarter. Whether you’re building chat, voice, or video features, ACS has some shiny new tools to simplify your workflows and impress your users.

Let’s break it down.


Limited Access User Tokens: Now Generally Available

Ever wanted to give your users just enough access to get the job done without opening the floodgates? Meet Limited Access User Tokens. These beauties let you control what users can and can’t do—like joining a call but not starting one.

Think of it like a VIP pass that only gets you into the lounge, not backstage. Perfect for scenarios where security and controlled participation are a must. And yes, it’s available right now for you to play with.


“Try Phone Calling” (Public Preview)

Imagine this: you’re setting up telephony in your app, but you’re not 100% sure the setup actually works. Enter “Try Phone Calling”, now in public preview. This feature lets you make test calls directly from the Azure portal. No code. No app. Just you, a test call, and sweet, sweet confirmation that everything’s running smoothly.

This works with both PSTN (Public Switched Telephone Network) and direct routing setups. It’s like a “Hello, World” for phone calling.


UI Native Library Gets a Boost

The Native UI Library just got a couple of upgrades that’ll make your users love you even more (or at least blame you less when something goes wrong):

  1. User Facing Diagnostics (UFD): Think of this as your app whispering helpful tips to users. Muted mic? Bad network? UFD lets users know in real-time so they can fix issues themselves. No more “I can’t hear you” panic in the middle of a call. It’s available now, so start showing off your polished UX skills.
  2. iOS CallKit Integration: For all the Apple fans out there, ACS now integrates with iOS CallKit (in public preview). Your calls will feel native, with built-in notifications, call history, and even call hold. It’s like giving your app a little iOS magic wand.

PSTN Direct Offers Expanded

PSTN Direct Offers just leveled up with availability in 42 countries. That’s 400+ new cross-country offers, making it easier to integrate phone calling into your app no matter where your users are.

If you’ve been dreaming of adding PSTN calling for global users, this update is basically your green light.


Why These Updates Matter

Azure Communication Services just made it a lot easier to build reliable, secure, and scalable communication features into your apps. From tighter access controls to test calls and diagnostics, these tools are all about making your life easier and your apps better.

You can dive into the nitty-gritty here: Azure Communication Services Updates. Or just fire up the portal and start playing around. You’ll thank yourself later.

Now, go forth and communicate like the app-building rockstar you are.

Running PowerShell from a Logic App

Hola! Today let’s look at a simple way to get PowerShell scripts to run from a Logic App. It will involve a single extra tool, but this really adds versatility to an already versatile tool.

Start by creating a PowerShell script for your specific task. This script will be uploaded to an Azure Automation Runbook. For instance, if you aim to manage VMs, ensure the script includes Azure RM or Az module commands to start, stop, or monitor VM states. Here is an example:

# Sample PowerShell Script to Start a Specific Azure VM
Param(
    [string]$vmName,
    [string]$resourceGroupName
)

Connect-AzAccount -Identity
Start-AzVM -Name $vmName -ResourceGroupName $resourceGroupName

Obviously this is a short script that we can do with just Logic Apps (and not involve pwsh at all), but you get the point.

Now – Upload and publish your PowerShell script in an Azure Automation Runbook.

  1. In your Azure Automation Account, create a new Runbook.
  2. Choose “PowerShell” as the Runbook type.
  3. Import your script and publish the Runbook.

Go ahead test the runbook if you want.

Next – create a Logic App to trigger the Runbook. You might use a schedule, an HTTP request, or another event in Azure as a trigger.

  1. In the Logic App Designer, add a new step and search for the “Azure Automation” connector.
  2. Select “Create job” action.
  3. Fill in the necessary details: Automation Account, Runbook Name, and parameters (if your script requires them). In our example we might dynamically pass the VM name, or maybe look for only VMs that are off and loop through them.

For more complex scenarios, you might need to integrate with other Azure services before or after executing your PowerShell script:

  • Azure Functions: For custom logic that cannot be implemented directly in PowerShell or needs a specific runtime environment.
  • Azure Event Grid: To trigger your Logic App based on events from various Azure services.
  • Azure Monitor: To analyze logs and metrics from your Logic App and Automation Runbooks, enabling proactive management and optimization of your automated tasks.

And there you go! Go put PowerShell everywhere!

Quick Code – Install AMA and Assign a DCR with PowerShell

Happy Holidays! Here’s a quick post to share some code that will inventory Azure VMs, install the AMA if necessary, and then assign a DCR to the VM.

# Ensure you're logged in to Azure
Connect-AzAccount

# Define the Data Collection Rule (DCR) resource ID
$dcrResourceId = "<Your-DCR-Resource-ID>"

# Get all VMs in the subscription
$vms = Get-AzVM

# Use ForEach-Object with -Parallel to process VMs concurrently
$vms | ForEach-Object -Parallel {
    $vm = $_
    $osType = $vm.StorageProfile.OsDisk.OsType
    $extensionName = if ($osType -eq "Windows") { "AzureMonitorWindowsAgent" } else { "AzureMonitorLinuxAgent" }
    $extensionPublisher = "Microsoft.Azure.Monitor"
    $vmResourceId = "/subscriptions/$using:vm.SubscriptionId/resourceGroups/$using:vm.ResourceGroupName/providers/Microsoft.Compute/virtualMachines/$using:vm.Name"

    try {
        # Check if the Azure Monitor Agent extension is installed
        $amaExtension = Get-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -ErrorAction SilentlyContinue

        if (-not $amaExtension) {
            try {
                # Install the Azure Monitor Agent extension
                Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -Publisher $extensionPublisher -ExtensionType $extensionName -TypeHandlerVersion "1.0" -Location $using:vm.Location
                Write-Host "Installed Azure Monitor Agent on $($using:vm.Name)"
            } catch {
                Write-Host "Failed to install Azure Monitor Agent on $($using:vm.Name): $_"
            }
        } else {
            Write-Host "Azure Monitor Agent is already installed on $($using:vm.Name)"
        }
    } catch {
        Write-Host "Error checking Azure Monitor Agent on $($using:vm.Name): $_"
    }

    try {
        # Assign the DCR to the VM
        $settings = @{ "dataCollectionRuleResourceIds" = @($using:dcrResourceId) }
        Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name "AzureMonitorVmExtension" -Publisher $extensionPublisher -ExtensionType $extensionName -Settings $settings -Location $using:vm.Location
        Write-Host "Assigned DCR to $($using:vm.Name)"
    } catch {
        Write-Host "Failed to assign DCR to $($using:vm.Name): $_"
    }
} -ThrottleLimit 5 # Adjust the ThrottleLimit as necessary

Setting up Azure OpenAI with PowerShell

If haven’t been living under a rock, you know that Azure OpenAI is a powerful tool that brings the cutting-edge capabilities of OpenAI’s models to the cloud, offering scalability, reliability, and integration with Azure’s vast ecosystem.

Because I am who I am we will use PowerShell to setup our Azure OpenAI instance. Whether you’re automating deployment or integrating Azure OpenAI into your existing infrastructure, PowerShell scripts can simplify the process. Let’s get started with a step-by-step guide to setting up your Azure OpenAI instance using PowerShell.

Prerequisites

Before we dive into the commands, ensure you have the following:

  • An Azure subscription. If you don’t have one, you can create a free account.
  • PowerShell installed on your system. If you’re on Windows, you’re probably already set. For Mac and Linux users, check out PowerShell Core.
  • The Azure PowerShell module installed. You can install it by running Install-Module -Name Az -AllowClobber -Scope CurrentUser in your PowerShell terminal.

Step 1: Log in to Azure

First things first, let’s log into Azure. Open your PowerShell terminal and run:

Connect-AzAccount

This command opens a login window where you can enter your Azure credentials. Once authenticated, you’re ready to proceed.

Step 2: Create a Resource Group

Azure OpenAI instances need to reside in a resource group, a container that holds related resources for an Azure solution. To create a new resource group, use:

New-AzResourceGroup -Name 'MyResourceGroup' -Location 'EastUS'

Replace 'MyResourceGroup' with your desired resource group name and 'EastUS' with your preferred location.

Step 3: Register the OpenAI Resource Provider

Before deploying Azure OpenAI, ensure your subscription is registered to use the OpenAI resource provider. Register it with:

powershell

Register-AzResourceProvider -ProviderNamespace 'Microsoft.OpenAI'

This command might take a few minutes. To check the status, you can run Get-AzResourceProvider -ProviderNamespace 'Microsoft.OpenAI'.

Step 4: Create an Azure OpenAI Instance

Now, the exciting part—creating your Azure OpenAI instance. Use the following command:

powershell

New-AzResource -ResourceGroupName 'MyResourceGroup' -ResourceType 'Microsoft.OpenAI/workspaces' -Name 'MyOpenAIInstance' -Location 'EastUS' -PropertyObject @{ sku = 'S0'; properties = @{ description = 'My Azure OpenAI instance for cool AI projects'; } }

Make sure to replace 'MyResourceGroup', 'MyOpenAIInstance', and 'EastUS' with your resource group name, desired OpenAI instance name, and location, respectively.

Step 5: Confirm Your Azure OpenAI Instance

To ensure everything went smoothly, you can list all OpenAI instances in your resource group:

powershell

Get-AzResource -ResourceGroupName 'MyResourceGroup' -ResourceType 'Microsoft.OpenAI/workspaces'

This command returns details about the OpenAI instances in your specified resource group, confirming the successful creation of your instance. Enjoy your brand new OpenAI instance!

Quick Dive: Integrating Logic Apps with Azure OpenAI

Let’s cut to the chase: Integrating Azure Logic Apps with Azure OpenAI unlocks a plethora of possibilities, from automating content creation to enhancing data analysis. Below is a step-by-step guide to melding these powerful tools.

Step 1: Set Up Azure OpenAI

First, you need an Azure OpenAI service instance. Go to the Azure Portal, search for Azure OpenAI Service, and create a new instance. Once deployed, grab your API key and endpoint URL from the resource management section.

Step 2: Create Your Logic App

Navigate back to the Azure Portal and create a new Logic App:

  • Choose your subscription and resource group.
  • Pick a region close to you for lower latency.
  • Name your Logic App.
  • Click “Review + create” and then “Create” after validation passes.

Step 3: Design Your Logic App Workflow

Once your Logic App is ready, it’s time to design the workflow:

  • Open your Logic App in the Azure Portal and go to the Logic App Designer.
  • Start with a common trigger like “When an HTTP request is received” if you want your Logic App to act based on external requests.
  • Add a new step by searching for “HTTP” in the actions list and choose the “HTTP – HTTP” action. This will be used to call the Azure OpenAI API.

Step 4: Configure the HTTP Action for Azure OpenAI

  • Method: POST
  • URI: Enter the endpoint URL of your Azure OpenAI service.
  • Headers: Add two headers:
    • Content-Type with the value application/json
    • Authorization with the value Bearer <Your Azure OpenAI API Key>
  • Body: Craft the JSON payload according to your task. For example, to generate text, your body might look like this:
{
  "prompt": "Write a brief about integrating Azure OpenAI with Logic Apps.",
  "temperature": 0.7,
  "max_tokens": 100
}

Step 5: Process the Response

After calling the Azure OpenAI API, you’ll want to handle the response:

  • Add a “Parse JSON” action to interpret the API response.
  • In the “Content” box, select the body of the HTTP action.
  • Define the schema based on the Azure OpenAI response format. For text generation, you’ll focus on extracting the generated text from the response.

Step 6: Add Final Actions

Decide what to do with the Azure OpenAI’s response. You could:

  • Send an email with the generated content.
  • Save the response to a database or a file in Azure Blob Storage.
  • Respond to the initial HTTP request with the generated content.

Step 7: Test Your Logic App

  • Save your Logic App and run a test by triggering it based on your chosen trigger method.
  • Monitor the run in the “Overview” section of your Logic App to ensure everything executes as expected.

Deploy Logic Apps with PowerShell

This post is basically just a way to refresh my memory when in the next 3 months I completely forget how easy this is. Here’s how you can leverage PowerShell to manage your Logic Apps and their connections more effectively.

# Define variables
$resourceGroupName = 'YourResourceGroup'
$logicAppName = 'YourLogicAppName'
$templateFilePath = 'path/to/your/template.json'
$parametersFilePath = 'path/to/your/parameters.json'

# Deploy the Logic App
New-AzResourceGroupDeployment -Name DeployLogicApp `
  -ResourceGroupName $resourceGroupName `
  -TemplateFile $templateFilePath `
  -TemplateParameterFile $parametersFilePath

If you need a template example or parameters example, check the end of this post!!

Managing Logic App Connections with PowerShell

PowerShell can also simplify the creation and management of Logic App connections, making it easier to connect to services like Office 365 or custom APIs:

# Creating a connection to Office 365
$connectionName = 'office365Connection'
$connectionParams = @{
    'token:TenantId' = '<YourTenantId>';
    'token:PrincipalId' = '<YourPrincipalId>';
    'token:ClientSecret' = '<YourClientSecret>'
}

New-AzResource -ResourceType 'Microsoft.Web/connections' -ResourceName $connectionName `
  -ResourceGroupName $resourceGroupName -Location 'eastus' `
  -Properties $connectionParams

Sample Template and Parameter Json Files:

Template:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [
    {
      "type": "Microsoft.Logic/workflows",
      "apiVersion": "2019-05-01",
      "name": "[parameters('logicAppName')]",
      "location": "[parameters('location')]",
      "properties": {
        "state": "Enabled",
        "definition": {
          "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
          "contentVersion": "1.0.0.0",
          "triggers": {
            "When_a_HTTP_request_is_received": {
              "type": "Request",
              "kind": "Http",
              "inputs": {
                "method": "POST",
                "schema": {}
              }
            }
          },
          "actions": {
            "Send_an_email": {
              "type": "ApiConnection",
              "inputs": {
                "host": {
                  "connection": {
                    "name": "@parameters('$connections')['office365']['connectionId']"
                  }
                },
                "method": "post",
                "body": {
                  "Subject": "Email Subject Here",
                  "Body": "<p>Email Body Here</p>",
                  "To": "example@example.com"
                },
                "path": "/Mail"
              }
            }
          },
          "outputs": {}
        },
        "parameters": {
          "$connections": {
            "defaultValue": {},
            "type": "Object"
          }
        }
      }
    }
  ],
  "parameters": {
    "logicAppName": {
      "defaultValue": "YourLogicAppName",
      "type": "String"
    },
    "location": {
      "defaultValue": "eastus",
      "type": "String"
    }
  }
}

Parameters:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "logicAppName": {
      "value": "YourLogicAppName"
    },
    "location": {
      "value": "eastus"
    }
  }
}

Automating Azure Service Health Alerts with PowerShell

Hello, Azure amigos! Today we’re diving into the depths of automating Azure Service Health alerts using PowerShell.

What’s Azure Service Health Anyway?

Azure Service Health provides personalized alerts and guidance when Azure service issues affect you. It breaks down into three main types of alerts:

  • Service issues: Problems in Azure services that affect you right now.
  • Planned maintenance: Upcoming maintenance that can affect your services in the future.
  • Health advisories: Issues that require your attention but don’t directly impact Azure services (e.g., security vulnerabilities, deprecated features).

Now, onto the fun part—automating these alerts with PowerShell!

Prerequisites

I’ll assume you’ve got the Azure PowerShell module installed and you’re familiar with the basics of PowerShell scripting and Azure. If not, it’s like assuming you can cook a gourmet meal without knowing how to turn on the stove—start there first!

Let’s get one more thing worked out – creating an action group to use in the Alert Rule.

$ActionGroupName = "MyActionGroup"
$ResourceGroupName = "MyResourceGroup"
$ShortName = "MyAG"

# Replace these values with your actual email and phone number
$Email = "your-email@domain.com"
$Sms = "+1-555-867-5309"

# Creating the action group
New-AzActionGroup -ResourceGroupName $ResourceGroupName -Name $ActionGroupName -ShortName $ShortName -EmailReceiver $Email -SmsReceiver $Sms -Location "Global"

With our action group ready, it’s time to define what we’re actually alerting on. We can create alerts for specific issues, maintenance events, or advisories. Here’s how:

# Assuming you've already created an action group as per the previous steps

$ResourceGroupName = "MyResourceGroup"
$RuleName = "MyServiceHealthAlert"
$ActionGroupId = (Get-AzActionGroup -ResourceGroupName $ResourceGroupName -Name "MyActionGroup").Id

# Service Health alert criteria
$criteria = New-AzActivityLogAlertCondition -Field 'category' -Equal 'ServiceHealth'

# Creating the Service Health alert
Set-AzActivityLogAlert -Location "Global" -Name $RuleName -ResourceGroupName $ResourceGroupName -Scope "/subscriptions/your-subscription-id" -Condition $criteria -ActionGroup $ActionGroupId

This PowerShell command creates an alert rule specifically for Service Health notifications within Azure. It triggers based on the ‘ServiceHealth’ category in the Azure Activity Log, ensuring you’re notified whenever there are relevant service health events affecting your subscription.

Explanation:

  • $criteria: This line defines what we’re alerting on. In this case, it’s any activity log entries with a category of ‘ServiceHealth’.
  • Set-AzActivityLogAlert: This cmdlet creates or updates an activity log alert rule. We specify the alert name, the scope (usually your subscription or a resource group), the conditions under which to trigger, and the action group to notify.

And there ya go! Simple and quick. Enjoy your new Alert Rule!

Optimizing Azure Cost Management with PowerShell

Let’s dig into some quick hits for trying to keep your costs down in Azure – and since I am who I am let’s use PowerShell

Automating Cost Reports

First – lets script the retrieval of usage and cost data, businesses can monitor their cloud expenditures closely, identify trends, and make informed decisions to optimize costs.

Get-AzConsumptionUsageDetail -StartDate "2023-01-01" -EndDate "2023-01-31" | Export-Csv -Path "./AzureCostsJan.csv"

This simple script fetches the consumption details for January 2023 and exports the data to a CSV file – from there you can use something like Excel to dig into your big costs.

Identifying Underutilized Resources

PowerShell scripts can scan Azure services to pinpoint underutilized resources, such as VMs with low CPU utilization or oversized and underused storage accounts, which are prime candidates for downsizing or deletion to cut costs.

Get-AzVM | ForEach-Object {
    $metrics = Get-AzMetric -ResourceId $_.Id -MetricName "Percentage CPU" -TimeGrain "00:05:00" -StartTime (Get-Date).AddDays(-30) -EndTime (Get-Date)
    $avgCpu = ($metrics.Data | Measure-Object -Property Average -Average).Average
    if ($avgCpu -lt 10) {
        Write-Output "$($_.Name) is underutilized."
    }
}

This script assesses VMs for low CPU usage, identifying those with an average CPU utilization below 10% over the last 30 days.

Implementing Budget Alerts

Setting up budget alerts with PowerShell helps prevent unexpected overspending by notifying you when your costs approach predefined thresholds.

$budget = New-AzConsumptionBudget -Amount 1000 -Category Cost -TimeGrain Monthly -StartDate 2023-01-01 -EndDate 2023-12-31 -Name "MonthlyBudget" -NotificationKey "90PercentAlert" -NotificationThreshold 90 -ContactEmails "admin@example.com"

This script creates a monthly budget of $1000 and sets up an alert to notify specified contacts via email when 90% of the budget is consumed.

And there you go! Some quick and easy scripts to make sure you don’t blow your Azure budget!