Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.26k stars 3.86k forks source link

Get-AzAks: Strange Output type System.Linq.Enumerable #9847

Closed TheKingIGER closed 5 years ago

TheKingIGER commented 5 years ago

Description

I found some strange behavior of the Get-AzAks Cmdlet. Everthing is descripted in the Steps to reproduce section

Steps to reproduce

Script/Commands:
$aks = get-azaks

$aks.Count

$aks[0]

$aks.GetType().Fullname
Output:
1
1

ProvisioningState       : Succeeded
DnsPrefix               : aks1
Fqdn                    : aks1.hcp.westeurope.azmk8s.io
KubernetesVersion       : 1.12.6
AgentPoolProfiles       : {agentpool}
LinuxProfile            : 
ServicePrincipalProfile : Microsoft.Azure.Commands.Aks.Models.PSContainerServiceServicePrincipalProfile
Id                      : /subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/a
                          /providers/Microsoft.ContainerService/managedClusters/aks1
Name                    : aks1
Type                    : Microsoft.ContainerService/ManagedClusters
Location                : westeurope
Tags                    : {}

ProvisioningState       : Succeeded
DnsPrefix               : aks2
Fqdn                    : aks2.hcp.westeurope.azmk8s.io
KubernetesVersion       : 1.12.7
AgentPoolProfiles       : {agentpool}
LinuxProfile            : 
ServicePrincipalProfile : Microsoft.Azure.Commands.Aks.Models.PSContainerServiceServicePrincipalProfile
Id                      : /subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/aks2-rg/providers/Microsoft.ContainerService/managedClusters/aks2
Name                    : aks2
Type                    : Microsoft.ContainerService/ManagedClusters
Location                : westeurope
Tags                    : {}

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[[Microsoft.Azure.Commands.Aks.Generated.Version2017_08_
31.Models.ManagedCluster, Microsoft.Azure.PowerShell.Clients.Aks, Version=1.0.0.0, Culture=neutral, PublicKeyT
oken=31bf3856ad364e35],[Microsoft.Azure.Commands.Aks.Models.PSKubernetesCluster, Microsoft.Azure.PowerShell.Cm
dlets.Aks, Version=1.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]

Using the .Count property of the $aks variable the output will be 1 1 instead of 2

When using an index ($aks[0]), the output will be all objects from the Array.

The return type of the Commands is a little bit strange. It's not a System.Object[] like other cmdlets (e.g. Get-AzVm).

Working Workarounds:

Workaround:
$aks = get-azaks

($aks.count).count

foreach($a in $aks){
    "Next Aks is $($a.name)"
    $a
}
Workaround Output:
2

Next Aks is aks1
ProvisioningState       : Succeeded
DnsPrefix               : aks1
Fqdn                    : aks1.hcp.westeurope.azmk8s.io
KubernetesVersion       : 1.12.6
AgentPoolProfiles       : {agentpool}
LinuxProfile            : 
ServicePrincipalProfile : Microsoft.Azure.Commands.Aks.Models.PSContainerServiceServicePrincipalProfile
Id                      : /subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/aks1-rg
                          /providers/Microsoft.ContainerService/managedClusters/aks1
Name                    : aks1
Type                    : Microsoft.ContainerService/ManagedClusters
Location                : westeurope
Tags                    : {}

Next Aks is aks2
ProvisioningState       : Succeeded
DnsPrefix               : aks2
Fqdn                    : aks2.hcp.westeurope.azmk8s.io
KubernetesVersion       : 1.12.7
AgentPoolProfiles       : {agentpool}
LinuxProfile            : 
ServicePrincipalProfile : Microsoft.Azure.Commands.Aks.Models.PSContainerServiceServicePrincipalProfile
Id                      : /subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxa/resourcegroups/aks2-rg/providers/Microsoft.ContainerService/managedClusters/aks2
Name                    : aks2
Type                    : Microsoft.ContainerService/ManagedClusters
Location                : westeurope
Tags                    : {}

$aks.count -> ($aks.count).Count or ($aks.name).Count

$aks[0] -> foreach

Environment data

Name                           Value                                                                                                                                                   
----                           ----             
PSVersion                      5.1.14393.3053                                                                                                                                    
PSEdition                      Desktop                                                                                                                                               
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                                   
BuildVersion                   10.0.14393.3053                                                                                                                                  
CLRVersion                     4.0.30319.42000                                                                                                                             
WSManStackVersion              3.0                                                                                                                                                     PSRemotingProtocolVersion      2.3                                                                                                                                                       
SerializationVersion           1.1.0.1 

Module versions

Get-Module  az.* -ListAvailable

ModuleType Version    Name                                ExportedCommands                                                                                                                               
---------- -------    ----                                ----------------                                                                                                                               
Script     1.6.0      Az.Accounts                         {Disable-AzDataCollection, Disable-AzContextAutosave, Enable-AzDataCollection, Enable-AzContextAutosave...}                                    
Script     1.0.0      Az.Advisor                          {Get-AzAdvisorRecommendation, Enable-AzAdvisorRecommendation, Disable-AzAdvisorRecommendation, Get-AzAdvisorConfiguration...}                  
Script     1.0.1      Az.Aks                              {Get-AzAks, New-AzAks, Remove-AzAks, Import-AzAksCredential...}                                                                                
Script     1.1.0      Az.AnalysisServices                 {Resume-AzAnalysisServicesServer, Suspend-AzAnalysisServicesServer, Get-AzAnalysisServicesServer, Remove-AzAnalysisServicesServer...}          
Script     1.2.0      Az.ApiManagement                    {Add-AzApiManagementApiToProduct, Add-AzApiManagementProductToGroup, Add-AzApiManagementRegion, Add-AzApiManagementUserToGroup...}             
Script     1.0.0      Az.ApplicationInsights              {Get-AzApplicationInsights, New-AzApplicationInsights, Remove-AzApplicationInsights, Set-AzApplicationInsightsPricingPlan...}                  
Script     1.3.0      Az.Automation                       {Get-AzAutomationHybridWorkerGroup, Remove-AzAutomationHybridWorkerGroup, Get-AzAutomationJobOutputRecord, Import-AzAutomationDscNodeConfigu...
Script     1.1.0      Az.Batch                            {Remove-AzBatchAccount, Get-AzBatchAccount, Get-AzBatchAccountKey, New-AzBatchAccount...}                                                      
Script     1.0.0      Az.Billing                          {Get-AzBillingInvoice, Get-AzBillingPeriod, Get-AzEnrollmentAccount, Get-AzConsumptionBudget...}                                               
Script     1.3.0      Az.Cdn                              {Get-AzCdnProfile, Get-AzCdnProfileSsoUrl, New-AzCdnProfile, Remove-AzCdnProfile...}                                                           
Script     1.1.1      Az.CognitiveServices                {Get-AzCognitiveServicesAccount, Get-AzCognitiveServicesAccountKey, Get-AzCognitiveServicesAccountSku, Get-AzCognitiveServicesAccountType...}  
Script     2.4.0      Az.Compute                          {Remove-AzAvailabilitySet, Get-AzAvailabilitySet, New-AzAvailabilitySet, Update-AzAvailabilitySet...}                                          
Script     1.0.1      Az.ContainerInstance                {New-AzContainerGroup, Get-AzContainerGroup, Remove-AzContainerGroup, Get-AzContainerInstanceLog}                                              
Script     1.0.1      Az.ContainerRegistry                {New-AzContainerRegistry, Get-AzContainerRegistry, Update-AzContainerRegistry, Remove-AzContainerRegistry...}                                  
Script     1.1.2      Az.DataFactory                      {Set-AzDataFactoryV2, Update-AzDataFactoryV2, Get-AzDataFactoryV2, Remove-AzDataFactoryV2...}                                                  
Script     1.0.0      Az.DataLakeAnalytics                {Get-AzDataLakeAnalyticsDataSource, New-AzDataLakeAnalyticsCatalogCredential, Remove-AzDataLakeAnalyticsCatalogCredential, Set-AzDataLakeAna...
Script     1.2.1      Az.DataLakeStore                    {Get-AzDataLakeStoreTrustedIdProvider, Remove-AzDataLakeStoreTrustedIdProvider, Remove-AzDataLakeStoreFirewallRule, Set-AzDataLakeStoreTrust...
Script     1.0.0      Az.DeploymentManager                {Get-AzDeploymentManagerArtifactSource, New-AzDeploymentManagerArtifactSource, Set-AzDeploymentManagerArtifactSource, Remove-AzDeploymentMan...
Script     1.0.0      Az.DevTestLabs                      {Get-AzDtlAllowedVMSizesPolicy, Get-AzDtlAutoShutdownPolicy, Get-AzDtlAutoStartPolicy, Get-AzDtlVMsPerLabPolicy...}                            
Script     1.1.1      Az.Dns                              {Get-AzDnsRecordSet, New-AzDnsRecordConfig, Remove-AzDnsRecordSet, Set-AzDnsRecordSet...}                                                      
Script     1.2.1      Az.EventGrid                        {New-AzEventGridTopic, Get-AzEventGridTopic, Set-AzEventGridTopic, New-AzEventGridTopicKey...}                                                 
Script     1.2.0      Az.EventHub                         {New-AzEventHubNamespace, Get-AzEventHubNamespace, Set-AzEventHubNamespace, Remove-AzEventHubNamespace...}                                     
Script     1.1.0      Az.FrontDoor                        {New-AzFrontDoor, Get-AzFrontDoor, Set-AzFrontDoor, Remove-AzFrontDoor...}                                                                     
Script     2.0.0      Az.HDInsight                        {Get-AzHDInsightJob, New-AzHDInsightSqoopJobDefinition, Wait-AzHDInsightJob, New-AzHDInsightStreamingMapReduceJobDefinition...}                
Script     1.2.0      Az.IotHub                           {Add-AzIotHubKey, Get-AzIotHubEventHubConsumerGroup, Get-AzIotHubConnectionString, Get-AzIotHubJob...}                                         
Script     1.2.0      Az.KeyVault                         {Add-AzKeyVaultCertificate, Update-AzKeyVaultCertificate, Stop-AzKeyVaultCertificateOperation, Get-AzKeyVaultCertificateOperation...}          
Script     1.2.1      Az.LogicApp                         {Get-AzIntegrationAccountAgreement, Get-AzIntegrationAccountAssembly, Get-AzIntegrationAccountBatchConfiguration, Get-AzIntegrationAccountCa...
Script     1.1.0      Az.MachineLearning                  {Move-AzMlCommitmentAssociation, Get-AzMlCommitmentAssociation, Get-AzMlCommitmentPlanUsageHistory, Remove-AzMlCommitmentPlan...}              
Script     1.0.0      Az.MarketplaceOrdering              {Get-AzMarketplaceTerms, Set-AzMarketplaceTerms}                                                                                               
Script     1.1.0      Az.Media                            {Sync-AzMediaServiceStorageKey, Set-AzMediaServiceKey, Get-AzMediaServiceKey, Get-AzMediaServiceNameAvailability...}                           
Script     1.2.1      Az.Monitor                          {Get-AzMetricDefinition, Get-AzMetric, Remove-AzLogProfile, Get-AzLogProfile...}                                                               
Script     1.11.0     Az.Network                          {Add-AzApplicationGatewayAuthenticationCertificate, Get-AzApplicationGatewayAuthenticationCertificate, New-AzApplicationGatewayAuthenticatio...
Script     1.1.0      Az.NotificationHubs                 {Get-AzNotificationHub, Get-AzNotificationHubAuthorizationRule, Get-AzNotificationHubListKey, Get-AzNotificationHubPNSCredential...}           
Script     1.3.1      Az.OperationalInsights              {New-AzOperationalInsightsAzureActivityLogDataSource, New-AzOperationalInsightsCustomLogDataSource, Disable-AzOperationalInsightsLinuxCustom...
Script     1.1.2      Az.PolicyInsights                   {Get-AzPolicyEvent, Get-AzPolicyState, Get-AzPolicyStateSummary, Get-AzPolicyRemediation...}                                                   
Script     1.1.0      Az.PowerBIEmbedded                  {Remove-AzPowerBIWorkspaceCollection, Get-AzPowerBIWorkspaceCollection, Get-AzPowerBIWorkspaceCollectionAccessKey, Get-AzPowerBIWorkspace...}  
Script     1.4.2      Az.RecoveryServices                 {Get-AzRecoveryServicesBackupProperty, Get-AzRecoveryServicesVault, Get-AzRecoveryServicesVaultSettingsFile, New-AzRecoveryServicesVault...}   
Script     1.1.0      Az.RedisCache                       {Remove-AzRedisCachePatchSchedule, New-AzRedisCacheScheduleEntry, Get-AzRedisCachePatchSchedule, New-AzRedisCachePatchSchedule...}             
Script     1.0.1      Az.Relay                            {New-AzRelayNamespace, Get-AzRelayNamespace, Set-AzRelayNamespace, Remove-AzRelayNamespace...}                                                 
Script     1.6.0      Az.Resources                        {Get-AzProviderOperation, Remove-AzRoleAssignment, Get-AzRoleAssignment, New-AzRoleAssignment...}                                              
Script     1.2.1      Az.ServiceBus                       {New-AzServiceBusNamespace, Get-AzServiceBusNamespace, Set-AzServiceBusNamespace, Remove-AzServiceBusNamespace...}                             
Script     1.1.1      Az.ServiceFabric                    {Add-AzServiceFabricApplicationCertificate, Add-AzServiceFabricClientCertificate, Add-AzServiceFabricClusterCertificate, Add-AzServiceFabric...
Script     1.0.2      Az.SignalR                          {New-AzSignalR, Get-AzSignalR, Get-AzSignalRKey, New-AzSignalRKey...}                                                                          
Script     1.13.0     Az.Sql                              {Get-AzSqlDatabaseTransparentDataEncryption, Get-AzSqlDatabaseTransparentDataEncryptionActivity, Set-AzSqlDatabaseTransparentDataEncryption,...
Script     1.5.0      Az.Storage                          {Get-AzStorageAccount, Get-AzStorageAccountKey, New-AzStorageAccount, New-AzStorageAccountKey...}                                              
Script     1.1.1      Az.StorageSync                      {Invoke-AzStorageSyncCompatibilityCheck, New-AzStorageSyncService, Get-AzStorageSyncService, Remove-AzStorageSyncService...}                   
Script     1.0.0      Az.StreamAnalytics                  {Get-AzStreamAnalyticsFunction, Get-AzStreamAnalyticsDefaultFunctionDefinition, New-AzStreamAnalyticsFunction, Remove-AzStreamAnalyticsFunct...
Script     1.0.1      Az.TrafficManager                   {Add-AzTrafficManagerCustomHeaderToEndpoint, Remove-AzTrafficManagerCustomHeaderFromEndpoint, Add-AzTrafficManagerCustomHeaderToProfile, Rem...
Script     1.3.0      Az.Websites                         {Get-AzAppServicePlan, Set-AzAppServicePlan, New-AzAppServicePlan, Remove-AzAppServicePlan...}  

Debug output

DEBUG: 10:24:02 AM - GetAzureRmAks begin processing with ParameterSet 'ResourceGroupParameterSet'.
DEBUG: 10:24:02 AM - using account id 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'...
DEBUG: [Common.Authentication]: Authenticating using Account: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', environment: 'AzureCloud', tenant: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', Endpoint: 'https://login.microsoftonline.com/', ClientId: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', ClientRedirect: 'xxx', ResourceClientUri: 'https://management.core.windows.net/', ValidateAuthority: 'True'
DEBUG: [Common.Authentication]: Renewing token using AppId: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', AdalConfiguration with ADDomain: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', AdEndpoint: 'https://login.mi
crosoftonline.com/', ClientId: 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', RedirectUri: 'xxx'

DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxa/providers/Microsoft.ContainerService/managedClusters?api-version=2017-08-31

Headers:
x-ms-client-request-id        : 6b37ef97-57ee-467a-9b5a-f221fca7ec56
accept-language               : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-subscription-reads: 11999
x-ms-correlation-request-id   : dd7140ac-f854-483d-b214-2942ecd9e479
x-ms-request-id               : 319f7c72-8dd5-4e6f-a411-31ce9f07424b
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
x-ms-routing-request-id       : WESTEUROPE:20190816T082402Z:dd7140ac-f854-483d-b214-2942ecd9e479
Cache-Control                 : no-cache
Date                          : Fri, 16 Aug 2019 08:24:01 GMT
Server                        : nginx

Body:
{
  "value": [
    {
      "id": "/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/aks1-rg/providers/Microsoft.ContainerService/managedClusters/aks",
      "location": "westeurope",
      "name": "aks1",
      "type": "Microsoft.ContainerService/ManagedClusters",
      "properties": {
        "provisioningState": "Succeeded",
        "kubernetesVersion": "1.12.6",
        "dnsPrefix": "aks1",
        "fqdn": "aks1.hcp.westeurope.azmk8s.io",
        "agentPoolProfiles": [
          {
            "name": "agentpool",
            "count": 1,
            "vmSize": "Standard_D16s_v3",
            "osDiskSizeGB": 30,
            "storageProfile": "ManagedDisks",
            "osType": "Linux"
          }
        ],
        "servicePrincipalProfile": {
          "clientId": "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        }
      }
    },
    {
      "id": "/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/aks2-rg/providers/Microsoft.ContainerService/managedClusters/aks2",
      "location": "westeurope",
      "name": "aks2",
      "type": "Microsoft.ContainerService/ManagedClusters",
      "properties": {
        "provisioningState": "Succeeded",
        "kubernetesVersion": "1.12.7",
        "dnsPrefix": "aks2",
        "fqdn": "aks2.hcp.westeurope.azmk8s.io",
        "agentPoolProfiles": [
          {
            "name": "agentpool",
            "count": 2,
            "vmSize": "Standard_D16s_v3",
            "osDiskSizeGB": 100,
            "storageProfile": "ManagedDisks",
            "osType": "Linux"
          }
        ],
        "servicePrincipalProfile": {
          "clientId": "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        }
      }
    }
  ]
}

DEBUG: AzureQoSEvent: CommandName - Get-AzAks; IsSuccess - True; Duration - 00:00:00.1416487; Exception - ;
DEBUG: Finish sending metric.
DEBUG: 10:24:03 AM - GetAzureRmAks end processing.
DEBUG: 10:24:03 AM - GetAzureRmAks end processing.

Error output

No Output
abeckDev commented 5 years ago

I have looked at the behavior and could reproduce the error.

In my opinion there is something wrong with the response type because the Type System.Linq.Enumerable+WhereSelectEnumerableIterator indicates a Linq query which is not transacted succesfully.

If we look at the Code in the GetAZureRmAks.cs we will find the following code at Line 92:

var kubeClusters = string.IsNullOrEmpty(ResourceGroupName)
                            ? Client.ManagedClusters.List()
                            : Client.ManagedClusters.ListByResourceGroup(ResourceGroupName);
                        WriteObject(kubeClusters.Select(PSMapper.Instance.Map<PSKubernetesCluster>));

I am a bit confused about the Select Statement in the Write-Object call. The PSMapper does not look like a valid Lambda expression in my opinion.

Wouldn't something like the following code also do the job or is there a specific reason for running a Select before mapping the IPage<ManagedCluster> to PSKubernetesCluster?

var kubeClusters = string.IsNullOrEmpty(ResourceGroupName)
                            ? Client.ManagedClusters.List()
                            : Client.ManagedClusters.ListByResourceGroup(ResourceGroupName);
                        WriteObject(PSMapper.Instance.Map<PSKubernetesCluster>(kubeClusters));
cormacpayne commented 5 years ago

@TheKingIGER thanks for filing this issue -- I have opened a PR with the fix here

shashankrudroju commented 4 years ago

Is the issue fixed? I am able to reproduce the issue.