azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

Get-AzAksCluster -Id appears to ignore subscription in resource ID and uses current context subscription

Open andreasschild opened this issue 4 months ago • 9 comments

Description

Description

A platform team operating AKS clusters across many Azure subscriptions has observed unexpected behavior when using Get-AzAksCluster with a full Azure resource ID.

The expectation is that the cmdlet resolves the cluster based on the subscription embedded in the supplied resource ID. Instead, the cmdlet appears to use the subscription from the current Azure context and ignores the subscription contained in the resource ID when that subscription is not currently loaded as a context.

This behavior is particularly concerning in large-scale automation scenarios where identities may have access to many subscriptions and automation relies on Azure resource IDs being globally unique and self-contained.

Issue script & Debug output

$DebugPreference='Continue'
Set-AzContext -Subscription "714c36e4-xxxx-xxxx-xxxx"

# Works: Gets the cluster from the specified subscription
Get-AzAksCluster `
    -SubscriptionId "65be18f4-xxxx-xxxx-xxxx" `
    -ResourceGroupName "testing" `
    -Name "aks-testing"

# Doesn't work: Returns a not found or if a cluster with the same name 
# and the same resource group name it even returns a wrong cluster from the sub of the current context
Get-AzAksCluster `
    -Id "/subscriptions/65be18f4-xxxx-xxxx-xxxx/resourceGroups/testing/providers/Microsoft.ContainerService/managedClusters/aks-testing"


[...]
        === Token Acquisition finished successfully:
[...]
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/subscriptions/714c36e4-xxxx-xxxx-xxxx/resourceGroups/testing/providers/Microsoft.ContainerService/managedClusters/aks-testing?api-version=2026-03-01

Headers:
Accept-Language               : en-US
x-ms-client-request-id        : 6bbec8ed-f87f-487f-81c7-ec6e8a58f447

Body:

DEBUG: [AcquirePolicyTokenHandler] Intercept GET https://management.azure.com/subscriptions/714c36e4-xxxx-xxxx-xxxx/resourceGroups/testing/providers/Microsoft.ContainerService/managedClusters/aks-testing?api-version=2026-03-01
DEBUG: [AcquirePolicyTokenHandler] Skip: verb not allowed for token acquisition.
DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
NotFound

Headers:
Cache-Control                 : no-cache
Pragma                        : no-cache
x-ms-failure-cause            : gateway
x-ms-request-id               : 770535e1-aa36-4883-a4b5-d2965412fd62
x-ms-correlation-request-id   : 770535e1-aa36-4883-a4b5-d2965412fd62
x-ms-routing-request-id       : GERMANYWESTCENTRAL:20260730T083517Z:770535e1-aa36-4883-a4b5-d2965412fd62
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
X-Cache                       : CONFIG_NOCACHE
X-MSEdge-Ref                  : Ref A: 8C68EFB50170412F8D73B22B9C6DE0CB Ref B: FRA231050411025 Ref C: 2026-07-30T08:35:16Z
Date                          : Thu, 30 Jul 2026 08:35:16 GMT

Body:
{
  "error": {
    "code": "ResourceNotFound",
    "message": "The Resource 'Microsoft.ContainerService/managedClusters/aks-testing' under resource group 'testing' was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix"
  }
}

[...]

Environment data

Name                           Value
----                           -----
PSVersion                      7.6.4
PSEdition                      Core
GitCommitId                    7.6.4
OS                             Microsoft Windows 10.0.26200
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.4
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     5.5.1                 Az.Accounts                         {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault…}
Script     7.2.1                 Az.Aks                              {Disable-AzAksAddOn, Enable-AzAksAddOn, Get-AzAksCluster, Get-AzAksNodePool…}

Error output

HistoryId: 8

