New-AzPolicyAssignment - Paramter is not being assigned - azure

I am trying to assign a built-in policy to scope through PowerShell, it is being assigned however the parameter is not being added to the assignment.
In Particular, "Deploy Log Analytics agent for Linux VMs", is being assigned correctly but upon checking assignment, the policy is correctly assigned but parameter "logAnalytics" is empty however we already have a LogAnalytics workspace.
Connect-AzAccount
$subscriptionID ='ABCDFGG-ADSFSDF--SFSDF'
get-azsubscription -SubscriptionId $subscriptionID| set-azcontext
$PolicyName = 'Deploy Log Analytics agent for Linux VMs'
$NewName = 'Deploy Log Analytics agent for Linux VMs-Aug04-2'
# Get a reference to the policy definition to assign
$PolicyAssign = Get-AzPolicyDefinition | Where-Object { $_.Properties.DisplayName -eq $PolicyName}
$Paramter = #{'logAnalytics'=('LA-TEST-EU1')}
New-AzPolicyAssignment -Name $NewName -DisplayName $NewName -Scope /subscriptions/$($SubscriptionId) -PolicyDefinition $PolicyAssign -PolicyParameterObject $Paramter -Location 'eastUS' -AssignIdentity

The logAnalytics parameter value should be in the format of the Resource ID:
/subscriptions/[SUBSCRIPTIION-ID]/resourcegroups/[RESOURCEGROUP-NAME]/providers/microsoft.operationalinsights/workspaces/[WORKSPACENAME]
If you go to your Log Analytics Workspace > Properties you will find the Resource ID. That ID is what you need to use.

Related

How can we create 1 action group in Azure to trigger a logic app for multiple subscriptions

My logic app is sitting in x subscription.
And I need a set of y, z subscriptions to be able to trigger this logic app via action group.
Is there a way I can create a single action group to enable it in budgets of all subscriptions to trigger that logic app?
In Azure portal, this is a limitation, so only way is to create a new resource group and an action group within it for all the subscriptions individually to connect to a particular logic app.
It is possible to add action group for multiple subscriptions using Azure PowerShell.
You can try below script to achieve it:
$context = Get-AzSubscription -SubscriptionId "<Provide the subscriptionId in which the action group exists>"
Set-AzContext $context
$actionGroup = Get-AzActionGroup -name "<actiongroupname>" -ResourceGroupName "xxxxxxxx"
$subscription = Get-AzSubscription | select subscriptionId,tenantId | Format-table
foreach($sub in $subscription) {
$context = Get-AzSubscription -subscriptionId $sub -TenantId $tenantID
set-AZContext $context
$setactionGroup = set-AzActionGroup -Name $actionGroup -ResourceGroupName $Resourcegroup -Receiver $email //creates a new action group or modifies the existed one's
write-host "Action added"
}
Output:
Action triggered in other subscription in Portal:

How to get the Resource Group of a resource in Azure?

I have resources in a Resource Group in Azure and it wont let me move the resource because it is in a Resource Group that is not the hosting Resource Group even though it has been moved .
I have tried to run the command in Powershell az resource list but cant seem to see the hosting Resource Group of the resource.
Is there a command I can run in Powershell that will give the current Resource Group of the resource and the hosting Resource Group of the resource?
Is there a Powershell command that will give the current Resource Group of the resource?
Yes its the Get-AzureRmResource command:
$resourceId = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}"
$resource = Get-AzureRmResource -ResourceId $resourceId
$resourceGroupName = $resource.ResourceGroupName
Fortunately there's an alternative to avoid specifying the "ResourceGroupName" which you're trying to find and that's specifying the ResourceType..
$resourceGroupName = Get-AzureRmResource -ResourceName {resourceName} -ResourceType {resourceType} | Select-Object -ExpandProperty ResourceGroupName
Also note the -ExpandProperties parameter in the documentation to include the resource properties.
Based on the shared information, I have understood that you want to know the
hosted resource group(in which resource group got created before move operation).
current resource group (currently where the resource resides in).
We don't have any direct cmdlets to pull this information.
You can make use of activity logs to see the resource move operation and pull the information of resources which were moved & respective target resource group names accordingly using the below cmdlet
Get-AzActivityLog -StartTime (get-date).AddDays(-90) -EndTime (get-date)| Where-Object {$_.Authorization.Action -like "Microsoft.Resources/subscriptions/resourceGroups/moveresources/action" -and $_.OperationName -like "Move Resource Group Resources" -and $_.EventName -like "Begin request" } | Select -ExpandProperty Properties
Sample screenshot for your reference:
Note: Using Get-AzActivityLog cmdlet you can pull logs for only last 90days.

