Error while creating new role assignment in Azure - azure

For a given Azure subscription I want to assign custom role to Service Principal. In order to achieve this, I first check if the custom role definition exists in the subscription. If the role does not exists I update the role definition's assignable scope to include this subscription. I am facing 'RoleDefinitionDoesNotExist' error intermittently when I try to assign role. How do I fix this?
My code:
$roleDef = Get-AzureRmRoleDefinition -Name $azureRmRole
if($roleDef -eq $null)
{
Select-AzureRmSubscription -SubscriptionName $prodSubscription
#Role definition exists in $prodSubscription
$newRole = Get-AzureRmRoleDefinition -Name $azureRmRole
#$scope = '/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx'
$newRole.AssignableScopes.Add($scope)
$def = Set-AzureRmRoleDefinition -Role $newRole
# I have verified that role definition is updated
}
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
New-AzureRmRoleAssignment -RoleDefinitionName $azureRmRole -ObjectId $SPNid -Scope $scope
Error:
New-AzureRmRoleAssignment : The specified role definition with ID 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx' does not exist.
At C:\Untitled1.ps1:71 char:1
+ New-AzureRmRoleAssignment -RoleDefinitionName $azureRmRole -ObjectId ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmRoleAssignment], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand

You should define your custom role like below:
{
"Name": "Virtual Machine Power Manager",
"IsCustom": true,
"Description": "Can monitor, stop, start and restart v2 ARM virtual machines.",
"Actions": [
"Microsoft.Storage/*/read",
"Microsoft.Network/*/read",
"Microsoft.Compute/*/read",
"Microsoft.Compute/virtualMachines/start/action",
"Microsoft.Compute/virtualMachines/powerOff/action",
"Microsoft.Compute/virtualMachines/deallocate/action",
"Microsoft.Compute/virtualMachines/restart/action",
"Microsoft.Authorization/*/read",
"Microsoft.Resources/subscriptions/resourceGroups/read",
"Microsoft.Insights/alertRules/*",
"Microsoft.Insights/diagnosticSettings/*",
"Microsoft.Support/*"
],
"NotActions": [
],
"AssignableScopes": [
"/subscriptions/c25b1c8e-xxxx-1111-abcd-1a12d7012123"
]
}
According to your description, you role's definition maybe wrong, you had better check it.
If you want to give custom role to a service principal, please try to use the following cmdlet.
New-AzureRmRoleAssignment -ServicePrincipalName "https://shuiweb.azurewebsites.net" `
-RoleDefinitionName 'Virtual Machine Power Manager' `
-Scope '/subscriptions/*******'
The blog:AZURE AUTOMATION RUNBOOKS WITH AZURE AD SERVICE PRINCIPALS AND CUSTOM RBAC ROLES will be helpful.

Related

display custom error message in Azure powershell and exit

I am trying to get the list of storages name for a specific subscription using powershell. If I have the correct subscription name, I get the result but if there is some mistype then I get this error:
Select-AzSubscription : Please provide a valid tenant or a valid subscription.
Select-AzSubscription -SubscriptionName $subName
CategoryInfo : CloseError: (:) [Set-AzContext], ArgumentException
FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand
What would be the best option to handle the error message and exit out from the script with a message "Couldn't find the subscription".
Here is the powershell code:
###Set a subscription name
$subName = "Test SubscriptionName"
Select-AzSubscription -SubscriptionName $subName
### Select storage accounts based for above subscription
$sAccount = Get-AzStorageAccount | select StorageAccountName
$sAccount
The better solution should be use the scripts below:
$subName = "Test SubscriptionName"
try{
Select-AzSubscription -SubscriptionName $subName -ErrorAction Stop
}
catch [System.ArgumentException]{
Write-Host "Couldn't find the subscription"
#use exit to exit the script
exit
}
#Select storage accounts based for above subscription
$sAccount = Get-AzStorageAccount | select StorageAccountName
$sAccount
You can just do a null test:
$sub = Select-AzSubscription -SubscriptionName $subName -ErrorAction SilentlyContinue
if ($sub -eq $null)
{
"Couldn't find the subscription"
## Add you exit code here!
}
else
{ "Good subname" }
I was able to solve it using try-catch method. Here is the solution:
$subName = "Test SubscriptionName"
Try {
Select-AzSubscription -SubscriptionName $subName -ErrorAction Stop
#Select storage accounts based for above subscription
$sAccount = Get-AzStorageAccount | select StorageAccountName
$sAccount
}
Catch{
Write-Host $_.Exception.Message
}

A parameter cannot be found that matches parameter name 'PasswordPolicies' in Powershell

