|
| 1 | +function Get-CIPPFunctionAppResourceGroup { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Resolve the resource group that the CIPP Function App site lives in. |
| 5 | + .DESCRIPTION |
| 6 | + Returns the resource group of the running Function App, using authoritative sources only: |
| 7 | +
|
| 8 | + 1. WEBSITE_RESOURCE_GROUP - platform-injected, the site's actual RG. Free, no decode. |
| 9 | + 2. xms_mirid claim from the managed identity token - the site's own ARM resource ID, |
| 10 | + present even when WEBSITE_RESOURCE_GROUP is empty, needs no extra call or permission. |
| 11 | +
|
| 12 | + The legacy approach of parsing WEBSITE_OWNER_NAME is intentionally NOT used: that string |
| 13 | + encodes the App Service Plan's webspace RG, which is frequently different from the site's RG |
| 14 | + (e.g. it returns 'DefaultResourceGroup-WEU' or '<rg>-m01' for sites whose plan was created |
| 15 | + in an auto-generated/other resource group). Writing auth settings, restarting, or querying |
| 16 | + the wrong RG is worse than failing, so this throws when no reliable source is available. |
| 17 | + .PARAMETER SiteName |
| 18 | + The Function App site name to resolve. Defaults to WEBSITE_SITE_NAME. |
| 19 | + .EXAMPLE |
| 20 | + Get-CIPPFunctionAppResourceGroup |
| 21 | + Returns e.g. 'CIPP-myinstance' |
| 22 | + #> |
| 23 | + [CmdletBinding()] |
| 24 | + param( |
| 25 | + [Parameter(Mandatory = $false)] |
| 26 | + [string]$SiteName = $env:WEBSITE_SITE_NAME |
| 27 | + ) |
| 28 | + |
| 29 | + # 1. Platform-injected site resource group - authoritative, zero cost. |
| 30 | + if ($env:WEBSITE_RESOURCE_GROUP) { |
| 31 | + return $env:WEBSITE_RESOURCE_GROUP |
| 32 | + } |
| 33 | + |
| 34 | + # 2. The managed identity's own token names this site's resource ID (incl. RG). Only trust it |
| 35 | + # when it actually points at this Microsoft.Web/sites resource, so a user-assigned identity |
| 36 | + # (whose xms_mirid is a userAssignedIdentities resource) falls through rather than returning |
| 37 | + # the identity's RG. |
| 38 | + try { |
| 39 | + $MiRid = Get-CIPPManagedIdentityResourceId |
| 40 | + if ($SiteName -and $MiRid -match "(?i)/resourcegroups/(?<RG>[^/]+)/providers/Microsoft\.Web/sites/$([regex]::Escape($SiteName))(/|$)") { |
| 41 | + return $Matches.RG |
| 42 | + } |
| 43 | + Write-Information "xms_mirid did not match site '$SiteName': $MiRid" |
| 44 | + } catch { |
| 45 | + Write-Warning "Could not read resource group from managed identity token: $($_.Exception.Message)" |
| 46 | + } |
| 47 | + |
| 48 | + # 3. No reliable source - fail loudly rather than guess from WEBSITE_OWNER_NAME. |
| 49 | + throw "Could not determine the function app resource group for site '$SiteName'. WEBSITE_RESOURCE_GROUP is empty and the managed identity resource ID was unavailable." |
| 50 | +} |
0 commit comments