Error while running Set-AzDiagnosticSetting command - azure

I created a Service principal in azure and assigned my service principal to the custom role which I have created with set of permission in that particular subscription.
With the service principal, I am able to create a key vault, Storage account, and function app and so on.
But when I execute this particular command
Set-AzDiagnosticSetting -Name $diagnosticLogsSettingsName -ResourceId $resource.ResourceId -StorageAccountId $diagnosticLogStorageAccount.Id -Enabled $true -Category $Categories -MetricCategory AllMetrics -RetentionEnabled $true -RetentionInDays 90
I am getting the following error
Set-AzDiagnosticSetting : Exception type: ErrorResponseException, Message: Null/Empty, Code: Null, Status
03:24:52 Error message: Set-AzDiagnosticSetting : Exception type: ErrorResponseException, Message: Null/Empty, Code: Null, Status
03:24:52 code:Forbidden, Reason phrase: Forbidden
Not sure why I am getting forbidden error
Could anyone Please help me to resolve the issue. Thanks in advance

Able to resolve the issue By adding the following permission to my custom role.
Microsoft.Insights/diagnosticSettings/write
I came to know to add this permission by executing the following command in "-Debug" mode which will give a clear error with the missing permission
Set-AzDiagnosticSetting -Name $diagnosticLogsSettingsName -ResourceId $resource.ResourceId -StorageAccountId $diagnosticLogStorageAccount.Id -Enabled $true -Category $Categories -MetricCategory AllMetrics -RetentionEnabled $true -RetentionInDays 90 -Debug
So just need to add -Debug flag at the end of command

One of the workaround you can follow to resolve the above issue;
Based on this GitHub Blog
For example to enable all available metrics and logs for a particular
resource (i.e,Resource01).
Set-AzDiagnosticSetting -ResourceId "Resource01" -Enabled $True
Alternatively, please find this SO THREAD| Enabling diagnostic settings for Azure Storage Account using PowerShell as suggested by ,#Joy Wang .
We have tried with the suggested PowerShell script and it works fine
NOTE:- Please make sure that we are providing the correct workspace ID(Log analytics workspace ID) and resource ID(Storage account resource ID) .
OUTPUT DETAILS FOR REFERENCE:-

Related

Cannot install IIS on the azure virtual machines

When following the tutorial https://learn.microsoft.com/en-us/azure/application-gateway/create-ssl-portal (using Free Trial as subcription) I always fail for the error
ErrorCode: AuthorizationFailed
ErrorMessage: The client '<mai e-mail address>' with object id'xxx' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/extensions/write' over scope '/subscriptions/yyy/resourceGroups/myResourceGroupAG/providers/Microsoft.Compute/virtualMachines/myVM/extensions/IIS' or the scope is invalid. If access was recently granted, please refresh your credentials.
ErrorTarget:
StatusCode: 403
ReasonPhrase: Forbidden
OperationID : zzz
When runnig the command
Set-AzVMExtension `>> -ResourceGroupName myResourceGroupAG `
>> -ExtensionName IIS `
>> -VMName myVM `
>> -Publisher Microsoft.Compute `
>> -ExtensionType CustomScriptExtension `
>> -TypeHandlerVersion 1.4 `
>> -SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server; powershell Add-Content -Path \"C:\\inetpub\\wwwroot\\Default.htm\" -Value $($env:computername)"}' `
>> -Location 'West US 2'
According to the portal Access control I (JM in the picture) should have role Virtual machine Contributor, but it doesn't help.
I tried with same PowerShell script command it is perfectly working for me.
You can try to run Disconnect-AzAccount and Clear-AzContext as a solution, so that the context of all the user are deleted and after that you can again login to azure from powershell by Connect-Azaccount.
The Owner Access in Subscription level is sufficient to perform the operation that you are trying to perform so , Separately giving the Virtual Machine Contributor Role is not required.
OR
To workaround this issue you can manually install IIS server .
Step 1: Login to you VM.
Step 2 : Manage->Add role and feature
Step 3 : Select Webserver IIS -> Next->Install

Enabling an azure metric alert V2

i am working on azure to monitor appservices and while a Continous deployments i am trying to build an automation task to disable/enable alert during deployments
For disabling alerts it is working
Get-AzMetricAlertRuleV2 -ResourceGroupName "<resource group name>" -Name "<alert name>" | Add-AzMetricAlertRuleV2 -DisableRule
For enabling the alerts after the deployments
Get-AzMetricAlertRuleV2 -ResourceGroupName "<resource group name>" -Name "<alert name>" | Add-AzMetricAlertRuleV2 -TargetResourceRegion "westeurope"
I get the following error:
Add-AzMetricAlertRuleV2: Exception type: ErrorResponseException, Message: Alert update failed. Updating from StaticThresholdCriteria and odata.type SingleResourceMultipleMetricCriteria to StaticThresholdCriteria and odata.type MultipleResourceMultipleMetricCriteria is not supported. Activity ID: ec818831-0516-44a7-92ff-cbddaa82b634., Code: BadRequest, Status code:BadRequest, Reason phrase: BadRequest
You should not change the region by passing -TargetResourceRegion param while enabling. Add-AzMetricAlertRuleV2 is trying add a new rule thinking that it's a new rule and failing because of the shown error message (Updating from StaticThresholdCriteria and odata.type SingleResourceMultipleMetricCriteria to StaticThresholdCriteria and odata.type MultipleResourceMultipleMetricCriteria is not supported). So just enable by without passing any other params like below.
Get-AzMetricAlertRuleV2 -ResourceGroupName "<resource group name>" -Name "<alert name>" | Add-AzMetricAlertRuleV2