RequestId      :
Message        : Operation returned an invalid status code 'NotFound'
ServerMessage  :
ServerResponse : {NotFound}
RequestMessage : {GET https://management.azure.com/subscriptions/714c36e4--xxxx-xxxx-xxxx/resourceGroups/testing/providers/Microsoft.ContainerService/manag
                 edClusters/aks-testing?api-version=2026-03-01}
InvocationInfo : {Get-AzAksCluster}
Line           : Get-AzAksCluster -Id
                 "/subscriptions/65be18f4--xxxx-xxxx-xxxx/resourcegroups/testing/providers/Microsoft.ContainerService/managedClusters/aks-testing"
Position       : At line:1 char:1
                 + Get-AzAksCluster -Id "/subscriptions/65be18f4--xxxx-xxxx-xxxx …
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StackTrace     :    at Microsoft.Azure.Commands.Aks.KubeCmdletBase.RunCmdLet(Action action)
                    at Microsoft.Azure.Commands.Aks.GetAzureRmAks.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
HistoryId      : 8

andreasschild avatar Jul 30 '26 08:07 andreasschild

X Engineering Agent Bug analysis: Root cause analysis

Get-AzAksCluster accepts a full resource -Id parameter but the underlying client call appears to build the request using the current Azure context's subscription instead of the subscription segment embedded in the supplied resource ID. This means:

  • When the resource ID's subscription differs from the current context's subscription, the cmdlet returns ResourceNotFound (404) — the HTTP request in the repro is built against the context subscription (714c36e4-...) rather than the ID's subscription (65be18f4-...).
  • Worse, if a cluster with the same name/resource group happens to exist in the context subscription, the cmdlet silently returns the wrong cluster.

This breaks the guarantee that a fully-qualified Azure resource ID is self-contained and globally addressable — critical for automation across many subscriptions.

