How can i get Azure ResourceGroup costs using az cmdlets in Powershell? - azure

I am trying to get resourcegroup costs by the following
# all details
Get-AzConsumptionUsageDetail -ResourceGroup "demo-rg" -StartDate 2021-12-01 -
EndDate 2022-01-27 | Select-Object *
#or some details
Get-AzConsumptionUsageDetail -ResourceGroup "demo-rg" -StartDate 2022-01-01 -
EndDate 2022-01-27 | Select-Object InstanceName, Currency, PretaxCost | Sort-
Object -Property PretaxCost -Descending
But is there an equivalent command in the az cmds , as the arm will be phased out by Microsoft ?

Note that, AzureRM module will be deprecated on 29 February 2024 not Az module.
The command Get-AzConsumptionUsageDetail belongs to Az module and still can be used to fetch the details of resource group costs.
I tried to reproduce the same in my environment and got the results successfully like below:
Get-AzConsumptionUsageDetail -ResourceGroup "RGName"
To fetch the consumption usage details for subscription scope, you can also make use of below query:
az consumption usage list --subscription "SubscriptionID" --start-date "2022-02-01" --end-date "2022-02-02"
Reference:
Get-AzureRmConsumptionUsageDetail (AzureRM.Consumption)

Related

Azure Monitor - Pass variable in Log Analytics query using Powershell

I am trying create Log Analytics query based Alert Rule using powershell script and command :- New-AzScheduledQueryRule .
Here I am trying to declare a variable called $ResourceGroup and $SubscriptionID in powershell script and want to use this in Log analytics query, so i can call script and pass arguments of Resource Group and subscription and Log Alert Query Rule will be created for scope of ResourceGroup . But when I try to deploy the Log query Alert Rule , the variables are not recognized inside query.
`$query='AzureMetrics
| where ResourceId has "Microsoft.Network/azureFirewalls"
| where MetricName=="FirewallHealth"
| where Maximum <100
| project FirewallHealth=toint(Maximum),Resource, ResourceGroup'
$source = New-AzScheduledQueryRuleSource -Query $query -DataSourceId "/subscriptions/$SubscriptionIDWS/resourcegroups/$ResourceGroupWS/providers/microsoft.operationalinsights/workspaces/$LogAnalyticsWSName" -QueryType ResultCount
New-AzScheduledQueryRule -ResourceGroupName $ResourceGroupLAWorkspace -Location "eastus" -Action $alertingAction -Enabled $true -Description $($AlertDescription) -Schedule $schedule -Source $source -Name $($AlertName)

New automation variable by cli or ansible

After create a runbook and edit content, I want to create variable and set value for them. How can I do it by ansible or azure cli ?
Please help me
Azure Automation stores each encrypted variable securely. When you create a variable, you can specify its encryption and storage by Azure Automation as a secure asset.
You must set the value with the Set-AzAutomationVariable cmdlet or the internal Set-AutomationVariable cmdlet. You use the Set-AutomationVariable in your runbooks that are intended to run in the Azure sandbox environment, or on a Windows Hybrid Runbook Worker.
You can create variables and set value for them using PowerShell script.
$rgName = "ResourceGroup01"
$accountName = "MyAutomationAccount"
$vm = Get-AzVM -ResourceGroupName "ResourceGroup01" -Name "VM01" | Select Name, Location,Extensions
New-AzAutomationVariable -ResourceGroupName "ResourceGroup01" -AutomationAccountName "MyAutomationAccount" -Name "MyComplexVariable" -Encrypted $false -Value $vm
$vmValue = Get-AzAutomationVariable -ResourceGroupName "ResourceGroup01" -AutomationAccountName "MyAutomationAccount" -Name "MyComplexVariable"
$vmName = $vmValue.Value.Name
$vmTags = $vmValue.Value.Tags
Reference: Manage variables in Azure Automation | Microsoft Docs

Powershell Script to download Azure recommendations

Login-AzAccount
$subs= az account list --query '[*].id'
Get-AzAdvisorRecommendation list --subscription $subs
I need to download the list of Azure recommendations on a tenant which will be having multiple subscriptions using Powershell script
Get-AzAdvisorRecommendation list --subscription $subs
Instead of --subscription you need to pass -subscription as a parameter to Get-AzAdvisorRecommendation cmdlet.
As per the Azure PowerShell cmdlet documentation, The Cmdlet Get-AzAdvisorRecommendation doesnt have any flag -subscription as parameter.
You can use this below script to pull the azure advisor recommendations for all subscriptions under a particular tenant.
$list=#()
$sub=get-azsubscription
Write-Output $sub
foreach( $item in $sub){
Set-AzContext -Subscription $item.Id -Tenant $item.TenantId -Force
$rg=Get-AzResourceGroup
foreach($r in $rg){
$list+=Get-AzAdvisorRecommendation -ResourceGroupName $r.ResourceGroupName
}
}
$list | Export-Csv C:\Users\list.csv
Here is the sample output for reference:
While testing the above script in our local environment, we have passed a single subscription to the cmdlet Get-azsubscription using the -subscriptionId flag.
Using this updated script, I can download the recommendations as well, thanks Venkatesh for your inputs.
Login-AzAccount
$result= 'C:\Users\new.csv'
$list=#()
$subs=get-AzSubscription
foreach( $sub in $subs){
Set-AzContext -Subscription $sub.Id -Force
$list+=Get-AzAdvisorRecommendation | Select-Object category, Impact, #{Name="SubscriptionName"; Expression={$sub.name}}, #{Name="SubscriptionID";
Expression={$sub.Id}}, #{Name="Recommendation"; Expression=$_.ShortDescription.Problem}}, ImpactedField, ImpactedValue,RecommendationTypeId, LastUpdated, MetaData, SuppressionId, Name,
resourceid
}
$list | Export-Csv $result -NoTypeInformation

Install extension on both Classic and ARM VMs with single PowerShell command

I have a script that installs OMS extensions to all ARM VMs in the subscription. The problem is that I have subscriptions that contain only ARM VMs, subscriptions that contain only Classic VMs, and subscription that have both types of VMs. How can I modify the script to work in all of the conditions? The script is:
#This script installs OMS Monitoring Agent to all VMs in the selected Subscription.
#Before running this script, the user must login to Azure account and select target subscription.
#Example:
#Login-AzureRmAccount
#Select-AzureRmSubscription 'SubscriptionName'
$WorkspaceID = 'Provide Workspace ID here'
$WorkspaceKey = 'Provide Workspace key here'
$VMs = Get-AzureRmVM
$VMs.where({$_.osprofile.windowsconfiguration}) | ForEach-Object {
"Installing Microsoft.EnterpriseCloud.Monitoring.MicrosoftMonitoringAgent Extension: {0}" -f $_.id
Set-AzureRmVMExtension -ResourceGroupName $_.ResourceGroupName -VMName $_.Name -Name omsAgent -Publisher 'Microsoft.EnterpriseCloud.Monitoring' `
-ExtensionType 'MicrosoftMonitoringAgent' -AsJob -TypeHandlerVersion '1.0' -Location $_.Location -ForceRerun 'yesh' `
-SettingString ( "{'workspaceId': '$WorkspaceID'}") `
-ProtectedSettingString "{'workspaceKey': '$WorkspaceKey'}" |
Add-Member -Name VM -Value $_.Id -MemberType NoteProperty
}
Since you got both classic and ARM VMs, you got two different deployment models, hence two different PowerShell modules you are using.
In other words, you need to log in separately for each and have separate scripts for using them.
In the classic model you need to run the following cmdlet to login and access your VMs:
Add-AzureAccount
Get-AzureVM | Set-AzureVMExtension ``
-Publisher 'Microsoft.EnterpriseCloud.Monitoring' ``
-ExtensionName 'MicrosoftMonitoringAgent' ``
-Version '1.*' ``
-PublicConfiguration "<workspace id>" ``
-PrivateConfiguration "<workspace key>" ``
While searching for information I found this script. It's a script for on-boarding VMs from single, or multiple subscriptions, using both deployment models.