How to list down azure resources inside a particular subscription through powershell?

How to list down all the azure resources viz App services , App service plans , apim , service bus ,cosmos through powershell based on the subscription
The agenda here is to fetch these resources by passing the subscription as a parameter and getting all the respective resources inside that particular subscription.
I know how to fetch the resources using the resource group name as the parameter ,for eg
az appservice plan list [--resource-group]
But here I do not want to fetch based on the resource group , I need to pass the subscription so that all the resources inside that subscription get listed
list down azure resources inside a particular subscription through powershell
In PowerShell using PowerShell Commands:
Firstly, you need to set azure subscription using below PowerShell command:
xxx = Can be subcription name or id
Set-AzContext -Subscription "xxx"
Output:
Then use below PowerShell command to get all resources in the current Subdcription:
Get-AzResource | ft
Output:
ft means format table
Using the cli
az account set -s production
$Resources = az resource list | ConvertFrom-Json
$FilterType = #('Microsoft.Web/sites', 'Microsoft.ServiceBus/namespaces', 'Microsoft.DocumentDb/databaseAccounts')
$Resources | Where Type -in $FilterType
Using the Az module
Select-AzSubscription -Subscription 'Production'
$Resources = Get-azresource
$FilterType = #('Microsoft.Web/sites', 'Microsoft.ServiceBus/namespaces', 'Microsoft.DocumentDb/databaseAccounts')
$Resources | Where ResourceType -in $FilterType
AS for viewing just the types so you can make your selection, you can look in the portal URL of the resource or get all types present in your subscription using
# Query all resource first...
# Az cli
$Resources | Select -ExpandProperty Type -Unique | Sort-Object
# Az module
$Resources | Select -ExpandProperty ResourceType -Unique | Sort-Object

'Could not get the storage context' error when using Set-AzureStorageBlobContent in VSTS Azure Powershell task

