Loading...

Track IP addresses consumption with Azure Application Insights  -  Part 2

Track IP addresses consumption with Azure Application Insights  -  Part 2

Introduction

 

In part 1 we saw how to send a custom event telemetry to an Azure Application Insights instance through PowerShell.

 

We did track our Azure Virtual Network IP addresses consumption, we will now automate this tracking every 30 minutes through a Timer Trigger Azure Function App.

 

The Azure Function will be deployed through Bicep. Bicep is a domain-specific language (DSL) that uses declarative syntax to deploy Azure resources. It provides concise syntax, reliable type safety, and support for code reuse. According to Microsoft documentation Bicep offers the best authoring experience for your infrastructure-as-code solutions in Azure.

 

Jamesdld23_0-1675872620612.png

 

 

Prerequisites

Azure account

Before you begin, you must have an Azure account with an active subscription. Create an account for free.

 

Code repository

Download the sample code repository, run the following command in your local terminal window:

 

 

git clone https://github.com/JamesDLD/bicep-function-app-virtual-network-monitoring.git cd bicep-function-app-virtual-network-monitoring

 

 

Review the Bicep files and create your environment

 

Bicep file to create the Azure Function App

 

 

@description('The name of the function app that you wish to create.') param appName string = 'fnapp${uniqueString(resourceGroup().id)}' @description('Storage Account type') @allowed([ 'Standard_LRS' 'Standard_GRS' 'Standard_RAGRS' ]) param storageAccountType string = 'Standard_LRS' @description('Location for all resources.') param location string = resourceGroup().location @description('Location for Application Insights') param appInsightsLocation string @description('The language worker runtime to load in the function app.') @allowed([ 'node' 'dotnet' 'java' 'powershell' ]) param runtime string = 'powershell' var functionAppName = appName var hostingPlanName = appName var applicationInsightsName = appName var storageAccountName = '${uniqueString(resourceGroup().id)}azfunctions' var functionWorkerRuntime = runtime resource storageAccount 'Microsoft.Storage/storageAccounts@2021-08-01' = { name: storageAccountName location: location sku: { name: storageAccountType } kind: 'Storage' } resource applicationInsights 'Microsoft.Insights/components@2020-02-02' = { name: applicationInsightsName location: appInsightsLocation kind: 'web' properties: { Application_Type: 'web' Request_Source: 'rest' } } resource hostingPlan 'Microsoft.Web/serverfarms@2021-03-01' = { name: hostingPlanName location: location sku: { name: 'Y1' tier: 'Dynamic' } properties: {} } resource functionApp 'Microsoft.Web/sites@2021-03-01' = { name: functionAppName location: location kind: 'functionapp' identity: { type: 'SystemAssigned' } properties: { serverFarmId: hostingPlan.id siteConfig: { appSettings: [ { name: 'AzureWebJobsStorage' value: 'DefaultEndpointsProtocol=https;AccountName=${storageAccountName};EndpointSuffix=${environment().suffixes.storage};AccountKey=${storageAccount.listKeys().keys[0].value}' } { name: 'WEBSITE_CONTENTAZUREFILECONNECTIONSTRING' value: 'DefaultEndpointsProtocol=https;AccountName=${storageAccountName};EndpointSuffix=${environment().suffixes.storage};AccountKey=${storageAccount.listKeys().keys[0].value}' } { name: 'WEBSITE_CONTENTSHARE' value: toLower(functionAppName) } { name: 'FUNCTIONS_EXTENSION_VERSION' value: '~4' } { name: 'FUNCTIONS_WORKER_RUNTIME' value: functionWorkerRuntime } { name: 'APPLICATIONINSIGHTS_CONNECTION_STRING' value: applicationInsights.properties.ConnectionString } ] ftpsState: 'FtpsOnly' minTlsVersion: '1.2' } httpsOnly: true } } output functionAppName string = functionApp.name output principalId string = functionApp.identity.principalId

 

 

The following four Azure resources are created by this Bicep file:

 

 

Deploy the Bicep file using Azure CLI.

 

#variable location=westeurope resourceGroupName=exampleRG #create the resource group az group create --name $resourceGroupName --location $location #create the function app az deployment group create \ --name function_app \ --resource-group $resourceGroupName \ --template-file function_app.bicep \ --parameters appInsightsLocation=$location

 

 

When the deployment finishes, you should see a message indicating the deployment succeeded.

 

 

Bicep file to assign the Reader privilege to the Managed Identity of our Function App

 

@description('The principal Id of the object that will be granted the needed role.') param principalId string @description('This is the built-in Reader role. See https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles?WT.mc_id=AZ-MVP-5003548#reader') resource readerRoleDefinition 'Microsoft.Authorization/roleDefinitions@2018-01-01-preview' existing = { scope: subscription() name: 'acdd72a7-3385-48ef-bd42-f606fba81ae7' } targetScope = 'subscription' resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = { name: guid(readerRoleDefinition.id, principalId, readerRoleDefinition.id) properties: { roleDefinitionId: readerRoleDefinition.id principalId: principalId principalType: 'ServicePrincipal' } }

 

 

 

