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!