I am using an Azure Powershell task in an Azure (VSTS) Pipeline to try and upload a file to an Azure Classic container.
As part of setting up the Azure Powershell task (ver 3.1.10), I added the Azure Classic subscription that this container lives in to the Project Settings\Service connections:
I then select that subscription in the pipeline task:
When I execute the script, the logs seem to show that the task is both setting and selecting the expected subscription:
However, if I don't explicitly (re-)create and pass in the AzureStorageContext to the Set-AzureStorageBlobContent function, the task fails with:
[error]Could not get the storage context. Please pass in a storage context or set the current storage context.
Is this expected behavior?
Is there any way around having to re-create and pass in the context when it appears that it already exists?
For example, is there an environment variable that might contain the context that was automatically created/selected that I can just pass in?
Update:
I suspect that if the
Select-AzureSubscription call seen in the logs used the -Current switch, this would work as I'm expecting it to.
However, since that command is automatically ran with no way to configure it via the pipeline task, it's not verifiable.
Perhaps this needs to be a feature request?
Excerpts from script:
#Not passing in the context results in the error
Set-AzureStorageBlobContent -File "$file" -Blob "$blobpath/$blah" -Container $blobname -Properties $properties -Force
#Passing in the context works:
$azureKey = Get-AzureStorageKey "$accountName"
$storagekey = [string]$azureKey.Primary
$context = New-AzureStorageContext "$accountName" -StorageAccountKey $storagekey
Set-AzureStorageBlobContent -File "$file" -Blob "$blobpath/$blah" -Container $blobname -Properties $properties -Context $context -Force
While I probably should just delete this question (upon discovering the "answer"), I suppose I will provide what I found after more debugging, etc.
TLDR; -- This is mostly me not grepping the concept that an Azure Subscription (context) does not correlate to an Azure Storage (context).
Is this expected behavior?
Yes.
Simply having a currently set subscription does not mean there's a currently set storage context.
Come to find out, our company has multiple storage accounts in the subscription I was using.
It could be that if a subscription only has one storage account, the function would succeed without specifying a context? Maybe I will research that later.
Is there any way around having to re-create and pass in the context when it appears that it already exists?
No (perhaps because of the multiple storage accounts in the subscription).
I will have to specify/select the current storage context from the current subscription (as I did in the "Passing in the context works" part in my question).
Here's how I arrived at this:
First, I verified what actually was being set (if anything) as the current [subscription] context and then explicitly (re-)setting it.
Running the command still failed.
So, it wasn't that the subscription wasn't being set (since it was).
$current = (Get-AzureSubscription -Current).SubscriptionName
Write-Host "current subscription is $current"
$setCurrent = $false
Write-Host "setCurrent is $setCurrent"
$setCurrent = Select-AzureSubscription -Current -SubscriptionName "CDN Subscription" -PassThru
if ($setCurrent)
{
Write-Host "current set"
$current = (Get-AzureSubscription -Current).SubscriptionName
Write-Host "current subscription is $current"
}
else
{
Write-Host "current not set"
}
It then dawned on me that maybe 'subscription' did not equal 'storage'.
To verify that, I then ran the following:
$current = (Get-AzureSubscription -Current).SubscriptionName
Write-Host "current subscription is $current"
$table = Get-AzureStorageAccount | Format-Table -AutoSize -Property #{Label="Name";Expression={$_.StorageAccountName}},"Label","Location" | Out-String
Write-Host "$table"
The result - 4 storage accounts in the subscription.
Ergo, I will need to specify the account I want to upload to

Azure Portal Data Factory Monitor & Manate Error 404 File or Directory not found

I have created an Azure Data Factory pipeline and deployed it. No issues. When I am in the Azure portal Data Factory blade, I click on the Monitor & Manage button and it takes me to a new tab in MS Edge with the following error:
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
Does anyone know what I need to do to be able to monitor my Azure Data Factory pipeline activity?
Thank you.
Not sure about the 404 error, maybe just an authentication issue. Or permissions in your Azure directory.
To monitor a pipeline or ADF in general I would suggest using PowerShell. There are loads of cmdlets to do things beyond the Azure Portal UI, including set a time slice status.
For example, to check what's currently 'In Progress' in your factory do something like this...
Import-Module Azure
#Params...
$AzureUser = "" # <<< enter username
$AzurePass = "" #<<< enter password
$AzureSubscription = "" # <<< enter subscription name
$ResourceGroup = "" # <<< enter resource group name
#Create credential
$SecurePassword = ConvertTo-SecureString $AzurePass -AsPlainText -Force
$PSCredential = New-Object System.Management.Automation.PSCredential ($AzureUser, $SecurePassword)
#Create Azure Connection
Login-AzureRmAccount -Credential $PSCredential | Out-Null
#Set context for subscription
$SubId = Get-AzureSubscription `
-SubscriptionName $AzureSubscription | SELECT SubscriptionId
Set-AzureRmContext -SubscriptionId $SubId.SubscriptionId | Out-Null
#Get ADF details
$ADFName = Get-AzureRmDataFactory `
-ResourceGroupName $ResourceGroup | SELECT DataFactoryName
Get-AzureRmDataFactoryActivityWindow `
-DataFactoryName $ADFName.DataFactoryName `
-ResourceGroupName $ResourceGroup `
| ? {$_.WindowState -eq "InProgress"}
Here's a link to the other cmdlets.
https://learn.microsoft.com/en-us/powershell/resourcemanager/azurerm.datafactories/v2.5.0/azurerm.datafactories
Hope this helps.
Thank you Paul, I want to start getting more familiar with Azure Powershell cmdlets.
I was able to access the portal Monitor & Manage by opening the portal in Chrome. Seems strange that MS Azure doesn't work in MS Edge but it does work in Chrome.
Thank you for you response.
Jon

Resources