The following Azure resource is created by this Bicep file:

 

Deploy the Bicep file using Azure CLI.

 

#assign the azure built-in role to the function app principalId=$(az deployment group show \ --resource-group $resourceGroupName \ --name function_app \ --query properties.outputs.principalId.value \ --output tsv ) az deployment sub create \ --location $location \ --template-file role_assignment.bicep \ --parameters principalId=$principalId

 

 

When the deployment finishes, you should see a message indicating the deployment succeeded.

 

Use Azure CLI to validate the deployment.

 

az resource list --resource-group $resourceGroupName

 

 

Perform a manual git deployment to the Azure Function App

Deploy the PowerShell code to the Function App using Azure CLI.

 

functionAppName=$(az deployment group show \ --resource-group $resourceGroupName \ --name function_app \ --query properties.outputs.functionAppName.value \ --output tsv ) az functionapp deployment source config \ --branch main \ --manual-integration \ --name $functionAppName \ --resource-group $resourceGroupName \ --repo-url https://github.com/JamesDLD/bicep-function-app-virtual-network-monitoring

 

 

View the audit result Azure Application Insights

You will then be able to monitor the Function App logs being inserted every 30 minutes by navigating to you Function App > Logs as illustrated in the following screenshot.

 

 

Jamesdld23_1-1675872620680.png

 

The query:

 

customEvents | where name == "dld_telemetry_azure_vnets_counter" | extend SubnetAddressPrefix = customDimensions.SubnetAddressPrefix | extend SubnetIPaddressesCount = toreal(customDimensions.SubnetIPaddressesCount) | extend SubnetIPaddressesLimit = toreal(customDimensions.SubnetIPaddressesLimit) | extend SubnetName = tostring(customDimensions.SubnetName) | project timestamp, SubnetName, SubnetAddressPrefix, SubnetIPaddressesCount, SubnetIPaddressesLimit | summarize max(SubnetIPaddressesCount) by timestamp, SubnetName | render timechart

 

 

Clean up resources

 

az group delete --name $resourceGroupName

 

 

Conclusion

We saw in part 1 how to send a custom event telemetry to an Azure Application Insights instance through PowerShell, we did see in this article how to automate our audit, what about building an Azure Workbook in part 3?

 

Note: the complete source code we saw in this article is available here https://github.com/JamesDLD/bicep-function-app-virtual-network-monitoring

 

See You in the Cloud

Jamesdld

Published on:

Learn more
Azure Developer Community Blog articles
Azure Developer Community Blog articles

Azure Developer Community Blog articles

Share post:

Related posts

This Month in Azure Static Web Apps | 09/2024

    We are back with another edition of the Azure Static Web Apps Community! :party_popper:   September was yet another month ...

1 year ago

GitHub Copilot for Azure: 6 Must-Try Features

As developers, we are constantly seeking tools that streamline our workflows and boost productivity. … Enter GitHub Copilot for Azure, now in ...

1 year ago

Responsible AI Mitigation Layers

Generative AI is increasingly being used in various kinds of systems to augment humans and infuse intelligent behavior into existing and new a...

1 year ago

Streamline Your Azure Workflow: Introducing GitHub Copilot for Azure in VS Code

I'm excited to announce the public preview of GitHub Copilot for Azure - a new addition to your toolkit that seamlessly integrates with G...

1 year ago

Build Intelligent Apps Code-First with Prompty and Azure AI

      Building Generative AI applications can feel daunting for traditional app developers. What does the end-to-end applicati...

1 year ago

Certificación AI-900 (Fundamentos de IA) con Chicas en IA

La inteligencia artificial ha llegado para quedarse, ¡y más aún con la revolucionaria IA generativa! Para ayudar a los profesionales a especia...

1 year ago

Get certified with Learn Live GitHub series!

GitHub Universe is coming, and Microsoft and GitHub are partnering to offer a new special Learn Live series in Brazilian Portuguese, English a...

1 year ago

Certifícate con Learn Live GitHub en Español

Microsoft y GitHub se han unido para ofrecer una nueva serie especial de Learn Live en inglés y español: GitHub 2024. Del 10 al 24 de Octubre,...

1 year ago

Evaluating generative AI: Best practices for developers

As a developer working with generative AI, you've likely marveled at the impressive outputs your models can produce. But how do you ensure the...

1 year ago

Introducing Azure Product Retirement Livestreams

The Azure Retirements team, in collaboration with key partner groups, is excited t...

1 year ago

Newsletter

Get the latest Dynamics 365 and Power Platform content in your inbox

A curated digest of community blogs, product news, videos, and podcasts — delivered without the noise.

Weekly updates Unsubscribe anytime Fresh community picks
We use your email only for the newsletter and you can unsubscribe at any time.
By subscribing, you agree to the privacy policy.