Azure Application Insights, how to change daily cap by Azure CLI - azure

I'm trying to change daily cap for data transfer for all my Application Insights on Azure. Is there any way to change it for all of them?
I can't find how to do it by using Azure CLI.
Thank you.

You can change the daily cap with the Azure PowerShell cmdlet Set-AzureRmApplicationInsightsDailyCap.
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionName "Your Sub Name"
function Set-DailyCap {
$AI = Get-AzureRmApplicationInsights | Select ResourceGroupName, Name
$AI | foreach {
write-output ("Attempting to set daily cap for App Insights in resource group {0} instance {1}" -f $_.ResourceGroupName, $_.Name)
Set-AzureRmApplicationInsightsDailyCap -ResourceGroupName $_.ResourceGroupName -Name $_.Name -DailyCapGB 0.2
}
}
Set-DailyCap

Here is a modified version of #RonDBA's solution, which includes some logic to parse the names and set limits based on their name. Using this script, I was able to update hundreds of daily caps in a matter of seconds.
import-module azurerm.applicationinsights
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionName "yoursubscription here"
$ai = Get-AzureRmApplicationInsights | select ResourceGroupName, Name
$AI | foreach {
$cap = 1
$color = 'red'
if($_.Name -match 'dev'){
$cap = .12
$color = 'green'
}
if($_.Name -match 'stg'){
$cap = .24
$color = 'blue'
}
if($cap -eq 1)
{
if($_.Name -match 'api'){
$cap = 1.4
$color = 'yellow'
}
else{$cap = 2.9}
}
write-host ("Attempting to set daily cap at $cap for {0} instance " -f $_.ResourceGroupName) -NoNewline
write-host $_.Name -ForegroundColor $color
Set-AzureRmApplicationInsightsDailyCap -ResourceGroupName $_.ResourceGroupName -Name $_.Name -DailyCapGB $cap
}

There is no way you can change the daily cap of your application insights component using Azure CLI or even Azure REST APIs as of today.
To change it, use the Daily volume cap blade, linked from the Data
Volume Management blade (see below). Note that some subscription types
have credit which cannot be used for Application Insights. If the
subscription has a spending limit, the daily cap blade will have
instructions how to remove it and enable the daily cap to be raised
beyond 32.3 MB/day.
Data source/Reference:
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-pricing#data-rate

Related

PowerShell to remove all AD attributes when matching the specific string?

I wanted to remove smtp:*#olddomain.com in all of my users, but somehow the cmdlet does not take the wild card to loop through the attributes.
Script:
$DefaultDomain = 'NewCompany.onmicrosoft.com'
$OldDomain = 'olddomain.com'
$DistributionGroups = Import-Csv -LiteralPath C:\Source-DL.csv
$DistributionGroups | ForEach-Object {
Write-Host "Set DL: $($_.DisplayName) into [$($_.Alias+"#"+$DefaultDomain)]" -ForegroundColor Yellow
Set-DistributionGroup -Identity $_.Alias -WindowsEmailAddress $($_.Alias+"#"+$DefaultDomain) -Emailaddresses #{remove="$($_.Alias)#$OldDomain"}
}
The environment is not on-premise AD hence I can only access the Azure AD or Exchange Online cmdlet.

Can't add device to Azure Active Directory because it has two Object IDs