I was trying to set the password for an Azure user to not expire forever. In the process I tried below commands
Get-AzADUser -ObjectId <valid Azure user> | Select-Object UserprincipalName,#{
>> N="PasswordNeverExpires";E={$_.PasswordPolicies -contains "DisablePasswordExpiration"}
>> }
UserPrincipalName PasswordNeverExpires
----------------- --------------------
<valid Azure user> False
To set PasswordNeverExpires to True, I executed below command
Set-AzADUser -ObjectId <valid Azure user> -PasswordPolicies DisablePasswordExpiration
But it throws an error as below:
Update-AzADUser : A parameter cannot be found that matches parameter name 'PasswordPolicies'.
At line:1 char:51
+ ... ADUser -ObjectId <valid Azure user> -PasswordPolicies Disable ...
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Update-AzADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Azure.Commands.ActiveDirectory.UpdateAzureADUserCommand
Can someone help me on this issue please.
Thanks,
Sri Ram.
Az Powershell doesn't provide the setting password policy feature.
Use Azure AD Powershell instead.
Set-AzureADUser -ObjectId <user ID> -PasswordPolicies DisablePasswordExpiration
If you are concerned about having to log in to Azure AD Powershell again, you can connect a session using an existing token associated with the active azure context.
For example:
# login
Connect-AzAccount -Tenant {your tenant}
# perform other Azure operations...
$currentAzureContext = Get-AzContext
$tenantId = $currentAzureContext.Tenant.Id
$accountId = $currentAzureContext.Account.Id
Connect-AzureAD -TenantId $tenantId -AccountId $accountId
Then you can run Set-AzureADUser cmd.

getting "Bad Request" error in powershell while transferring the nsg flow log to the storage account in different subscription in azure

