Quick Code – Send Events to an Event Hub with PowerShell

Here is another quick one – let’s send events to an event hub with PowerShell!

function New-SasToken {
    param(
        [string]$ResourceUri,
        [string]$Key,
        [string]$PolicyName,
        [timespan]$TokenTimeToLive
    )

    $Expires = [DateTimeOffset]::Now.Add($TokenTimeToLive).ToUnixTimeSeconds()
    $StringToSign = [System.Web.HttpUtility]::UrlEncode($ResourceUri) + "`n" + $Expires
    $HMACSHA256 = New-Object System.Security.Cryptography.HMACSHA256
    $HMACSHA256.Key = [Text.Encoding]::UTF8.GetBytes($Key)
    $Signature = $HMACSHA256.ComputeHash([Text.Encoding]::UTF8.GetBytes($StringToSign))
    $Signature = [Convert]::ToBase64String($Signature)
    $Token = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($ResourceUri) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $PolicyName
    return $Token
}

# Event Hub parameters
$namespace = "yourNamespace"
$eventHubName = "yourEventHubName"
$sharedAccessKeyName = "yourSharedAccessKeyName"
$sharedAccessKey = "yourSharedAccessKey"
$endpoint = "https://$namespace.servicebus.windows.net/$eventHubName/messages"
$tokenTimeToLive = New-TimeSpan -Minutes 60

# Generate SAS token
$sasToken = New-SasToken -ResourceUri $endpoint -Key $sharedAccessKey -PolicyName $sharedAccessKeyName -TokenTimeToLive $tokenTimeToLive

# Event data
$body = @"
{
    "Data": "Sample Event Data"
}
"@

# Send the event
$headers = @{
    "Authorization" = $sasToken
    "Content-Type" = "application/json"
}

try {
    $response = Invoke-RestMethod -Uri $endpoint -Method Post -Body $body -Headers $headers
    Write-Output "Event sent successfully"
}
catch {
    Write-Error "Failed to send event: $_"
}

Azure Inventory Management with PowerShell

Listen – creating resources in Azure with PowerShell is easy – but actually knows what you have deployed is something else. Let’s dive into the steps to harness the power of PowerShell for a streamlined Azure inventory process.

Prerequisites

Before we embark on this journey, ensure you have:

  • An Azure account with necessary access permissions.
  • PowerShell and the Azure PowerShell module ready on your machine.

Configuring PowerShell for Azure

Connecting to Azure is the first step. Open your PowerShell window and enter these commands. This should let you set your context from the Gridview.

# Connect to Azure with interactive login
Connect-AzAccount

# List subscriptions and select one interactively
Get-AzSubscription | Out-GridView -PassThru | Set-AzContext

Lets go ahead and start to look at your resources:

# List all resources and export to CSV
Get-AzResource | Select-Object ResourceType, Name, Location | Export-Csv -Path ./AllResources.csv -NoTypeInformation

# VM Inventory: List VMs and export their details
Get-AzVM | Select-Object Name, Location, HardwareProfile.VmSize | Export-Csv -Path ./VMInventory.csv -NoTypeInformation

# Storage Accounts: List accounts and export their details
Get-AzStorageAccount | Select-Object StorageAccountName, Location, SkuName | Export-Csv -Path ./StorageAccounts.csv -NoTypeInformation

# Network Resources: List VNets and export their details
Get-AzVirtualNetwork | Select-Object Name, Location, AddressSpace | Export-Csv -Path ./VNetInventory.csv -NoTypeInformation

In the scripts above, each command not only fetches the necessary details but also exports them to a CSV file for easy access and reporting.

Advanced Techniques

Organizing and managing your resources effectively can further be achieved by using tags.

# Organizing resources with Tags: Filter by tag and export
Get-AzResource -Tag @{ Department="Finance"} | Select-Object Name, ResourceType | Export-Csv -Path ./FinanceResources.csv -NoTypeInformation

For more insights and advanced techniques, visit the Azure PowerShell documentation. Here’s to efficient management of your Azure resources. Happy scripting!