When I try to add the device looping through a txt file, it says its already a member. When I check the members in the group, nothing changes. From what I've researched, this is due to hybrid setup with on-prem and Azure AD, but I would like to add the devices to the Azure group.
$azgroup = "myGroup"
$machines = get-content ".\deviceList.txt"
write-host "Getting Object ID of group.." -ForegroundColor Green
$objid = (get-azureadgroup -Filter "DisplayName eq '$azgroup'" ).objectid
write-host "Getting group members (We dont want duplicates!).." -ForegroundColor Cyan
$members = Get-AzureADGroupMember -ObjectId $objid -all $true | select displayname
foreach ($machine in $machines) {
$refid = Get-AzureADDevice -Filter "DisplayName eq '$machine'"
$result = ""
$result = ($members -match $machine)
if($result -eq ""){
try{
Write-host "Adding " $refid.displayname -ForegroundColor Cyan
Add-AzureADGroupMember -ObjectId $objid -RefObjectId $refid.objectid[0]
}
catch{
write-host "An error occured for " $refid.displayname -ForegroundColor Red
}
}
else
{
write-host $machine " is already a member" -ForegroundColor Green
}
}
I tried treating the specific ObjectID as an array but neither worked to add to Azure AD group
Add-AzureADGroupMember -ObjectId $objid -RefObjectId $refid.objectid[0]
If the AzureAD module doesn't work within a hybrid infrastructure, is there any way to bulk add devices to a group in Azure AD?
Here is the working solution. Ok so due to each device having more than one reference IDs, I just treated like an array. This is the part of my code I had to change:
[String]$refid = (Get-AzureADDevice -Filter "DisplayName eq '$machine'")[0].ObjectId
I misplaced the my index ([0]) and placed it after the property, not before it. Then I made sure it outputed a string for good measure, although you can check this with the .gettype() method. Because the on-premise DC and Azure sync, you can use these Device reference IDs interchangeably. It also didnt help outputting a custom error at first, thats what I get for copy-pasting part of someone else's code...

Azure Powershell Question for Virtual Machine

I am reviewing a script that is supposed to delete a vm along with all of the resources attributed to the vm
Write-Host -NoNewline -ForegroundColor Green "Please enter the VM name you would like to remove:"
$VMName = Read-Host
$vm = Get-AzVm -Name $VMName
if ($vm) {
$RGName=$vm.ResourceGroupName
Write-Host -ForegroundColor Cyan 'Resource Group Name is identified as-' $RGName
#boot diagnostics container auto generated in storage account. Auto delete this storageURI property
$diagSa = [regex]::match($vm.DiagnosticsProfile.bootDiagnostics.storageUri, '^http[s]?://(.+?)\.').groups[1].value
Write-Host -ForegroundColor Cyan 'Marking Disks for deletion...'
$tags = #{"VMName"=$VMName; "Delete Ready"="Yes"}
$osDiskName = $vm.StorageProfile.OSDisk.Name
$datadisks = $vm.StorageProfile.DataDisks
$ResourceID = (Get-Azdisk -Name $osDiskName).id
New-AzTag -ResourceId $ResourceID -Tag $tags | Out-Null
if ($vm.StorageProfile.DataDisks.Count -gt 0) {
foreach ($datadisks in $vm.StorageProfile.DataDisks){
$datadiskname=$datadisks.name
$ResourceID = (Get-Azdisk -Name $datadiskname).id
New-AzTag -ResourceId $ResourceID -Tag $tags | Out-Null
}
}
if ($vm.Name.Length -gt 9){
$i = 9
}
else
{
$i = $vm.Name.Length - 1
}
$azResourceParams = #{
'ResourceName' = $VMName
'ResourceType' = 'Microsoft.Compute/virtualMachines'
'ResourceGroupName' = $RGName
}
$vmResource = Get-AzResource #azResourceParams
$vmId = $vmResource.Properties.VmId
$diagContainerName = ('bootdiagnostics-{0}-{1}' -f $vm.Name.ToLower().Substring(0, $i), $vmId)
$diagSaRg = (Get-AzStorageAccount | where { $_.StorageAccountName -eq $diagSa }).ResourceGroupName
$saParams = #{
'ResourceGroupName' = $diagSaRg
'Name' = $diagSa
}
Write-Host -ForegroundColor Cyan 'Removing Boot Diagnostic disk..'
if ($diagSa){
Get-AzStorageAccount #saParams | Get-AzStorageContainer | where {$_.Name-eq $diagContainerName} | Remove-AzStorageContainer -Force
}
else {
Write-Host -ForegroundColor Green "No Boot Diagnostics Disk found attached to the VM!"
}
Write-Host -ForegroundColor Cyan 'Removing Virtual Machine-' $VMName 'in Resource Group-'$RGName '...'
$null = $vm | Remove-AzVM -Force
Write-Host -ForegroundColor Cyan 'Removing Network Interface Cards, Public IP Address(s) used by the VM...'
foreach($nicUri in $vm.NetworkProfile.NetworkInterfaces.Id) {
$nic = Get-AzNetworkInterface -ResourceGroupName $vm.ResourceGroupName -Name $nicUri.Split('/')[-1]
Remove-AzNetworkInterface -Name $nic.Name -ResourceGroupName $vm.ResourceGroupName -Force
foreach($ipConfig in $nic.IpConfigurations) {
if($ipConfig.PublicIpAddress -ne $null){
Remove-AzPublicIpAddress -ResourceGroupName $vm.ResourceGroupName -Name $ipConfig.PublicIpAddress.Id.Split('/')[-1] -Force
}
}
}
Write-Host -ForegroundColor Cyan 'Removing OS disk and Data Disk(s) used by the VM..'
Get-AzResource -tag $tags | where{$_.resourcegroupname -eq $RGName}| Remove-AzResource -force | Out-Null
Write-Host -ForegroundColor Green 'Azure Virtual Machine-' $VMName 'and all the resources associated with the VM were removed sucessfully...'
}
else{
Write-Host -ForegroundColor Red "The VM name entered doesn't exist in your connected Azure Tenant! Kindly check the name entered and restart the script with correct VM name..."
}
I had a question: what does this block of code exactly do:
$diagSa = [regex]::match($vm.DiagnosticsProfile.bootDiagnostics.storageUri, '^http[s]?://(.+?)\.').groups[1].value
I know it matches the storage uri, but how? And why is this needed? I am not sure what the .groups[1].value is referring to either
$diagSa =
[regex]::match($vm.DiagnosticsProfile.bootDiagnostics.storageUri,
'^http[s]?://(.+?).').groups[1].value
I know it matches the storage uri, but how?
You are using the [regex] type accelerator & match method () in the above expression.
The Match() method is a way to instruct PowerShell to attempt to match a string inside of another string. The Match() method has two parameters; the string you'd like to match on and the regular expression you'd like to test against.
Whenever a match is found and a regex group is used; (), the [regex] type accelerator has a Captures property. This Captures property then has a property called Groups. This is a collection that contains lots of attributes of what was matched. The second element in that collection contains the actual value that was matched.
what the .groups[1].value is referring to either
groups[1].values returns the storage account name where the boot diagnostics container resides.
And why is this needed?
When creating an Azure VM, you always have the option of creating a boot diagnostics container. This is useful to troubleshooting VM boot issues but doesn’t get removed when a VM is deleted. Let’s remedy that.
To remove the boot diagnostics container, you first need to figure out the name of the storage account the container resides on. To find that storage account, you’ll have to do some parsing of the storageUri property that’s exists in the DiagnosticsProfile object on the VM.
for more information about [regex]::match().group[1].value expression refer the below blog :
https://mcpmag.com/articles/2015/09/30/regex-groups-with-powershell.aspx

