source/Private/AzureResourceOperations.ps1
|
function Connect-RJAzureContext { [CmdletBinding()] [OutputType([PSCustomObject])] param( [string]$SubscriptionId, [switch]$TenantOnly ) Write-Verbose "Checking Azure connection..." # Return cached context if it still matches the active Az session if ($script:RJAzureContextCache) { if ($TenantOnly -or -not $SubscriptionId -or $SubscriptionId -eq $script:RJAzureContextCache.SubscriptionId) { $activeContext = Get-AzContext -ErrorAction SilentlyContinue if ($activeContext -and $activeContext.Tenant.Id -eq $script:RJAzureContextCache.TenantId -and ($TenantOnly -or ($script:RJAzureContextCache.SubscriptionId -and $activeContext.Subscription.Id -eq $script:RJAzureContextCache.SubscriptionId))) { Write-Verbose "Using cached Azure context (Tenant: $($script:RJAzureContextCache.TenantName), Subscription: $($script:RJAzureContextCache.SubscriptionName))" if ($TenantOnly) { return [PSCustomObject]@{ TenantId = $script:RJAzureContextCache.TenantId TenantName = $script:RJAzureContextCache.TenantName SubscriptionId = $null SubscriptionName = $null } } return $script:RJAzureContextCache } Write-Verbose "Active Az context changed — re-evaluating connection." $script:RJAzureContextCache = $null } } $context = Get-AzContext -ErrorAction SilentlyContinue if (-not $context -or -not $context.Account) { Write-Information "Connecting to Azure..." $connectParams = @{} if ($SubscriptionId) { $connectParams.SubscriptionId = $SubscriptionId } Connect-AzAccount @connectParams -WhatIf:$false -Confirm:$false | Out-Null $context = Get-AzContext -ErrorAction SilentlyContinue if (-not $context -or -not $context.Account) { throw "Failed to establish Azure connection" } Write-Verbose "Successfully connected to Azure as $($context.Account.Id)" } else { Write-Verbose "Already connected to Azure as $($context.Account.Id)" } $allContexts = @(Get-AzContext -ListAvailable) # Tenant selection $tenantGroups = @($allContexts | Group-Object { $_.Tenant.Id }) if ($tenantGroups.Count -gt 1) { $counter = 0 $tenantOptions = @($tenantGroups | ForEach-Object { $counter++ $firstContext = $_.Group[0] $tenantName = if ($firstContext.Tenant.Name) { $firstContext.Tenant.Name } else { $firstContext.Tenant.Id } [PSCustomObject]@{ Key = $firstContext.Tenant.Id Display = "[$counter] $tenantName" Description = "Tenant ID: $($firstContext.Tenant.Id)" } }) $tenantOptions += [PSCustomObject]@{ Key = $null Display = "[$($counter + 1)] Cancel" Description = "Cancel and return" } $selectedTenantId = Show-RJGenericMenu -Title "Multiple Azure Tenants Found" -Prompt "Select a tenant:" -Options $tenantOptions if ($null -eq $selectedTenantId) { return $null } $tenantContexts = @($allContexts | Where-Object { $_.Tenant.Id -eq $selectedTenantId }) } else { $selectedTenantId = $tenantGroups[0].Group[0].Tenant.Id $tenantContexts = @($tenantGroups[0].Group) } # True only when the user picked a tenant from the menu above. With a single known tenant the # requested subscription may legitimately live in a tenant we haven't signed into yet, so the # fallback sign-in below must not be pinned to it. $tenantExplicitlySelected = $tenantGroups.Count -gt 1 if (-not $TenantOnly) { $tenantContexts = @($tenantContexts | Where-Object { $_.Subscription.Id }) } # Subscription selection if ($TenantOnly) { $selectedContext = if ($context.Tenant.Id -eq $selectedTenantId) { $context } else { $tenantContexts[0] } } elseif ($SubscriptionId) { $targetContext = $tenantContexts | Where-Object { $_.Subscription.Id -eq $SubscriptionId } if ($targetContext) { $selectedContext = $targetContext } else { Write-Verbose "Switching to subscription $SubscriptionId" try { Set-AzContext -SubscriptionId $SubscriptionId -WhatIf:$false -Confirm:$false -ErrorAction Stop | Out-Null } catch { Write-Information "Subscription $SubscriptionId not found in current contexts. Connecting to Azure..." $fallbackParams = @{ SubscriptionId = $SubscriptionId } if ($tenantExplicitlySelected) { $fallbackParams.TenantId = $selectedTenantId } Connect-AzAccount @fallbackParams -WhatIf:$false -Confirm:$false | Out-Null } $selectedContext = Get-AzContext if (-not $selectedContext -or $selectedContext.Subscription.Id -ne $SubscriptionId) { throw "Failed to switch to subscription $SubscriptionId" } if ($tenantExplicitlySelected -and $selectedContext.Tenant.Id -ne $selectedTenantId) { throw "Subscription $SubscriptionId belongs to tenant $($selectedContext.Tenant.Id), not the selected tenant $selectedTenantId" } } } elseif ($tenantContexts.Count -gt 1) { $counter = 0 $subOptions = @($tenantContexts | ForEach-Object { $counter++ [PSCustomObject]@{ Key = $_.Subscription.Id Display = "[$counter] $($_.Subscription.Name)" Description = "ID: $($_.Subscription.Id)" } }) $subOptions += [PSCustomObject]@{ Key = $null Display = "[$($counter + 1)] Cancel" Description = "Cancel and return" } $selectedSubId = Show-RJGenericMenu -Title "Multiple Azure Subscriptions Found" -Prompt "Select a subscription:" -Options $subOptions if ($null -eq $selectedSubId) { return $null } $selectedContext = $tenantContexts | Where-Object { $_.Subscription.Id -eq $selectedSubId } } else { $selectedContext = $tenantContexts[0] } if (-not $TenantOnly -and -not $selectedContext.Subscription.Id) { throw "No Azure subscription is available in tenant $selectedTenantId. This command works with Azure resources and requires one." } # Set the selected context as active if ($selectedContext.Subscription.Id -ne $context.Subscription.Id -or $selectedContext.Tenant.Id -ne $context.Tenant.Id) { Set-AzContext -Context $selectedContext -WhatIf:$false -Confirm:$false -ErrorAction Stop | Out-Null Write-Verbose "Switched to context: $($selectedContext.Subscription.Name)" } $subscription = if (-not $TenantOnly) { $selectedContext.Subscription } $result = [PSCustomObject]@{ TenantId = $selectedContext.Tenant.Id TenantName = $selectedContext.Tenant.Name SubscriptionId = $subscription.Id SubscriptionName = $subscription.Name } Write-Verbose "Selected tenant: $($result.TenantName) ($($result.TenantId))" if (-not $TenantOnly) { Write-Verbose "Selected subscription: $($result.SubscriptionName) ($($result.SubscriptionId))" } $script:RJAzureContextCache = $result return $result } function Test-ResourceGroup { <# .SYNOPSIS Verifies that a resource group exists. .PARAMETER ResourceGroupName The name of the resource group to check. .OUTPUTS The resource group object if it exists. Throws if not found. #> [CmdletBinding()] param( [Parameter(Mandatory)] [string]$ResourceGroupName ) Write-Verbose "Verifying resource group '$ResourceGroupName' exists..." try { $rg = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction Stop Write-Verbose "Resource group found in '$($rg.Location)'" return $rg } catch { throw "Resource group '$ResourceGroupName' not found." } } function Get-ArmTemplatePath { <# .SYNOPSIS Resolves the path to a JSON ARM template bundled with the module. .PARAMETER RelativePath Path relative to the azure-resources directory. .OUTPUTS Absolute path to the template file. #> [CmdletBinding()] param( [Parameter(Mandatory)] [string]$RelativePath ) # $PSScriptRoot points to source/Private/ when dot-sourced from the module # Module root is two levels up: source/Private/ -> source/ -> module root $moduleRoot = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent $templatePath = Join-Path -Path (Join-Path -Path $moduleRoot -ChildPath "azure-resources") -ChildPath $RelativePath if (-not (Test-Path $templatePath)) { throw "ARM template not found at: $templatePath" } return $templatePath } function New-RJArmDeployment { <# .SYNOPSIS Deploys a JSON ARM template to a resource group. .PARAMETER ResourceGroupName The target resource group. .PARAMETER TemplatePath Path to the JSON ARM template file. .PARAMETER DeploymentName Name for the deployment (for tracking in Azure portal). .PARAMETER Parameters Optional hashtable of template parameters. .OUTPUTS Hashtable of deployment outputs. #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [Parameter(Mandatory)] [string]$TemplatePath, [Parameter(Mandatory)] [string]$DeploymentName, [hashtable]$Parameters = @{} ) Write-Verbose "Deploying '$DeploymentName' from $(Split-Path $TemplatePath -Leaf)..." if (-not $PSCmdlet.ShouldProcess("Resource group '$ResourceGroupName'", "Deploy ARM template '$DeploymentName'")) { return } $deployment = Invoke-RJArmDeploymentWithProgress -ResourceGroupName $ResourceGroupName ` -TemplatePath $TemplatePath ` -DeploymentName $DeploymentName ` -Parameters $Parameters Write-Verbose "Deployment '$DeploymentName' succeeded" return $deployment.Outputs } function Wait-RJServicePrincipalReplication { <# .SYNOPSIS Waits for a service principal to replicate across Azure AD with exponential backoff. .PARAMETER ServicePrincipalId The object ID of the service principal to wait for. .OUTPUTS [bool] True if replicated, False if timed out. #> [OutputType([bool])] [CmdletBinding()] param( [Parameter(Mandatory)] [string]$ServicePrincipalId ) Write-Information "Waiting for service principal to replicate across Microsoft Entra ID..." for ($attempt = 1; $attempt -le $ReplicationMaxAttempts; $attempt++) { if ($attempt -gt 1) { $delay = $ReplicationBaseDelaySeconds * [math]::Pow(2, $attempt - 2) # 8, 16, 32 Write-Information " Not yet available - retrying in $delay seconds (attempt $attempt/$ReplicationMaxAttempts)..." Start-Sleep -Seconds $delay } try { $sp = Get-AzADServicePrincipal -ObjectId $ServicePrincipalId -ErrorAction Stop if ($sp) { Write-Verbose "Service principal replicated successfully" return $true } } catch { if ($_.FullyQualifiedErrorId -notmatch 'Request_ResourceNotFound') { throw # Unexpected error — don't retry } if ($attempt -eq $ReplicationMaxAttempts) { Write-Warning "Service principal not found after $ReplicationMaxAttempts attempts. Proceeding anyway..." return $false } Write-Verbose "Service principal not yet available. Retrying..." } } return $false } function Test-RJRoleAssignmentExist { <# .SYNOPSIS Checks whether a role assignment already exists for a given principal and role on a scope. .PARAMETER Scope The Azure resource ID to check for role assignments. .PARAMETER PrincipalId The object ID of the service principal. .PARAMETER RoleDefinitionId The GUID of the role definition (without the full resource ID prefix). .OUTPUTS [bool] True if the role assignment already exists. #> [OutputType([bool])] [CmdletBinding()] param( [Parameter(Mandatory)] [string]$Scope, [Parameter(Mandatory)] [string]$PrincipalId, [Parameter(Mandatory)] [string]$RoleDefinitionId ) try { $existing = Get-AzRoleAssignment -ObjectId $PrincipalId -Scope $Scope -RoleDefinitionId $RoleDefinitionId -ErrorAction SilentlyContinue if ($existing) { Write-Verbose "Role assignment already exists for principal '$PrincipalId' with role '$RoleDefinitionId' on scope '$Scope'" return $true } } catch { Write-Verbose "Could not check existing role assignments: $($_.Exception.Message). Will attempt assignment." } return $false } function Get-RJLogAnalyticsWorkspaceLocation { <# .SYNOPSIS Returns the region of an existing Log Analytics workspace in the resource group. .PARAMETER ResourceGroupName The resource group to look in. .PARAMETER WorkspaceName The name of the Log Analytics workspace. .OUTPUTS The workspace location, or $null when the workspace does not exist. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [Parameter(Mandatory)] [string]$WorkspaceName ) $workspace = Get-AzResource -ResourceGroupName $ResourceGroupName ` -ResourceType 'Microsoft.OperationalInsights/workspaces' -ErrorAction Stop | Where-Object { $_.Name -eq $WorkspaceName } if (-not $workspace) { Write-Verbose "Log Analytics workspace '$WorkspaceName' not found in resource group '$ResourceGroupName'." return $null } Write-Verbose "Log Analytics workspace '$WorkspaceName' exists in location '$($workspace.Location)'." return $workspace.Location } function Get-RJWorkplaceCloudStorageAccount { <# .SYNOPSIS Returns an existing storage account in the resource group, including its properties. .PARAMETER ResourceGroupName The resource group to look in. .PARAMETER StorageAccountName The name of the storage account. .OUTPUTS The storage account resource, or $null when the storage account does not exist. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [Parameter(Mandatory)] [string]$StorageAccountName ) $storageAccount = Get-AzResource -ResourceGroupName $ResourceGroupName ` -ResourceType 'Microsoft.Storage/storageAccounts' -ExpandProperties -ErrorAction Stop | Where-Object { $_.Name -eq $StorageAccountName } if (-not $storageAccount) { Write-Verbose "Storage account '$StorageAccountName' not found in resource group '$ResourceGroupName'." return $null } Write-Verbose "Storage account '$StorageAccountName' exists in location '$($storageAccount.Location)'." return $storageAccount } function Get-RJWorkplaceCloudStorageDefaultName { <# .SYNOPSIS Returns the default Workplace Cloud Storage account name for a resource group. .DESCRIPTION 'strj' followed by the first 20 hex characters of the SHA-256 hash of the lowercase resource group ID. The same resource group always yields the same name. .PARAMETER ResourceGroupName The resource group the storage account is deployed to. .OUTPUTS The storage account name (24 lowercase letters and digits). #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$ResourceGroupName ) $hex = Get-RJResourceGroupIdHash -ResourceGroupName $ResourceGroupName return "strj$($hex.Substring(0, 20))" } function Get-RJResourceGroupIdHash { <# .SYNOPSIS Returns the SHA-256 hash of the lowercase resource group ID as 64 lowercase hex characters. .PARAMETER ResourceGroupName The resource group to hash. .OUTPUTS The hash (64 lowercase hex characters). #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$ResourceGroupName ) $resourceGroupId = (Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction Stop).ResourceId.ToLowerInvariant() $sha256 = [System.Security.Cryptography.SHA256]::Create() try { $hash = $sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($resourceGroupId)) } finally { $sha256.Dispose() } return -join ($hash | ForEach-Object { $_.ToString('x2') }) } function Get-RJKeyVault { <# .SYNOPSIS Returns an existing Key Vault in the resource group, including its properties. .PARAMETER ResourceGroupName The resource group to look in. .PARAMETER KeyVaultName The name of the Key Vault. .OUTPUTS The Key Vault resource, or $null when the Key Vault does not exist. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [Parameter(Mandatory)] [string]$KeyVaultName ) $keyVault = Get-AzResource -ResourceGroupName $ResourceGroupName ` -ResourceType 'Microsoft.KeyVault/vaults' -ExpandProperties -ErrorAction Stop | Where-Object { $_.Name -eq $KeyVaultName } if (-not $keyVault) { Write-Verbose "Key Vault '$KeyVaultName' not found in resource group '$ResourceGroupName'." return $null } Write-Verbose "Key Vault '$KeyVaultName' exists in location '$($keyVault.Location)'." return $keyVault } function Get-RJKeyVaultDefaultName { <# .SYNOPSIS Returns the default Key Vault name for a resource group. .DESCRIPTION 'kv-rj-' followed by the first 18 hex characters of the SHA-256 hash of the lowercase resource group ID. The same resource group always yields the same name. .PARAMETER ResourceGroupName The resource group the Key Vault is deployed to. .OUTPUTS The Key Vault name (24 characters). #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$ResourceGroupName ) $hex = Get-RJResourceGroupIdHash -ResourceGroupName $ResourceGroupName return "kv-rj-$($hex.Substring(0, 18))" } function Initialize-RJAzureResourcesServicePrincipal { <# .SYNOPSIS Ensures the RealmJoin Azure Resources service principal exists and returns its object ID. .PARAMETER ResourceGroupName The resource group used for the service principal ARM deployment when the service principal is missing. .OUTPUTS [string] The object ID of the RealmJoin Azure Resources service principal. #> [CmdletBinding(SupportsShouldProcess)] [OutputType([string])] param( [Parameter(Mandatory)] [string]$ResourceGroupName ) $appId = Get-RJAzureResourcesAppId $existingSp = Get-ServicePrincipalByAppId -AppId $appId if ($existingSp) { Write-Information " Service principal '$($existingSp.DisplayName)' already exists — skipping deployment." Write-Verbose "RJ Service Principal ID: $($existingSp.Id)" return $existingSp.Id } if (-not $PSCmdlet.ShouldProcess("Service principal for AppId '$appId'", "Deploy")) { return $null } $spTemplatePath = Get-ArmTemplatePath -RelativePath "realmJoinServicePrincipal.json" $outputs = New-RJArmDeployment -ResourceGroupName $ResourceGroupName ` -TemplatePath $spTemplatePath ` -DeploymentName "rj-serviceprincipal-$(Get-Date -Format 'yyyyMMddHHmmss')" ` -Parameters @{ realmJoinAzureResourcesAppId = $appId } $rjServicePrincipalId = $outputs["servicePrincipalId"].Value Write-Verbose "RJ Service Principal ID: $rjServicePrincipalId" $null = Wait-RJServicePrincipalReplication -ServicePrincipalId $rjServicePrincipalId return $rjServicePrincipalId } function Set-RJAutomationAccountResource { <# .SYNOPSIS Orchestrates the full Automation Account deployment (4 steps). .DESCRIPTION Step 1: Configure RealmJoin Service Principal (deployed only if it does not exist yet) Step 2: Configure Automation Account with system-assigned managed identity Step 3: Configure permissions (Graph, Exchange, Defender, SharePoint app roles) Step 4: Configure Entra ID directory roles of the managed identity .PARAMETER ResourceGroupName The target resource group (must exist). .PARAMETER AutomationAccountName Optional name for the automation account. Auto-generated if not provided. .PARAMETER PermissionsManifestUrl Optional URL of a permissions manifest to use instead of the published one. .PARAMETER DirectoryRolesManifestUrl Optional URL of a directory roles manifest to use instead of the published one. .PARAMETER RunbookBranch Branch of the runbooks repository to download the manifests from. .OUTPUTS Hashtable with Success, Outputs (AutomationAccountId, AutomationAccountName, AutomationAccountPrincipalId, ServicePrincipalId, PermissionsAssigned: one {name, appId, permissionCount} entry per resource application, DirectoryRolesAssigned and DirectoryRolesExisting: role display names). #> [CmdletBinding(SupportsShouldProcess)] [OutputType([hashtable])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [string]$AutomationAccountName, [string]$PermissionsManifestUrl, [string]$DirectoryRolesManifestUrl, [string]$RunbookBranch = $DefaultRunbookBranch ) $result = @{ Success = $false Outputs = @{} } if (-not $PSCmdlet.ShouldProcess("Resource group '$ResourceGroupName'", "Deploy Automation Account, permissions and directory roles")) { return $result } $manifestSource = if ($PermissionsManifestUrl) { $PermissionsManifestUrl } else { Get-RJRunbookManifestUrl -Type Permissions -Branch $RunbookBranch } Write-Information "Loading permissions manifest from $manifestSource" $permissionsManifest = Get-RJRunbookManifest -Type Permissions -Url $PermissionsManifestUrl -Branch $RunbookBranch $rolesManifestSource = if ($DirectoryRolesManifestUrl) { $DirectoryRolesManifestUrl } else { Get-RJRunbookManifestUrl -Type DirectoryRoles -Branch $RunbookBranch } Write-Information "Loading directory roles manifest from $rolesManifestSource" $directoryRoles = Get-RJRunbookManifest -Type DirectoryRoles -Url $DirectoryRolesManifestUrl -Branch $RunbookBranch # Step 1: Configure RealmJoin Service Principal Write-Information "Step 1/4: Configuring RealmJoin Service Principal..." $rjServicePrincipalId = Initialize-RJAzureResourcesServicePrincipal -ResourceGroupName $ResourceGroupName # Step 2: Configure Automation Account Write-Information "Step 2/4: Configuring Automation Account..." $aaTemplatePath = Get-ArmTemplatePath -RelativePath "azure-automation-account/automationAccount.json" $step2Params = @{ rjServicePrincipalId = $rjServicePrincipalId contributorRoleId = $ContributorRoleId } if ($AutomationAccountName) { $step2Params.automationAccountName = $AutomationAccountName } # Check if role is already assigned (avoids RoleAssignmentExists error from manual portal assignments) $assignContributorRole = $true if ($AutomationAccountName) { $aaScope = "/subscriptions/$($script:RJAzureContextCache.SubscriptionId)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName" if (Test-RJRoleAssignmentExist -Scope $aaScope -PrincipalId $rjServicePrincipalId -RoleDefinitionId $ContributorRoleId) { $assignContributorRole = $false Write-Information " Contributor role already assigned — skipping role assignment." } } $step2Params.assignContributorRole = $assignContributorRole $step2Outputs = New-RJArmDeployment -ResourceGroupName $ResourceGroupName ` -TemplatePath $aaTemplatePath ` -DeploymentName "rj-automationaccount-$(Get-Date -Format 'yyyyMMddHHmmss')" ` -Parameters $step2Params $automationAccountId = $step2Outputs["automationAccountId"].Value $automationAccountPrincipalId = $step2Outputs["automationAccountPrincipalId"].Value Write-Verbose "Automation Account ID: $automationAccountId" Write-Verbose "Managed Identity Principal ID: $automationAccountPrincipalId" # Wait for Managed Identity replication $null = Wait-RJServicePrincipalReplication -ServicePrincipalId $automationAccountPrincipalId # Step 3: Configure Permissions Write-Information "Step 3/4: Configuring permissions..." $permissionsAssigned = @() if (@($permissionsManifest).Count -eq 0) { Write-Information " No API permissions to assign — skipping." } else { $permTemplatePath = Get-ArmTemplatePath -RelativePath "azure-automation-account/rjAutomationAccountPermissions.json" $step3Outputs = New-RJArmDeployment -ResourceGroupName $ResourceGroupName ` -TemplatePath $permTemplatePath ` -DeploymentName "rj-permissions-$(Get-Date -Format 'yyyyMMddHHmmss')" ` -Parameters @{ principalId = $automationAccountPrincipalId permissionsManifest = (ConvertTo-Json -InputObject @($permissionsManifest) -Depth 5 -Compress) } $permissionsAssigned = @($step3Outputs["permissionsAssigned"].Value) } # Step 4: Configure Entra ID directory roles Write-Information "Step 4/4: Configuring Entra ID directory roles..." $step4Result = @{ Assigned = @() AlreadyAssigned = @() } if (@($directoryRoles).Count -eq 0) { Write-Information " No directory roles to assign — skipping." } else { $step4Result = Set-RJAutomationAccountDirectoryRole -PrincipalId $automationAccountPrincipalId -RoleNames $directoryRoles -Confirm:$false } $result.Success = $true $result.Outputs = @{ AutomationAccountId = $automationAccountId AutomationAccountName = $step2Outputs["automationAccountName"].Value AutomationAccountPrincipalId = $automationAccountPrincipalId ServicePrincipalId = $rjServicePrincipalId PermissionsAssigned = $permissionsAssigned DirectoryRolesAssigned = @($step4Result.Assigned) DirectoryRolesExisting = @($step4Result.AlreadyAssigned) } return $result } function Set-RJLogAnalyticsResource { <# .SYNOPSIS Orchestrates the full Log Analytics Workspace deployment (2 steps). .DESCRIPTION Step 1: Configure RealmJoin Service Principal (deployed only if it does not exist yet) Step 2: Configure Log Analytics Workspace with conditional DCRs and custom tables .PARAMETER ResourceGroupName The target resource group (must exist). .PARAMETER WorkspaceName Optional name for the workspace. Auto-generated if not provided. .PARAMETER DeployAuditLogsDCR Whether to deploy the audit logs DCR. Default: true. .PARAMETER DeployRunbookLogsDCR Whether to deploy the runbook logs DCR. Default: true. .PARAMETER DeployOperationalLogsDCR Whether to deploy the operational logs DCR. Default: true. .OUTPUTS Hashtable with Success, Outputs (workspace info, DCR info). #> [CmdletBinding(SupportsShouldProcess)] [OutputType([hashtable])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [string]$WorkspaceName, [bool]$DeployAuditLogsDCR = $DefaultDeployAuditLogsDCR, [bool]$DeployRunbookLogsDCR = $DefaultDeployRunbookLogsDCR, [bool]$DeployOperationalLogsDCR = $DefaultDeployOperationalLogsDCR ) $result = @{ Success = $false Outputs = @{} } if (-not $PSCmdlet.ShouldProcess("Resource group '$ResourceGroupName'", "Deploy Log Analytics Workspace and DCRs")) { return $result } # Step 1: Configure RealmJoin Service Principal Write-Information "Step 1/2: Configuring RealmJoin Service Principal..." $rjServicePrincipalId = Initialize-RJAzureResourcesServicePrincipal -ResourceGroupName $ResourceGroupName # Step 2: Configure Log Analytics Workspace Write-Information "Step 2/2: Configuring Log Analytics Workspace..." $lawTemplatePath = Get-ArmTemplatePath -RelativePath "log-analytics-workspace/logAnalyticsWorkspace.json" $step2Params = @{ servicePrincipalId = $rjServicePrincipalId deployAuditLogsDCR = $DeployAuditLogsDCR deployRunbookLogsDCR = $DeployRunbookLogsDCR deployOperationalLogsDCR = $DeployOperationalLogsDCR logAnalyticsReaderRoleId = $LogAnalyticsReaderRoleId monitoringMetricsPublisherRoleId = $MonitoringMetricsPublisherRoleId } if ($WorkspaceName) { $step2Params.workspaceName = $WorkspaceName $workspaceLocation = Get-RJLogAnalyticsWorkspaceLocation -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName if ($workspaceLocation) { Write-Information " Using existing workspace location '$workspaceLocation'." $step2Params.location = $workspaceLocation } } # Check if roles are already assigned (avoids RoleAssignmentExists error from manual portal assignments) $subscriptionId = $script:RJAzureContextCache.SubscriptionId $assignWorkspaceRole = $true if ($WorkspaceName) { $lawScope = "/subscriptions/$subscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName" if (Test-RJRoleAssignmentExist -Scope $lawScope -PrincipalId $rjServicePrincipalId -RoleDefinitionId $LogAnalyticsReaderRoleId) { $assignWorkspaceRole = $false Write-Information " Log Analytics Reader role already assigned — skipping." } } $step2Params.assignWorkspaceRole = $assignWorkspaceRole # Check each DCR role — only for DCRs we're actually deploying $assignAuditLogsDcrRole = $true $assignRunbookLogsDcrRole = $true $assignOperationalLogsDcrRole = $true if ($DeployAuditLogsDCR -or $DeployRunbookLogsDCR -or $DeployOperationalLogsDCR) { $existingDcrs = Get-AzResource -ResourceGroupName $ResourceGroupName -ResourceType 'Microsoft.Insights/dataCollectionRules' -ErrorAction SilentlyContinue foreach ($dcr in $existingDcrs) { if ($dcr.Name -like 'dcr-rj-aud-logs-*' -and $DeployAuditLogsDCR) { if (Test-RJRoleAssignmentExist -Scope $dcr.ResourceId -PrincipalId $rjServicePrincipalId -RoleDefinitionId $MonitoringMetricsPublisherRoleId) { $assignAuditLogsDcrRole = $false Write-Information " Audit logs DCR role already assigned — skipping." } } elseif ($dcr.Name -like 'dcr-rj-rb-logs-*' -and $DeployRunbookLogsDCR) { if (Test-RJRoleAssignmentExist -Scope $dcr.ResourceId -PrincipalId $rjServicePrincipalId -RoleDefinitionId $MonitoringMetricsPublisherRoleId) { $assignRunbookLogsDcrRole = $false Write-Information " Runbook logs DCR role already assigned — skipping." } } elseif ($dcr.Name -like 'dcr-rj-op-logs-*' -and $DeployOperationalLogsDCR) { if (Test-RJRoleAssignmentExist -Scope $dcr.ResourceId -PrincipalId $rjServicePrincipalId -RoleDefinitionId $MonitoringMetricsPublisherRoleId) { $assignOperationalLogsDcrRole = $false Write-Information " Operational logs DCR role already assigned — skipping." } } } } $step2Params.assignAuditLogsDcrRole = $assignAuditLogsDcrRole $step2Params.assignRunbookLogsDcrRole = $assignRunbookLogsDcrRole $step2Params.assignOperationalLogsDcrRole = $assignOperationalLogsDcrRole $step2Outputs = New-RJArmDeployment -ResourceGroupName $ResourceGroupName ` -TemplatePath $lawTemplatePath ` -DeploymentName "rj-laworkspace-$(Get-Date -Format 'yyyyMMddHHmmss')" ` -Parameters $step2Params $result.Success = $true $result.Outputs = @{ ServicePrincipalId = $rjServicePrincipalId WorkspaceName = $step2Outputs["workspaceName"].Value WorkspaceId = $step2Outputs["workspaceId"].Value CustomerId = $step2Outputs["customerId"].Value # Audit Logs DCR AuditLogsTableName = $step2Outputs["auditLogsTableName"].Value AuditLogsStreamName = $step2Outputs["auditLogsStreamName"].Value AuditLogsIngestionEndpoint = $step2Outputs["auditLogsIngestionEndpoint"].Value AuditLogsDcrImmutableId = $step2Outputs["auditLogsDcrImmutableId"].Value AuditLogsDcrId = $step2Outputs["auditLogsDcrId"].Value AuditLogsDcrName = $step2Outputs["auditLogsDcrName"].Value # Runbook Logs DCR RunbookLogsTableName = $step2Outputs["runbookLogsTableName"].Value RunbookLogsStreamName = $step2Outputs["runbookLogsStreamName"].Value RunbookLogsIngestionEndpoint = $step2Outputs["runbookLogsIngestionEndpoint"].Value RunbookLogsDcrImmutableId = $step2Outputs["runbookLogsDcrImmutableId"].Value RunbookLogsDcrId = $step2Outputs["runbookLogsDcrId"].Value RunbookLogsDcrName = $step2Outputs["runbookLogsDcrName"].Value # Operational Logs DCR OperationalLogsTableName = $step2Outputs["operationalLogsTableName"].Value OperationalLogsStreamName = $step2Outputs["operationalLogsStreamName"].Value OperationalLogsIngestionEndpoint = $step2Outputs["operationalLogsIngestionEndpoint"].Value OperationalLogsDcrImmutableId = $step2Outputs["operationalLogsDcrImmutableId"].Value OperationalLogsDcrId = $step2Outputs["operationalLogsDcrId"].Value OperationalLogsDcrName = $step2Outputs["operationalLogsDcrName"].Value } return $result } function Set-RJWorkplaceCloudStorageResource { <# .SYNOPSIS Orchestrates the Workplace Cloud Storage deployment (2 steps). .DESCRIPTION Step 1: Configure RealmJoin Service Principal (deployed only if it does not exist yet) Step 2: Configure the storage account and the Storage Blob Data Contributor role of the service principal. An existing storage account is not redeployed; only the role is assigned. .PARAMETER ResourceGroupName The target resource group (must exist). .PARAMETER StorageAccountName Optional name for the storage account. Defaults to Get-RJWorkplaceCloudStorageDefaultName. .PARAMETER SkuName The SKU of a newly created storage account. .OUTPUTS Hashtable with Success, Outputs (ServicePrincipalId, StorageAccountId, StorageAccountName, BlobEndpoint). #> [CmdletBinding(SupportsShouldProcess)] [OutputType([hashtable])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [string]$StorageAccountName, [string]$SkuName = $DefaultWorkplaceCloudStorageSkuName ) $result = @{ Success = $false Outputs = @{} } if (-not $PSCmdlet.ShouldProcess("Resource group '$ResourceGroupName'", "Deploy Workplace Cloud Storage account and role assignment")) { return $result } if (-not $StorageAccountName) { $StorageAccountName = Get-RJWorkplaceCloudStorageDefaultName -ResourceGroupName $ResourceGroupName } $existingAccount = Get-RJWorkplaceCloudStorageAccount -ResourceGroupName $ResourceGroupName -StorageAccountName $StorageAccountName if ($existingAccount -and $existingAccount.Properties.allowBlobPublicAccess -eq $false) { throw "Storage account '$StorageAccountName' does not allow anonymous blob access, which Workplace Cloud Storage requires. Enable 'Allow Blob anonymous access' in the storage account configuration (an Azure Policy denying it needs an exemption) and run the command again." } # Step 1: Configure RealmJoin Service Principal Write-Information "Step 1/2: Configuring RealmJoin Service Principal..." $rjServicePrincipalId = Initialize-RJAzureResourcesServicePrincipal -ResourceGroupName $ResourceGroupName # Step 2: Configure Storage Account Write-Information "Step 2/2: Configuring Workplace Cloud Storage account..." $storageTemplatePath = Get-ArmTemplatePath -RelativePath "workplace-cloud-storage/storageAccount.json" $step2Params = @{ storageAccountName = $StorageAccountName servicePrincipalId = $rjServicePrincipalId storageBlobDataContributorRoleId = $StorageBlobDataContributorRoleId skuName = $SkuName deployStorageAccount = ($null -eq $existingAccount) assignBlobDataContributorRole = $true } if ($existingAccount) { Write-Information " Storage account '$StorageAccountName' already exists — assigning the role only." if (Test-RJRoleAssignmentExist -Scope $existingAccount.ResourceId -PrincipalId $rjServicePrincipalId -RoleDefinitionId $StorageBlobDataContributorRoleId) { $step2Params.assignBlobDataContributorRole = $false Write-Information " Storage Blob Data Contributor role already assigned — skipping." } } $step2Outputs = New-RJArmDeployment -ResourceGroupName $ResourceGroupName ` -TemplatePath $storageTemplatePath ` -DeploymentName "rj-workplacecloudstorage-$(Get-Date -Format 'yyyyMMddHHmmss')" ` -Parameters $step2Params $result.Success = $true $result.Outputs = @{ ServicePrincipalId = $rjServicePrincipalId StorageAccountId = $step2Outputs["storageAccountId"].Value StorageAccountName = $step2Outputs["storageAccountName"].Value BlobEndpoint = $step2Outputs["blobEndpoint"].Value } return $result } function Set-RJKeyVaultResource { <# .SYNOPSIS Orchestrates the Key Vault deployment for RealmJoin LAPS (2 steps). .DESCRIPTION Step 1: Check the RealmJoin Client service principal (never created here; the Client feature must be configured) Step 2: Configure the Key Vault (Azure RBAC) and the Key Vault roles of the Client service principal. An existing Key Vault is not redeployed; only the missing roles are assigned. .PARAMETER ResourceGroupName The target resource group (must exist). .PARAMETER KeyVaultName Optional name for the Key Vault. Defaults to Get-RJKeyVaultDefaultName. .OUTPUTS Hashtable with Success, Outputs (ServicePrincipalId, KeyVaultId, KeyVaultName, VaultUri). #> [CmdletBinding(SupportsShouldProcess)] [OutputType([hashtable])] param( [Parameter(Mandatory)] [string]$ResourceGroupName, [string]$KeyVaultName ) $result = @{ Success = $false Outputs = @{} } if (-not $PSCmdlet.ShouldProcess("Resource group '$ResourceGroupName'", "Deploy Key Vault and role assignments")) { return $result } # Step 1: Check RealmJoin Client Service Principal Write-Information "Step 1/2: Checking RealmJoin Client Service Principal..." $clientAppId = Get-RJClientAppId $clientServicePrincipal = Get-ServicePrincipalByAppId -AppId $clientAppId if (-not $clientServicePrincipal) { throw "The RealmJoin Client service principal (AppId '$clientAppId') does not exist in this tenant. Key Vault access for RealmJoin LAPS is granted to this service principal. Add the 'Client' feature with Update-RJTenant -AddFeatures Client first, then run the command again." } Write-Information " Service principal '$($clientServicePrincipal.DisplayName)' found." if (-not $KeyVaultName) { $KeyVaultName = Get-RJKeyVaultDefaultName -ResourceGroupName $ResourceGroupName } $existingVault = Get-RJKeyVault -ResourceGroupName $ResourceGroupName -KeyVaultName $KeyVaultName if ($existingVault -and $existingVault.Properties.enableRbacAuthorization -ne $true) { throw "Key Vault '$KeyVaultName' uses the vault access policy permission model. RealmJoin LAPS requires Azure role-based access control. Switch the permission model to 'Azure role-based access control' in the Key Vault's access configuration (existing access policies stop applying) or use another Key Vault, and run the command again." } # Step 2: Configure Key Vault Write-Information "Step 2/2: Configuring Key Vault..." $roleDefinitionIds = @() if ($existingVault) { Write-Information " Key Vault '$KeyVaultName' already exists — assigning the roles only." } foreach ($roleName in $KeyVaultClientRoles.Keys) { $roleDefinitionId = $KeyVaultClientRoles[$roleName] if ($existingVault -and (Test-RJRoleAssignmentExist -Scope $existingVault.ResourceId -PrincipalId $clientServicePrincipal.Id -RoleDefinitionId $roleDefinitionId)) { Write-Information " $roleName role already assigned — skipping." continue } $roleDefinitionIds += $roleDefinitionId } $keyVaultTemplatePath = Get-ArmTemplatePath -RelativePath "key-vault/keyVault.json" $step2Params = @{ keyVaultName = $KeyVaultName servicePrincipalId = $clientServicePrincipal.Id deployKeyVault = ($null -eq $existingVault) roleDefinitionIds = $roleDefinitionIds } $step2Outputs = New-RJArmDeployment -ResourceGroupName $ResourceGroupName ` -TemplatePath $keyVaultTemplatePath ` -DeploymentName "rj-keyvault-$(Get-Date -Format 'yyyyMMddHHmmss')" ` -Parameters $step2Params $result.Success = $true $result.Outputs = @{ ServicePrincipalId = $clientServicePrincipal.Id KeyVaultId = $step2Outputs["keyVaultId"].Value KeyVaultName = $step2Outputs["keyVaultName"].Value VaultUri = $step2Outputs["vaultUri"].Value } return $result } |