Setting Up and Accessing Azure Cognitive Services with PowerShell

Alright folks – we’re going to dive into how you can leverage Azure Cognitive Services with PowerShell to not only set up AI services but also to interact with them. Let’s go!

Prerequisites

Before we begin, ensure you have the following:

  • An Azure subscription.
  • PowerShell 7.x or higher installed on your system.
  • Azure PowerShell module. Install it by running Install-Module -Name Az -AllowClobber in your PowerShell session.

Use Connect-AZAccount to get into your subscription, then run this to create a new RG and Cognitive Services resource:

$resourceGroupName = "<YourResourceGroupName>"
$location = "EastUS"
$cognitiveServicesName = "<YourCognitiveServicesName>"

# Create a resource group if you haven't already
New-AzResourceGroup -Name $resourceGroupName -Location $location

# Create Cognitive Services account
New-AzCognitiveServicesAccount -Name $cognitiveServicesName -ResourceGroupName $resourceGroupName -Type "CognitiveServices" -Location $location -SkuName "S0"

It’s that simple!

To interact with Cognitive Services, you’ll need the access keys. Retrieve them with:

$key = (Get-AzCognitiveServicesAccountKey -ResourceGroupName $resourceGroupName -Name $cognitiveServicesName).Key1

With your Cognitive Services resource set up and your access keys in hand, you can now interact with various cognitive services. Let’s explore a couple of examples:

Text Analytics

To analyze text for sentiment, language, or key phrases, you’ll use the Text Analytics API. Here’s a basic example to detect the language of a given text:

$text = "Hello, world!"
$uri = "https://<YourCognitiveServicesName>.cognitiveservices.azure.com/text/analytics/v3.1/languages"