I am getting "Bad Request" error while transferring the nsg flow log to the storage account in different subscription. My script is working fine while using the storage account of same subscription.
$workspaceResourceId = "/subscriptions/xxxxxxxxxxxxxxxxxxxxxxxx/resourcegroups/rg-log-mgmt-prd-westeurope-01/providers/microsoft.operationalinsights/workspaces/nbsapucscoms"
$workspaceGUID = "xxxxxxxxxxxxxxxxxx"
$workspaceLocation = "westeurope"
$n = Get-AzureRmNetworkSecurityGroup -ResourceGroupName rg-8kmiles-dfi-westeurope-01 -Name apitst-nsg
$NwName = 'NetworkWatcher_' + $n.Location
$NW = Get-AzureRmNetworkWatcher -ResourceGroupName NetworkWatcherRg -Name $NwName
#enter the storage account details.
$storageAccount="/subscriptions/xxxxxxxxxxxxxxx/resourceGroups/rg-log-mgmt-prd-westeurope-01/providers/Microsoft.Storage/storageAccounts/nvsswelogmgmt001"
$flowLogStatus=Get-AzureRmNetworkWatcherFlowLogStatus -NetworkWatcher $NW -TargetResourceId $n.Id
if($false -eq $flowLogStatus.Enabled){
#Configure Version 2 FLow Logs with Traffic Analytics Configured
Set-AzureRmNetworkWatcherConfigFlowLog -NetworkWatcher $NW -TargetResourceId $n.Id `
-StorageAccountId $storageAccount -EnableFlowLog $true -EnableTrafficAnalytics `
-WorkspaceResourceId $workspaceResourceId -WorkspaceGUID $workspaceGUID `
-WorkspaceLocation $workspaceLocation -EnableRetention $true -RetentionInDays 365
#Query Flow Log Status
$flowLogStatus=Get-AzureRmNetworkWatcherFlowLogStatus -NetworkWatcher $NW -TargetResourceId $n.Id
write-verbose "$($n.Name) Nsg Flow Log Enabled : $($flowLogStatus.Enabled)" -verbose
}
The error which i am getting is this
Set-AzureRmNetworkWatcherConfigFlowLog : Operation returned an invalid status
code 'BadRequest'
At C:\Users\singhniu\Desktop\Pipeline\TestNsgFlowLog.ps1:22 char:5
+ Set-AzureRmNetworkWatcherConfigFlowLog -NetworkWatcher $NW -Targe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmNetworkWatcherConfig
FlowLog], ErrorResponseException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Network.SetAzureNetwork
WatcherConfigFlowLogCommand
after debugging i came to know that i was using V1 storage account which does not support retention. for retention policy to be applied we need to upgrade it to V2.
bellow is the output after debugging.
Body:
{
"error": {
"code": "UnsupportedStorageAccountVersionWithRetention",
"message": "Storage /subscriptions/xxxxxxxxxxxxxxxxxxxxxxx/resourceGroups/rg-lo
g-mgmt-prd-westeurope-01/providers/Microsoft.Storage/storageAccounts/nvss is a V1 st
orage account and with retention policy. Only V2 storage account are supported with retention po
licy. Read more -> aka.ms/LogsHelp",
"details": []
}
}

Enable automatic key rotation for keyvault

I've been working on a solution to implement automatic key rotation for a storage account using keyvault. The script I'm using is listed below. The object ID is not a service principal (its my ObjectID).
$resourcegroup = "resourcegroupname"
$saname = "storageaccountname"
$vaultname = "keyvaultname"
$storage = Get-AzureRmStorageAccount -ResourceGroupName $resourcegroup -
StorageAccountName $saname
$userPrincipalId = $(Get-AzureRmADUser -ObjectId "my-object-id").Id
New-AzureRmRoleAssignment -ObjectId $userPrincipalId -RoleDefinitionName
'Storage Account Key Operator Service Role' -Scope $storage.Id
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultname -ObjectId $userPrincipalId - -PermissionsToStorage all
$regenPeriod = [System.Timespan]::FromDays(1)
Add-AzureKeyVaultManagedStorageAccount -VaultName $vaultname -AccountName
$saname -AccountResourceId $storage.Id -ActiveKeyName key2 -RegenerationPeriod $regenPeriod
But then I get the following error
Add-AzureKeyVaultManagedStorageAccount : Key vault service doesn't have proper permissions to access the storage account
https://something.vault.azure.net/storage/something
At line:17 char:1
+ Add-AzureKeyVaultManagedStorageAccount -VaultName $vaultname -Account ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureKeyVaultManagedStorageAccount], KeyVaultErrorException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.AddAzureKeyVaultManagedStorageAccount
You also need to assign Storage Account Key Operator Service Role to KeyVault's Service principal on the storage account.
Refer to the documentation here

Azure Automation: Service Principal account from different tenant authenticates but doesn't return service principal

I'm having issues executing a runbook aon a subscription in a different tenant.
This is what I have done so far:
1) Created a keyvault cert.
2) Exported .cer and .PFX of certificate.
3) Created a Service Principal on the rpgorch-aad account (300eab96-4619-4b6b-af42-8eb66506ab04)
4) Created a connection in Automation with that service principal's information
5) Uploaded password protected PFX to Automation certificate store
First, a working example from within the same tenant:
$connectionName = 'AzureRunasConnection'
"Getting Azure Connection $connectionName"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
"Logging in to Azure using Add-AzureRmAccount"
Add-AzureRmAccount -ServicePrincipal `
-Tenant $servicePrincipalConnection.TenantID `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint -Verbose
"Setting Context with Set-AzureRmContext"
Set-AzureRmContext -Tenant $servicePrincipalConnection.TenantID -SubscriptionId $servicePrincipalConnection.SubscriptionId -Verbose
"Writing Output of the Service Principal Connection"
write-output $servicePrincipalConnection
"Testing getting resource groups."
Get-AzureRmResourceGroup
Results:
Getting Azure Connection AzureRunasConnection
Logging in to Azure using Add-AzureRmAccount
PSComputerName : localhost
PSSourceJobInstanceId : Redacted
Environments : {AzureCloud, AzureChinaCloud, AzureUSGovernment}
Context : Microsoft.Azure.Commands.Profile.Models.PSAzureContext
Setting Context with Set-AzureRmContext
PSComputerName : localhost
PSSourceJobInstanceId : Redacted
Account : Redacted
Environment : AzureCloud
Subscription : Redacted
Tenant : Redacted
Writing Output of the Service Principal Connection
Name Value
---- -----
SubscriptionId Redacted
TenantId Redacted
ApplicationId Redacted
CertificateThumbprint Redacted
Testing getting resource groups.
PSComputerName : localhost
PSSourceJobInstanceId : Redacted
ResourceGroupName : Redacted
Location : eastus
Resources :
ResourcesTable :
ProvisioningState : Succeeded
Tags : {}
TagsTable :
ResourceId : /subscriptions/Redacted/resourceGroups/Redacted
Now the SAME code, but for the other tenant.
$connectionName = 'Redacted'
"Getting Azure Connection"
$connectionName
$Conn = Get-AutomationConnection -Name $connectionName
"Logging in to Azure using Add-AzureRmAccount"
Add-AzureRmAccount -ServicePrincipal `
-Tenant $Conn.TenantID `
-ApplicationId $Conn.ApplicationId `
-CertificateThumbprint $Conn.CertificateThumbprint -Verbose
"Setting Context with Set-AzureRmContext"
Set-AzureRmContext -Tenant $Conn.TenantID -SubscriptionId $Conn.SubscriptionId -Verbose
"Selecting subscriptionID "
$Conn.SubscriptionID
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
"Testing getting resource groups."
Get-AzureRmResourceGroup
Results:
Getting Azure Connection
RPGOrchResourceManagement
Logging in to Azure using Add-AzureRmAccount
Results:
PSComputerName : localhost
PSSourceJobInstanceId : Redacted
Environments : {AzureCloud, AzureChinaCloud, AzureUSGovernment}
Context : Microsoft.Azure.Commands.Profile.Models.PSAzureContext
Setting Context with Set-AzureRmContext
Set-AzureRmContext : Provided subscription Redacted does not exist
At ManageSingleVM:52 char:52
+
+ CategoryInfo : CloseError: (:) [Set-AzureRmContext], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand
PSComputerName : localhost
PSSourceJobInstanceId : Redacted
Environments : {AzureCloud, AzureChinaCloud, AzureUSGovernment}
Context : Microsoft.Azure.Commands.Profile.Models.PSAzureContext
Setting Context with Set-AzureRmContext
Set-AzureRmContext : Provided subscription Redacted does not exist
At ManageSingleVM:52 char:52
+
+ CategoryInfo : CloseError: (:) [Set-AzureRmContext], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand
I figured out the answer to this. For anyone else looking, I needed to run this command on the Application ID:
New-AzureRMRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $ApplicationId | Write-Verbose -ErrorAction SilentlyContinue

Resources