How to get subscription id from the VM in AZURE

Is there a way to get the subscription id from the running (LINUX)VM instance in AZURE?
Can WALinuxAgent read the subscription ID from the internal server ?
This can be achieved using the Azure Instance Metadata Service. Calling this service from your VM will return a JSON with SubscriptionId among other useful data. Sample Microsoft bash script for calling the metadata service (with updated version in the request):
sudo apt-get install curl
sudo apt-get install jq
curl -H Metadata:True "http://169.254.169.254/metadata/instance?api-version=2017-08-01&format=json" | jq .
See "Response" section in provided link for sample response, with subscriptionId.
You can use powershell to achieve this.
First of all.
What kind of VM deployment model?
ARM
In this case it very simple.
$vm = Get-AzureRmVM -ResourceGroupName $resourceGroupName -Name $vmName
$vm.Id
You'll see - "/subscriptions/{subscriptionId}/..."
Classic
If you know resource group VM was deployed to, use following:
$resource = Get-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.ClassicCompute/virtualMachines -Name $vmName
$resource.ResourceId
Same - you"ll see "/subscriptions/{subscriptionId}/..."
Way to find resourceGroupName, if unknown (in case you write some automative script):
$vm = Get-AzureVM | Where {$_.Name -eq $vmName}
$service = Get-AzureService -ServiceName $vm.ServiceName
$service.ExtendedProperties.ResourceGroup
Hope it helps

Resources