Powershell Script continues to ask me to use Select-AzureSubscription although I have called it

I have an Azure runbook where I am trying to deallocate VMs. When I run the runbook I get the error
Stop-AzureVM : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to
set the default subscription.
I have used the below in my script.
Add-AzureRmAccount
Select-AzureRMSubscription
After calling the select, it prints out
PSComputerName : localhost
PSSourceJobInstanceId :
Account :
Environment :
Subscription :
Tenant :
with the correct subscrption and tenant information so it seems the select is working correctly, but for some reason I still cannot use the Stop-AzureVM cmdlet.
Any ideas?
The command Stop-AzureVM is Azure Service Management PowerShell command. It just can be used to stop Azure classic VM. But the command Add-AzureRmAccount is Azure Resource Management PowerShell command. After running the command, we just can manage Azure Resource Management resources. For more details, please refer to here and here.
So with Azure ARM VM, please use the command Stop-AzureRmVM to stop it. Meanwhile, regarding how to stop Azure classic VM, please refer to the following steps
Create Azure Classic Run As Account
Script
$ConnectionAssetName = "AzureClassicRunAsConnection"
# Get the connection
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
# Authenticate to Azure with certificate
$CertificateAssetName = $Conn.CertificateAssetName
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
#stop VM
Stop-AzureVM -ServiceName "ContosoService01" -Name "MyVM" -Force
Besides, regarding how to check if the VM is classic, please refer to the blog
Try Running the below :
Get-Module AzureRm.Profile -ListAvailable
This issue might occur when there is multiple instances of the module. If there are multiple instance remove the older modules and retain the new module.
To remove the old module : Uninstall-Module -Name AzureRm.Profile -RequiredVersion 4.6.0#(olderversion if you have any)

Azure Automation RunAs account access to Active Directory resource

I am trying to create a Runbook which does some maintenance in Active Directory. On creation of an Automation Account an "RunAs" account was created. In the runbook I connect to AD using the below command.
$connectionName = "AzureRunAsConnection"
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to AzureAD..."
Connect-AzureAD `
-TenantId $servicePrincipalConnection.TenantId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-LogLevel Info
This command runs fine, however the subsequent use of AD CMDLETS gives the following error,
$Users = Get-AzureADUser
Get-AzureADUser : Error occurred while executing GetUsers Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation.
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
The same is true for other CMDLETS in the AD module, not just this I have tried adding API permission through the registered application (relating to the Automation Account connection resource) in Active Directory but I am still facing the above privileges issue.
According to some test, you need to add the permissions of Azure AD but not Micorsoft Graph. It seems the Get-AzureADUser command use Azure AD graph in the backend. So we need to do the operations as below:
After that we can use the command Get-AzureADUser successfully(if you test the command in powershell, when you add the Azure AD permission, please close the powershell and reopen it and re-connect)

Get-AzureRmSqlDatabaseRestorePoints fails with authorisation error

I am trying to use Get-AzureRmSqlDatabaseRestorePoints and New-AzureRmSqlDatabaseRestorePoint for managing Azure Datwarehouse restore points and restore process using Powershell. I am getting authorisation error when I call this command. I have contributor privileges at subscription and sql server level.
What I noticed that subscription id in the https request for API call is different from my selected subscription.
How can I force these commands to use my active subscription or can I pass subscription when I call this command.
Error details
Body:
{
"error":
"code": "AuthorizationFailed",
"message": "The client 'xxxxxxx' with object id 'xxxx-xxxx-xxxx-xxxx' does not have authorization to perform action 'Microsoft.Sql/servers/databases/restorePoints/read' over scope
'/subscriptions/Subscription B/resourceGroups/DataWarehouse-SIT-rg/providers/Microsoft.Sql/servers/servername/databases/DataWarehouse'."
}
}
Full Code
$subscription = "Subscription A"
Login-AzureRmAccount -Subscription $subscription
Get-AzureRmSubscription
Select-AzureRmSubscription -Subscription $subscription
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName
$server = Get-AzureRmSqlServer -ResourceGroupName $resourceGroup.ResourceGroupName -ServerName $serverName
$database = Get-AzureRmSqlDatabase -ServerName $server.ServerName -ResourceGroupName $resourceGroup.ResourceGroupName -DatabaseName $databaseName
New-AzureRmSqlDatabaseRestorePoint -RestorePointLabel $restorePointName -ResourceGroupName $resourceGroup.ResourceGroupName -ServerName $server.ServerName -DatabaseName $database.DatabaseName
Thanks!
The error itself states that your account don't have READ permission to your restorepoints(Microsoft.Sql/servers/databases/restorePoints/read). Can you verify your permissions or try with another account?
Check whether do you have enough permission in your Subscription IAM
https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal
Subscription IAM Policy
Add your Email
Add your Role(s)
P.S: You need to contact your Subscription Owner in order to perform the above steps.
Issue was resolved after upgrading AzureRM module. Issue exists in module version 5.7.0 but it is resolved in version 6.6.0.

Resources