Adding tags to azure VMs via CSV

trying to add tags to VMs via CSV data, right now I have the below code:
if ($context.Account -eq $null) {
# Login-AzureAccount
Connect-AzAccount
}
# Select Azure Subscription
$subscriptionId = (Get-AzSubscription | Out-GridView -Title "Select an Azure Subscription ..." -PassThru).SubscriptionId
#Select specified subscription ID
Select-AzSubscription -SubscriptionId $subscriptionId
$InputCSVFilePath = "test.csv"
$csvItems = Import-Csv $InputCSVFilePath
################
foreach ($item in $csvItems){
Clear-Variable r
#$r = Get-AzResource -ResourceGroupName $item.ResourceGroup -Name $item.VM -ErrorAction Continue
$r = Get-AzResource -Name $item.VM
################
if ($r -ne $null){
if ($r.Tags){
# Tag - Client DL
if ($r.Tags.ContainsKey("Client_DL")){
$r.Tags["Client_DL"] = $item.ClientDL
}else{
$r.Tags.Add("Client_DL", $item.ClientDL)
}
# Tag - Priority
if ($r.Tags.ContainsKey("Priority")){
$r.Tags["Priority"] = $item.Priority
}else{
$r.Tags.Add("Priority", $item.Priority)
}
}
}else{
Write-Host "No VM found named $($item.VMName)!"
}
}
I verified that my code does indeed go through the functions but for some reason the tags are not being set on my VM's. I ran the commands manually in powershell and I was able to set a tag by doing:
$r = Get-AzResource -Name TestVM
$r.Tags.Add("Client_DL", "TEST-DL")
Am I missing something? i'm running a Set-PSDebug -Trace 2 when running my code and it seems to check out just fine, but the tags aren't getting set/written.
So you're adding the tags in memory but you're not calling any of the Az cmdlets to set the tags back on the resource.
You can see in the example in the docs here they return the VM with Get-AzResource, append their new tag to the existing tags and then use Set-AzResource to write the newly added tag back.
Just be careful of that
When updating tags through PowerShell, tags are updated as a whole. If you are adding one tag to a resource that already has tags, you will need to include all the tags that you want to be placed on the resource
Alternatively you could use Update-AzTag which has an -Operation parameter and lets you choose whether you want to merge, replace or delete the existing tags.
https://learn.microsoft.com/en-us/powershell/module/az.resources/update-aztag?view=azps-6.0.0
Ultimately you'd need to set back your $r.Tags value to your resource as the last operation within your if statement.