$body = @{
    documents = @(
        @{
            id = "1"
            text = $text
        }
    )
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri $uri -Method Post -Body $body -Headers @{
    "Ocp-Apim-Subscription-Key" = $key
    "Content-Type" = "application/json"
}

$response.documents.languages | Format-Table -Property name, confidenceScore

So this code will try and determine the language of the text submitted. The output might look like this:

Name           ConfidenceScore
----           ---------------
English        0.99

Let’s try computer vision now:

Computer Vision

Azure’s Computer Vision service can analyze images and extract information about visual content. Here’s how you can use PowerShell to send an image to the Computer Vision API for analysis:

$imageUrl = "<YourImageUrl>"
$uri = "https://<YourCognitiveServicesName>.cognitiveservices.azure.com/vision/v3.1/analyze?visualFeatures=Description"

$body = @{
    url = $imageUrl
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri $uri -Method Post -Body $body -Headers @{
    "Ocp-Apim-Subscription-Key" = $key
    "Content-Type" = "application/json"
}

$response.description.captions | Format-Table -Property text, confidence

This code is trying to describe the image, so the output might look like this – pardon the bad word wrap:

Text                            Confidence
----                            ----------
A scenic view of a mountain range under a clear blue sky 0.98

To learn more about Cognitive Services – check out the Docs!

Azure and AI Event Automation – #2

Assessing Your Current Azure Setup

Before integrating AI into your Azure automation processes, it’s crucial to assess your current Azure environment. This assessment will help identify the strengths, limitations, and potential areas for improvement.

  1. Evaluate Existing Resources and Capabilities
    • Take an inventory of your current Azure resources. This includes virtual machines, databases, storage accounts, and any other services in use.
    • Assess the performance and scalability of these resources. Are they meeting your current needs? How might they handle increased loads with AI integration?
    • Use Azure’s built-in tools like Azure Advisor for recommendations on optimizing resource utilization.
  2. Review Current Automation Configurations
    • Examine your existing automation scripts and workflows. How are they configured and managed? Are there opportunities for optimization or enhancement?
    • Consider the use of Azure Automation to streamline these processes.
  3. Identify Data Sources and Workflows
    • Identify the data sources that your automation processes use. How is this data stored, accessed, and managed?
    • Map out the workflows that are currently automated. Understanding these workflows is crucial for integrating AI effectively.
  4. Check Compliance and Security Measures
    • Ensure that your setup complies with relevant data protection regulations and security standards. This is particularly important when handling sensitive data with AI.
    • Use tools like Azure Security Center to review and enhance your security posture.
  5. Assess Integration Points for AI
    • Pinpoint where in your current setup AI can be integrated for maximum benefit. Look for processes that are repetitive, data-intensive, or could significantly benefit from predictive insights.
    • Consider the potential of Azure AI services like Azure Machine Learning and Azure Cognitive Services in these areas.

Setting Up Essential Azure Services

After assessing your Azure environment, the next step is to set up and configure the essential services that form the backbone of AI-driven automation. Here’s how you can approach the setup of these key services:

  1. Azure Machine Learning (AML)
    • Log into Azure Portal: Access your account at https://portal.azure.com.
    • Navigate to Machine Learning: Find “Machine Learning” under “AI + Machine Learning” in the ‘All services’ section.
    • Create a New Workspace: Click “Create” and choose your Azure subscription and resource group.
    • Configure Workspace: Provide a unique name, select a region, and optionally choose or allow Azure to create a storage account, key vault, and application insights resource.
    • Review and Create: Verify all details are correct, then click “Review + create” followed by “Create” to finalize.
    • Access the Workspace: After creation, visit your resource group, select the new workspace, and note the key details like subscription ID and resource group.
    • Explore Azure Machine Learning Studio: Use the provided URL to access the studio at https://ml.azure.com and familiarize yourself with its features.
    • Set Up Additional Resources: If not auto-created, manually set up a storage account, key vault, and application insights resource in the same region as your workspace.
  2. Azure Cognitive Services
    • Navigate to Cognitive Services: Search for “Cognitive Services” in the portal’s search bar.
    • Create a Resource: Click “Create” to start setting up a new Cognitive Services resource.
    • Fill in Details: Choose your subscription, create or select an existing resource group, and name your resource.
    • Select the Region: Choose a region near you or your users for better performance.
    • Review Pricing Tiers: Select an appropriate pricing tier based on your expected usage.
    • Review and Create: Confirm all details are correct, then click “Review + create”, followed by “Create”.
    • Access Resource Keys: Once deployed, go to the resource, and find the “Keys and Endpoint” section to get your API keys and endpoint URL.
    • Integrate with Applications: Use the retrieved keys and endpoint to integrate cognitive services into your applications.
  3. Azure Logic Apps
    • Search for Logic Apps: In the portal, find “Logic Apps” via the search bar.
    • Initiate Logic App Creation: Click “Add” or “Create” to start a new Logic App.
    • Configure Basic Settings: Select your subscription, resource group, and enter a name for your Logic App. Choose a region.
    • Create the Logic App: After configuring, click “Create” to deploy your Logic App.
    • Open Logic App Designer: Once deployed, open the Logic App and navigate to the designer.
    • Design the Workflow: We will go over this later! This is where the fun begins!!

Setting up these essential Azure services is a foundational step in creating an environment ready for AI-driven automation. Each service plays a specific role, and together, they provide a powerful toolkit for automating complex and intelligent workflows.

Leveraging Azure Machine Learning

  1. Create a Machine Learning Model:
    • Navigate to Azure Machine Learning Studio.
    • Create a new experiment and select a dataset or import your own.
    • Choose an algorithm and train your machine learning model.
  2. Deploy the Model:
    • Once your model is trained and evaluated, navigate to the “Models” section.
    • Select your model and click “Deploy”. Choose a deployment option (e.g., Azure Container Instance).
    • Configure deployment settings like name, description, and compute type.
  3. Consume the Model:
    • After deployment, get the REST endpoint and primary key from the deployment details.
    • Use these details to integrate the model into your applications or services.

Utilizing Azure Cognitive Services

  1. Select a Cognitive Service:
    • Determine which Cognitive Service (e.g., Text Analytics, Computer Vision) fits your needs.
    • In Azure Portal, navigate to “Cognitive Services” and create a resource for the selected service.
  2. Configure and Retrieve Keys:
    • Once the resource is created, go to the “Keys and Endpoint” section.
    • Copy the key and endpoint URL for use in your application.
  3. Integrate with Your Application:
    • Use the provided SDK or REST API to integrate the Cognitive Service into your application.
    • Pass the key and endpoint URL in your code to authenticate the service.

Automating with Azure Logic Apps

  1. Create a New Logic App:
    • In Azure Portal, go to “Logic Apps” and create a new app.
    • Select your subscription, resource group, and choose a name and region for the app.
  2. Design the Workflow:
    • Open the Logic App Designer.
    • Add a trigger (e.g., HTTP request, schedule) to start the workflow.
    • Add new steps by searching for connectors (e.g., Azure Functions, Machine Learning).
  3. Integrate AI Services:
    • Add steps that call Azure Machine Learning models or Cognitive Services.
    • Configure these steps by providing necessary details like API keys, endpoints, and parameters.
  4. Save and Test the Logic App:
    • Save your changes and use the “Run” button to test the Logic App.
    • Check the run history to verify if the workflow executed as expected.

Azure and AI Event Automation – #1

Introduction

Welcome to my new blog series on “AI-Enhanced Event Automation in Azure,” where I will delve into the integration of AI with Azure’s amazing automation capabilities. This series will be more than just a conceptual overview; it will be a practical guide to applying AI in Azure.

Through this series I will explore the role of AI in enhancing Azure’s event monitoring and automation processes. This journey will be tailored for those with a foundational understanding of Azure, aiming to leverage AI to unlock unprecedented potential in cloud computing.

We will begin with the basics of setting up your Azure environment for AI integration, where we’ll reference Azure’s comprehensive Learn documentation.

Moreover, I’ll explore advanced AI techniques and their applications in real-world scenarios, utilizing resources from the Azure AI Gallery to illustrate these concepts.

Let’s dig in!

Key Concepts and Terminologies

To ensure we’re all on the same page let’s clarify some key concepts and terminologies that will frequently appear throughout this series.

  1. Artificial Intelligence (AI): AI involves creating computer systems that can perform tasks typically requiring human intelligence. This includes learning, decision-making, and problem-solving. Azure provides various AI tools and services, which we will explore. Learn more about AI in Azure.
  2. Azure Automation: This refers to the process of automating the creation, deployment, and management of Azure resources. Azure Automation can streamline complex tasks and improve operational efficiencies. Azure Automation documentation offers a comprehensive guide.
  3. Azure Logic Apps: These are part of Azure’s app service, providing a way to automate and orchestrate tasks, business processes, and workflows when you need to integrate apps, data, systems, and services across enterprises or organizations. Explore Azure Logic Apps.
  4. Machine Learning: A subset of AI, machine learning involves training a computer system to learn from data, identify patterns, and make decisions with minimal human intervention. Azure’s machine learning services are pivotal in AI-enhanced automation. Azure Machine Learning documentation provides detailed information.
  5. Event-Driven Architecture: This is a design pattern used in software architecture where the flow of the program is determined by events. In Azure, this concept is crucial for automating responses to specific events within your infrastructure. Understanding Event-Driven Architecture in Azure can give you more insights.

Understanding these terms will be key to concepts we will discuss in this series. They form the building blocks of our exploration into AI-enhanced automation in Azure.

The Role of AI in Azure Automation

AI is not just an add-on but a transformative resource. AI in Azure Automation opens up new avenues for efficiency, intelligence, and sophistication in automated processes.

  1. Enhancing Efficiency and Accuracy: AI algorithms are adept at handling large volumes of data and complex decision-making processes much faster than traditional methods. In Azure, AI can be used to analyze operational data, predict trends, and automate responses with high precision. This leads to a significant increase in the efficiency and accuracy of automated tasks. AI and Efficiency in Azure provides further insights.
  2. Predictive Analytics: One of the most significant roles of AI in Azure Automation is predictive analytics. By analyzing historical data, AI models can predict future trends and behaviors, enabling Azure services to proactively manage resources, anticipate system failures, and automatically adjust to changing demands. The Predictive Analytics in Azure guide is a valuable resource for understanding this aspect.
  3. Intelligent Decision Making: AI enhances Azure automation by enabling systems to make smart decisions based on real-time data and learned patterns. This capability is particularly useful in scenarios where immediate and accurate decision-making is critical, such as in load balancing or threat detection. Azure’s Decision-Making Capabilities further explores this topic.
  4. Automating Complex Workflows: With AI, Azure can automate more complex, multi-step workflows that would be too intricate or time-consuming to handle manually. This includes tasks like data extraction, transformation, loading (ETL), and sophisticated orchestration across various services and applications. Complex Workflow Automation in Azure provides a deeper dive into this functionality.
  5. Continuous Learning and Adaptation: A unique aspect of AI in automation is its ability to continuously learn and adapt. Azure’s AI-enhanced automation systems can evolve based on new data, leading to constant improvement in performance and efficiency over time.

By integrating AI into Azure Automation, we unlock a realm where automation is not just about executing predefined tasks but about creating systems that can learn, adapt, and make intelligent decisions. This marks a significant leap from traditional automation, propelling businesses towards more dynamic and responsive operational models.

Examples of AI Enhancements in Automation

Understanding the practical impact of AI in Azure automation is easier with real-world examples.

  1. Automated Scaling Based on Predictive Analytics: Utilizing AI for predictive analysis, Azure can dynamically adjust resources for an e-commerce platform based on traffic and shopping trends, optimizing performance and cost. Learn more about Azure Autoscale.
  2. Intelligent Data Processing and Insights: Azure AI can analyze large datasets, like customer feedback or sales data, automating the extraction of valuable insights for quick, data-driven decision-making. Explore Azure Cognitive Services.
  3. Proactive Threat Detection and Response: AI-driven monitoring in Azure can identify and respond to security threats in real-time, enhancing network and data protection. Read about Azure Security Center.
  4. Custom Workflow Automation for Complex Tasks: In complex sectors like healthcare or finance, AI can automate intricate workflows, analyzing data for risk assessments or health predictions, improving accuracy and efficiency. Discover Azure Logic Apps.
  5. Adaptive Resource Management for IoT Devices: For IoT environments, Azure’s AI automation can intelligently manage devices, predict maintenance needs, and optimize resource allocation. See Azure IoT Hub capabilities.

These examples highlight AI’s ability to revolutionize Azure automation across various applications, demonstrating efficiency, insight, and enhanced security.

Challenges and Considerations

While integrating AI into Azure automation offers numerous benefits, it also comes with its own set of challenges and considerations.

  1. Complexity of AI Models: AI models can be complex and require a deep understanding of machine learning algorithms and data science principles. Ensuring that these models are accurately trained and tuned is crucial for their effectiveness. Understanding AI Model Complexity provides more insights.
  2. Data Privacy and Security: When dealing with AI, especially in automation, you often handle sensitive data. Ensuring data privacy and complying with regulations like GDPR is paramount. Azure’s Data Privacy Guide offers guidelines on this aspect.
  3. Integration and Compatibility Issues: Integrating AI into existing automation processes might involve compatibility challenges with current systems and workflows. Careful planning and testing are essential to ensure seamless integration. Azure Integration Services can help understand these complexities.
  4. Scalability and Resource Management: As your AI-driven automation scales, managing resources efficiently becomes critical. Balancing performance and cost, especially in cloud environments, requires continuous monitoring and adjustment. Azure Scalability Best Practices provides valuable insights.
  5. Keeping up with Technological Advancements: The field of AI is rapidly evolving. Staying updated with the latest advancements and understanding how they can be applied to Azure automation is crucial for maintaining an edge. Azure Updates is a useful resource for keeping up with new developments.

By understanding and addressing these challenges, you can more effectively harness the power of AI in Azure automation, leading to more robust and efficient solutions.

That’s all for now! In the next post we will dig into Azure and actually start to get our hands dirty!

Your gateway to Azure – Log Analytics

There are a ton of articles that detail how to get all sorts of data into Log Analytics. My friend Cameron Fuller has demonstrated several ways to do it, for example. Heck, I even wrote a post or two.

Recently it occurred to me that I hadn’t read a lot of articles on WHY you want your data in Log Analytics. For people that already have data being ingested it’s obvious, but if you haven’t started down that road yet you might be wondering what all the hype is about. This article is for you.

I will tell you right now – Log Analytics is the ‘gateway drug’ of Azure. One hit, and you are hooked. Once you get your data into Log Analytics the possible uses skyrocket. Let’s break down some of the obvious ones first.

Analysis

This one is the get’s the “Duh” award. Get the data into Log Analytics immediately let’s you use the Azure Data Explorer Query Language (aka at one time as Kusto).

The language is easy to understand, easy to write, and there are tons of examples for doing everything from simple queries to complex monsters with charts, predictions, and cross resource log searches. This is the first, and the most obvious benefit of data ingestion. Not to diminish the capability offered by stopping here, but if this is the extent of the usage of your data then you are missing out.

Solutions

Built right into Log Analytics is set of amazing pre-built solutions that can automatically take your logs and turn it into consumable and actionable data points. Need to know how your Operations Manager environment is doing? Connect SCOM to Log Analytics and you are just a few clicks away from seeing performance improvement suggestions, availability recommendations, and even spot upgrade issues before they occur. The SQL Assessment supplies even more actionable data across your entire connected SQL environment. Most of the solutions come with exquisitely details recommendations. Check out this example from my personal SQL Assessment.

There are many different solutions, and they are being added all the time. Container analysis, upgrade assessment, change tracking, malware checking, AD replication status – the list of solutions is amazing! Even better, the product team that builds these solutions wants to know what you want to see! Go here to see the full list of solutions currently available, and check out the link at the bottom of the page to leave your suggestions.

The not so obvious, and the most fun!

Ok – we’ve knocked out the most obvious usages, but now let’s look at some of the other fun uses!

Log Analytics queries can be directly exported and imported into PowerBI! Simply craft your query, click export (see below) and LA will automatically craft the connection information and query for in a way that PowerBI can understand! All of that data suddenly available to the power of one best BI engines in the business.

Ok – I can hear you all now. PowerBI is just another reporting type application (it’s not, btw), but what else can we do? How about integration to one of the most powerful set of automation tool-sets in the market? Connectors are available directly in both Flow and Logic Apps that allow you to query your data and trigger from the returned data. This is where your data integration truly starts!

Imagine some of the possibilities for both your on-prem and cloud resources:

  • Get texts about critical updates as they are found
  • Schedule update installations with a full approval chain
  • Send notifications about changes that occur in your environment, sending the notifications to the appropriate teams based on the change type
  • Azure Monitor alerts sent straight to Event Grids or Event Hubs for further processing
  • Connect your SCOM alerts through LA and right into Azure automation to perform runbooks in the cloud or on-prem
  • Consume logs from your building entry system and schedule software distributions when people leave the office

Understanding Microsoft Automation Options – Again

Microsoft has more automation options than there are flavors of jelly beans. Understanding what each one is capable of can be a chore in and of itself. Here is a quick primer on some of the tools:

  • Azure Automation
  • Power Apps
  • Azure Logic Apps
  • Azure Function Apps
  • System Center Orchestrator

Azure Automation
Azure Automation is a service that helps you automate manual, long-running, error-prone, and frequently repeated tasks that are commonly performed in a cloud and on-premises environment. It allows you to use runbooks (based on Windows PowerShell or Graphical Runbooks) to automate processes and workflows.
Azure Automation delivers a cloud-based automation, operating system updates, and configuration service that supports consistent management across your Azure and non-Azure environments. It includes process automation, configuration management, update management, shared capabilities, and heterogeneous features.

Pros:

  • Can automate a wide range of tasks and processes
  • Can run on a schedule or be triggered by an event
  • Can be used to automate processes across a variety of systems and platforms

Cons:

  • Requires some coding knowledge such as PowerShell
  • May require more setup and configuration compared to other services

Azure Logic Apps:
Azure Logic Apps is a cloud service that helps you automate and orchestrate tasks, business processes, and workflows when you need to integrate apps, data, systems, and services across enterprises or organizations. Logic Apps connects to your on-premises and cloud-based systems and services, and it provides over 200 connectors that you can use to create your logic app workflow.

Pros:

  • Provides a visual designer for building workflows
  • Offers a wide range of connectors to other systems and services
  • Can be triggered by a variety of events and can run on a schedule
  • Can be configured for multi or single tenant, which grants ability to scale in the appropriate manner

Cons:

  • May require more setup and configuration compared to other services, especially for apps that use the “Standard” model.

Azure Function Apps:
Azure Functions is a serverless compute service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. Functions can be triggered by a variety of inputs, including HTTP requests, timer triggers, and changes to data in other services, and it can be used to build a variety of applications and services. Function Apps are best used for data-in/data-out operations. You can build function apps that have a longer session life, but that requires advanced configuration and potentially higher cost.

Pros:

  • Serverless compute model (pay-per-use)
  • Can be triggered by a variety of inputs and events
  • Can be used to build a wide range of applications and services

Cons:

  • Requires coding knowledge
  • May not be suitable for more complex or customized scenarios, especially if you opt for long running functions

Power Apps and the Power App Platform:
Power Apps is a low-code platform for building custom business applications. With Power Apps, you can create custom business applications for web and mobile devices that can connect to your business data stored in the Common Data Service (CDS) or other data sources.

Pros:

  • Low-code platform for building custom business applications – especially useful for business users that don’t need IT involvement
  • Can connect to a wide range of data sources
  • Provides a visual designer for building apps

Cons:

  • May not be suitable for more complex or customized scenarios, and should not be used for business critical processes
  • May have limitations in terms of app functionality and capabilities

System Center Orchestrator (SCORCH):
SCORCH is a workflow automation software product that enables you to automate system and application processes across an enterprise. SCORCH is part of the System Center suite of tools and is designed to work with other System Center products, as well as other Microsoft and third-party products. It is the only wholly on-prem tool in this post.

Pros:

  • Can automate a wide range of tasks and processes across an enterprise
  • Provides a visual designer for building workflows
  • Offers a wide range of connectors to other systems and services
  • Can be triggered by a variety of events and can run on a schedule
  • Can be configured to be completely on-prem, should your company not allow cloud services

Cons:

  • First and foremost – dead product walking. Do not invest in SCORCH at this time. Microsoft might choose to invest in this product in the future, but do not invest time in this tool until that happens.
  • May require more setup and configuration compared to other workflow automation tools
  • May not be suitable for more complex or customized workflow scenarios
  • May require a significant investment in terms of time and resources to set up and maintain
  • May have dependencies on other System Center products or require integration with other Microsoft or third-party products

MQTT Data to Azure Log Analytics

Setting up solar on our farm in North Texas has been a treasure trove of data to analyze – everything from Inverter load, to PV watts in, to state-of-charge for the batteries – It’s a massive amount of useful information.

So naturally I want that data in Azure Log Analytics. It’s perfect platform to handle this amount of data. Small messages, lots of entries. Just ready for reporting and analytics.

To do this, we are going to use IOT Hub as a go-between. Here are the high-level steps:

To get MQTT data into Azure Log Analytics via IoT Hub, you will need to perform the following steps:

  1. Set up an IoT hub in your Azure account.
  2. Set up a device in your IoT hub.
  3. Configure the device to send data to your IoT hub using the MQTT protocol.
  4. Set up a log analytics workspace in your Azure account.
  5. Connect your IoT hub to your log analytics workspace.
  6. Start sending MQTT data from your device to your IoT hub.

And now some details:

  1. Set up an IoT hub in your Azure account:
  • In the Azure portal, click on “Create a resource” in the top left corner, then search for “IoT Hub” and select it.
  • Follow the prompts to create a new IoT hub, including selecting the subscription, resource group, and region you want to use.
  • Make note of the IoT hub’s name and connection string, as you will need these later.
  1. Set up a device in your IoT hub:
  • In the Azure portal, go to the IoT hub blade and select “IoT Devices” from the left menu.
  • Click the “Add” button to create a new device.
  • Follow the prompts to set up the device, including giving it a unique device ID and generating a device key or certificate.
  • Make note of the device ID and key/certificate, as you will need these later.
  1. Configure the device to send data to your IoT hub using MQTT:
  • The specific steps for this will depend on the device you are using, but generally you will need to specify the MQTT endpoint and authentication information for your IoT hub.
  • The MQTT endpoint will be in the format “YOUR-IOT-HUB-NAME.azure-devices.net”, and you will need to use the device ID and key/certificate you obtained in step 2 to authenticate.
  • Specify the MQTT topic you want to publish data to.
  1. Set up a log analytics workspace:
  • In the Azure portal, click on “Create a resource” in the top left corner, then search for “Log Analytics” and select it.
  • Follow the prompts to create a new log analytics workspace, including selecting the subscription, resource group, and region you want to use.
  • Make note of the workspace ID and primary key, as you will need these later.
  1. Connect your IoT hub to your log analytics workspace:
    • In the Azure portal, go to the IoT hub blade and select “Diagnostic settings” from the left menu.
    • Click the “Add diagnostic setting” button to create a new setting.
    • Select the log analytics workspace you created in step 4 as the destination for the data.
    • Select the data types you want to collect
    1. Start sending MQTT data from your device to your IoT hub:
    • Using the device ID, key/certificate, MQTT endpoint, and topic you obtained in steps 2 and 3, publish data to your IoT hub using the MQTT protocol.
    • The data should be automatically forwarded to your log analytics workspace and be available for analysis.

    Adding Azure Alert Rules with PowerShell 7

    Here is a quick and dirty post to create both Metric and Scheduled Query alert rule types in Azure:

    To create an Azure Alert rule using Powershell 7 and the AZ module, you will need to install both Powershell 7 and the AZ module.

    PowerShell 7: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.1

    To install the AZ module, run the following command in Powershell:

    Install-Module -Name AZ

    Once both Powershell 7 and the AZ module are installed, you can use the following commands to create an Azure Alert rule.

    To create a metric alert rule:

    $alertRule = New-AzMetricAlertRule `
        -ResourceGroupName "MyResourceGroup" `
        -RuleName "MyMetricAlertRule" `
        -TargetResourceId "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}" `
        -MetricName "Percentage CPU" `
        -Operator GreaterThan `
        -Threshold 90 `
        -WindowSize 30 `
        -TimeAggregationOperator Average
    

    And to create a Scheduled Query rule:

    $alertRule = New-AzLogAlertRule `
        -ResourceGroupName "MyResourceGroup" `
        -RuleName "MyScheduledQueryAlertRule" `
        -Location "East US" `
        -Condition "AzureMetrics | where ResourceProvider == 'Microsoft.Compute' and ResourceType == 'virtualMachines' and MetricName == 'Percentage CPU' and TimeGrain == 'PT1H' and TimeGenerated > ago(2h) | summarize AggregateValue=avg(MetricValue) by bin(TimeGenerated, 1h), ResourceId" `
        -ActionGroupId "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Insights/actionGroups/{action-group-name}"
    

    You will have to replace the main bits you would expect – ResourceGroupName, Subscription-ID, Action-Group-Name, Location, etc.

    Hope this helps!

    Stopwatch vs Measure-Command

    Just a quick one – consider using the Stopwatch class instead of Measure-Command in PowerShell. There are a couple of good reasons that you might want to:

    First off you get more granular measuring units. While this is not normally an issue for normal performance troubleshooting, there might be very unique circumstances where you need to get sub-millisecond.

    In my opinion the main reason to use the stopwatch class is the enhanced control it has. You can stop and restart the stopwatch at any time. You can specifically start the stopwatch, run some commands, stop the stopwatch, run more commands, and then restart it without having to add together 2 or more measure-commands. You also get the ability to zero out the stopwatch anytime you want. You can also have multiple stopwatches running at the same time!