Expected fix: When -Id is supplied, parse the subscription ID out of the resource ID and use it for the underlying REST call (overriding/ignoring the current context's subscription for this call), consistent with how other cmdlets handle -Id parameter sets.

Investigation pointers:

  • Look at the Get-AzAksCluster cmdlet implementation in src/Aks (likely GetAzureRmManagedClusterCommand or similar) and how the -Id parameter set resolves SubscriptionId for the generated client.
  • Compare against other Get-Az* cmdlets in the same module (or track SDK-generated client) that correctly parse -Id to extract SubscriptionId, ResourceGroupName, and resource name.
  • Add/adjust a ChangeLog.md entry under src/Aks/Aks.

Use this EXACT PR title: [Aks] resolve subscription from the resource ID instead of the current context

PR title & description (azure-powershell)

Follow CONTRIBUTING.md. azure-powershell does not enforce a strict title gate — it requires a clear, informative title and a fully filled-out PR template.

Suggested PR title (clear & informative; [Module] prefix is the common convention):

[Aks] resolve subscription from the resource ID instead of the current context

Required (per CONTRIBUTING.md):

  • Fill out the PR template completely — PRs are not reviewed without the completed checklist; do not delete it.
  • Link the issue — include Fixes #29928 in the description so the PR auto-closes it.
  • ChangeLog — add a bullet describing the fix under the ## Upcoming Release header of src/Aks/Aks/ChangeLog.md. Do not add a new version header.
  • Target branch — main.
  • Tests — add/adjust test coverage for the change. Tests must not contain hardcoded values (location, resource id, etc.) and must be re-recordable; do not skip existing tests.
  • Scope — keep the change limited to the affected module (src/Aks/).

X Engineering Agent · Fixer · react 👍 / 👎 to train the agent

x-engineering-agent avatar Jul 30 '26 08:07 x-engineering-agent

:bell: Routing this issue to @Azure/act-identity-squad.

:bell: Routing this issue to @Azure/act-observability-squad.

Thanks for reporting. It seems the aks command didn't handle resource id properly. Curious to know if that's a single defect or a pattern across modules.

isra-fel avatar Aug 12 '26 02:08 isra-fel

I checked the latest main to determine whether this is isolated to AKS or reflects a broader pattern.

There is no repository-wide guarantee that a subscription embedded in a resource ID is honored. The behavior depends on the cmdlet implementation:

  • Legacy/hand-written SDK cmdlets commonly ignore it. They parse only the resource group and resource name from -Id/-ResourceId, then invoke an SDK client built from the current/default context. In that pattern, ARM receives the current context subscription unless the user separately supplies a supported subscription override.
  • AutoRest ViaIdentity cmdlets generally honor it. When a full ID is supplied through -InputObject, generated code parses the subscription from the ID and constructs the ARM request path with that subscription.
  • Cmdlets that pass the complete ID/scope directly to ARM also honor it. Examples include generic resource and authorization operations.
  • A smaller number of hand-written cmdlets explicitly parse the subscription and use it to build the target URI/client; Network private-link operations are an example.

For Get-AzAksCluster -Id, the reported behavior is confirmed: GetAzureRmAks.cs extracts only ResourceGroupName and ResourceName, while KubeCmdletBase builds the Container Service client from DefaultProfile.DefaultContext. The SDK then inserts that client's subscription into the request URI. Consequently, an ID from another subscription can produce a 404 or, more seriously, return an identically named cluster from the current subscription.

A rough static census found approximately 500 hand-written cmdlet implementations across 23-26 module areas that appear to parse a target -Id/-ResourceId without consuming its subscription segment. Among legacy SDK cmdlets that directly parse resource IDs, this is overwhelmingly the common pattern (well over 90% in the static sample). Across the entire Azure PowerShell command surface it is likely a single-digit percentage, because most commands do not accept resource IDs and newer AutoRest-generated identity cmdlets generally behave correctly.

Frequently represented module areas include Network, NetAppFiles, Synapse, SQL, DataShare, KeyVault, Storage, Cognitive Services, Cosmos DB, and AKS. The count is intentionally approximate because static analysis cannot always distinguish a target resource ID from an ID that merely references a related resource.

In short: this is a broad legacy implementation pattern rather than an AKS-only defect, although each affected command still needs to be assessed individually before changing precedence semantics.

isra-fel avatar Aug 12 '26 03:08 isra-fel

Given the different behavior for handling the -Id parameter, the consistent way is to always use "Set-AzContext" before operating on any resource that's not in the current subscription (i.e. the subscription of the current context).

isra-fel avatar Aug 12 '26 04:08 isra-fel

Hi @isra-fel. thanks for the analysis. very helpful. is there a plan to have a common experience when using these commands with the -Id parameter? This might be a risky behaviour for projects, which do not have the knowledge of it. Unfortunately, using Set-AzContext as a platform team with hundreds of subscriptions will decrease the development velocity quite a bit. Trying to avoid it whenever possible and using the pre-loaded contexts when using Connect-AzAccount, which is configurable via the -MaxContextPopulation parameter.

andreasschild avatar Aug 13 '26 09:08 andreasschild

As another workaround, you can use Invoke-AzRestMethod with the full ARM URI. Unlike affected resource-specific cmdlets, it sends the path from -Uri directly, so the subscription embedded in the URI is honored:

$resourceId = "/subscriptions/65be18f4-xxxx-xxxx-xxxx/resourceGroups/testing/providers/Microsoft.ContainerService/managedClusters/aks-testing"
Invoke-AzRestMethod -Method GET -Uri "https://management.azure.com${resourceId}?api-version=2026-03-01"

This avoids switching context when the current identity has access to both subscriptions and they are in the same tenant. If the target subscription is in a different tenant, you still need to use Set-AzContext for that subscription/tenant before calling Invoke-AzRestMethod.

isra-fel avatar Sep 03 '26 03:09 isra-fel

is there a plan to have a common experience when using these commands with the -Id parameter

Unfortunately there isn't plan for such a massive change (talking about 20+ modules and 500+ cmdlets).

isra-fel avatar Sep 03 '26 03:09 isra-fel