Best way to retrieve CPU utilization for all VMs in a Azure subscription

Trying to get the CPU utilization (and preferably network as well. I would love to get RAM too, but as i understand that requires having the guest module installed to get those metrics. so at this point i just need the metrics at the 'host' level).
Idea is to run this against all VMs in a subscription, to get VM name, VM resource group, CPU utilization over the last x days, network in over the last x days, and network out over the last x days.
The first thing I tried though, using the "Get-AzureRMMetric", starts giving errors.
I type "get-azurermmetric", and am prompted for a resource ID. I enter the resource ID of the VM, and the response i get is a long string of warnings, and exception types, that an invalid status code 'notfound' was returned.
Any ideas?
First, you need to determine which metrics are supported for vm, use the following code:
(Get-AzureRmMetricDefinition -ResourceId "vm resource id").name
Then you can see the supported metrics(Just ignore the warning message):
As per your question, I think you need "Percentage CPU" / "Network In" / "Network Out".
Then you can use the sample code below for your purpose(you can make some changes if it does not meet your need):
#get all vms in a resource group, but you can remove -ResourceGroupName "xxx" to get all the vms in a subscription
$vms = Get-AzureRmVM -ResourceGroupName "xxx"
#get the last 3 days data
#end date
$et=Get-Date
#start date
$st=$et.AddDays(-3)
#define an array to store the infomation like vm name / resource group / cpu usage / network in / networkout
$arr =#()
foreach($vm in $vms)
{
#define a string to store related infomation like vm name etc. then add the string to an array
$s = ""
#percentage cpu usage
$cpu = Get-AzureRmMetric -ResourceId $vm.Id -MetricName "Percentage CPU" -DetailedOutput -StartTime $st `
-EndTime $et -TimeGrain 12:00:00 -WarningAction SilentlyContinue
#network in
$in = Get-AzureRmMetric -ResourceId $vm.Id -MetricName "Network In" -DetailedOutput -StartTime $st `
-EndTime $et -TimeGrain 12:00:00 -WarningAction SilentlyContinue
#network out
$out = Get-AzureRmMetric -ResourceId $vm.Id -MetricName "Network Out" -DetailedOutput -StartTime $st `
-EndTime $et -TimeGrain 12:00:00 -WarningAction SilentlyContinue
# 3 days == 72hours == 12*6hours
$cpu_total=0.0
$networkIn_total = 0.0
$networkOut_total = 0.0
foreach($c in $cpu.Data.Average)
{
#this is a average value for 12 hours, so total = $c*12 (or should be $c*12*60*60)
$cpu_total += $c*12
}
foreach($i in $in.Data.total)
{
$networkIn_total += $i
}
foreach($t in $out.Data.total)
{
$networkOut_total += $t
}
# add all the related info to the string
$s = "VM Name: " + $vm.name + "; Resource Group: " + $vm.ResourceGroupName + "; CPU: " +$cpu_total +"; Network In: " + $networkIn_total + "; Network Out: " + $networkOut_total
# add the above string to an array
$arr += $s
}
#check the values in the array
$arr
The test result:
Space
Is that we can able to fetch maximum usage on CPU with date using same script,
i have used to did below changes like call Maximum ...no luck..i hope some condition need to do you have solution for that
foreach($c in $cpu.Data.Maximum)
{
#this is a average value for 12 hours, so total = $c*12 (or should be $c*12*60*60)
$cpu_total += $c*12
#($c|measure -maximum).maximum
}

Resources