Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Azure login does not work for user-managed identities when executed from the VM Instance #27813

Closed
sfc-gh-aivanou opened this issue Nov 10, 2023 · 3 comments
Assignees
Labels
Account az login/account Auto-Assign Auto assign by bot Azure CLI Team The command of the issue is owned by Azure CLI team customer-reported Issues that are reported by GitHub users external to the Azure organization. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that
Milestone

Comments

@sfc-gh-aivanou
Copy link

sfc-gh-aivanou commented Nov 10, 2023

Describe the bug

I want to login to azure via cli from the VM Instance that runs ubuntu.
For this I execute:

az login --identity -u /subscriptions/MY_SUB/resourcegroups/MY_RES_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/MY_ID

The VM instance has role assignment with the the role above.
I am getting the following error:

Failed to connect to MSI. Please make sure MSI is configured correctly.
Get Token request returned http error: 400, reason: Bad Request

Both VM instance and User managed identity are in the same Subscription and Resource Group
What am I doing wrong?

Related command

az login --identity -u /subscriptions/MY_SUB/resourcegroups/MY_RES_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/MY_ID

Errors

Failed to connect to MSI. Please make sure MSI is configured correctly.
Get Token request returned http error: 400, reason: Bad Request

Issue script & Debug output

cli.knack.cli: Command arguments: ['login', '--identity', '-u', '/subscriptions/MY_SUB/resourcegroups/MY_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/MY_ID', '--debug']
cli.knack.cli: __init__ debug log:
Enable color in terminal.
cli.knack.cli: Event: Cli.PreExecute []
cli.knack.cli: Event: CommandParser.OnGlobalArgumentsCreate [<function CLILogging.on_global_arguments at 0x7f84cb4013f0>, <function OutputProducer.on_global_arguments at 0x7f84cb358310>, <function CLIQuery.on_global_arguments at 0x7f84cb179510>]
cli.knack.cli: Event: CommandInvoker.OnPreCommandTableCreate []
cli.azure.cli.core: Modules found from index for 'login': ['azure.cli.command_modules.profile']
cli.azure.cli.core: Loading command modules:
cli.azure.cli.core: Name                  Load Time    Groups  Commands
cli.azure.cli.core: profile                   0.002         2         8
cli.azure.cli.core: Total (1)                 0.002         2         8
cli.azure.cli.core: Loaded 2 groups, 8 commands.
cli.azure.cli.core: Found a match in the command table.
cli.azure.cli.core: Raw command  : login
cli.azure.cli.core: Command table: login
cli.knack.cli: Event: CommandInvoker.OnPreCommandTableTruncate [<function AzCliLogging.init_command_file_logging at 0x7f84ca547010>]
cli.azure.cli.core.azlogging: metadata file logging enabled - writing logs to '/home/$USER/.azure/commands/2023-11-10.01-33-55.login.16322.log'.
az_command_data_logger: command args: login --identity -u {} --debug
cli.knack.cli: Event: CommandInvoker.OnPreArgumentLoad [<function register_global_subscription_argument.<locals>.add_subscription_parameter at 0x7f84ca567d00>]
cli.knack.cli: Event: CommandInvoker.OnPostArgumentLoad []
cli.knack.cli: Event: CommandInvoker.OnPostCommandTableCreate [<function register_ids_argument.<locals>.add_ids_arguments at 0x7f84ca5ada20>, <function register_cache_arguments.<locals>.add_cache_arguments at 0x7f84ca5adb40>]
cli.knack.cli: Event: CommandInvoker.OnCommandTableLoaded []
cli.knack.cli: Event: CommandInvoker.OnPreParseArgs []
cli.knack.cli: Event: CommandInvoker.OnPostParseArgs [<function OutputProducer.handle_output_argument at 0x7f84cb3583a0>, <function CLIQuery.handle_query_parameter at 0x7f84cb1795a0>, <function register_ids_argument.<locals>.parse_ids_arguments at 0x7f84ca5adab0>]
urllib3.connectionpool: Starting new HTTP connection (1): 169.254.169.254:80
urllib3.connectionpool: http://169.254.169.254:80 "GET /metadata/identity/oauth2/token?resource=https%3A%2F%2Fmanagement.core.windows.net%2F&api-version=2018-02-01&msi_res_id=%2Fsubscriptions%2FMY_SUB%2Fresourcegroups%2FMY_GROUP%2Fproviders%2FMicrosoft.ManagedIdentity%2FuserAssignedIdentities%2FMY_ID HTTP/1.1" 400 68
msrestazure.azure_active_directory: MSI: Retrieving a token from http://169.254.169.254/metadata/identity/oauth2/token, with payload {'resource': 'https://management.core.windows.net/', 'api-version': '2018-02-01', 'msi_res_id': '/subscriptions/MY_SUB/resourcegroups/MY_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/MY_ID'}
cli.azure.cli.core.auth.adal_authentication: throw requests.exceptions.HTTPError when doing MSIAuthentication:
Traceback (most recent call last):
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/auth/adal_authentication.py", line 75, in set_token
    super().set_token()
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 600, in set_token
    token_entry = self._vm_msi.get_token(self.resource)
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 649, in get_token
    token_entry = self._retrieve_token_from_imds_with_retry(resource)
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 704, in _retrieve_token_from_imds_with_retry
    raise HTTPError(request=result.request, response=result.raw)
requests.exceptions.HTTPError

cli.azure.cli.core.azclierror: Traceback (most recent call last):
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/auth/adal_authentication.py", line 75, in set_token
    super().set_token()
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 600, in set_token
    token_entry = self._vm_msi.get_token(self.resource)
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 649, in get_token
    token_entry = self._retrieve_token_from_imds_with_retry(resource)
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 704, in _retrieve_token_from_imds_with_retry
    raise HTTPError(request=result.request, response=result.raw)
requests.exceptions.HTTPError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/az/lib/python3.10/site-packages/knack/cli.py", line 233, in invoke
    cmd_result = self.invocation.execute(args)
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/commands/__init__.py", line 663, in execute
    raise ex
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/commands/__init__.py", line 726, in _run_jobs_serially
    results.append(self._run_job(expanded_arg, cmd_copy))
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/commands/__init__.py", line 697, in _run_job
    result = cmd_copy(params)
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/commands/__init__.py", line 333, in __call__
    return self.handler(*args, **kwargs)
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/commands/command_operation.py", line 121, in handler
    return op(**command_args)
  File "/opt/az/lib/python3.10/site-packages/azure/cli/command_modules/profile/custom.py", line 122, in login
    return profile.login_with_managed_identity(username, allow_no_subscriptions)
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/_profile.py", line 203, in login_with_managed_identity
    msi_creds = MSIAuthenticationWrapper(resource=resource, msi_res_id=identity_id)
  File "/opt/az/lib/python3.10/site-packages/msrestazure/azure_active_directory.py", line 592, in __init__
    self.set_token()
  File "/opt/az/lib/python3.10/site-packages/azure/cli/core/auth/adal_authentication.py", line 85, in set_token
    raise AzureResponseError('Failed to connect to MSI. Please make sure MSI is configured correctly.\n'
azure.cli.core.azclierror.AzureResponseError: Failed to connect to MSI. Please make sure MSI is configured correctly.
Get Token request returned http error: 400, reason: Bad Request

cli.azure.cli.core.azclierror: Failed to connect to MSI. Please make sure MSI is configured correctly.
Get Token request returned http error: 400, reason: Bad Request
az_command_data_logger: Failed to connect to MSI. Please make sure MSI is configured correctly.
Get Token request returned http error: 400, reason: Bad Request
cli.knack.cli: Event: Cli.PostExecute [<function AzCliLogging.deinit_cmd_metadata_logging at 0x7f84ca547250>]
az_command_data_logger: exit code: 1
cli.__main__: Command ran in 0.429 seconds (init: 0.210, invoke: 0.219)
telemetry.main: Begin splitting cli events and extra events, total events: 1
telemetry.client: Accumulated 0 events. Flush the clients.
telemetry.main: Finish splitting cli events and extra events, cli events: 1
telemetry.save: Save telemetry record of length 3595 in cache
telemetry.main: Begin creating telemetry upload process.
telemetry.process: Creating upload process: "/usr/bin/../../opt/az/bin/python3 /opt/az/lib/python3.10/site-packages/azure/cli/telemetry/__init__.py /home/$USER/.azure"
telemetry.process: Return from creating process
telemetry.main: Finish creating telemetry upload process.

Expected behavior

successful login

Environment Summary

azure-cli                         2.53.1

core                              2.53.1
telemetry                          1.1.0

Dependencies:
msal                            1.24.0b2
azure-mgmt-resource             23.1.0b2

Python location '/opt/az/bin/python3'
Extensions directory '/home/$USER/.azure/cliextensions'

Python (Linux) 3.10.10 (main, Oct 24 2023, 06:10:44) [GCC 9.4.0]

Legal docs and information: aka.ms/AzureCliLegal


Your CLI is up-to-date.

Additional context

No response

@sfc-gh-aivanou sfc-gh-aivanou added the bug This issue requires a change to an existing behavior in the product in order to be resolved. label Nov 10, 2023
@microsoft-github-policy-service microsoft-github-policy-service bot added customer-reported Issues that are reported by GitHub users external to the Azure organization. Auto-Assign Auto assign by bot Account az login/account labels Nov 10, 2023
@microsoft-github-policy-service microsoft-github-policy-service bot added Azure CLI Team The command of the issue is owned by Azure CLI team question The issue doesn't require a change to the product in order to be resolved. Most issues start as that labels Nov 10, 2023
@yonzhan
Copy link
Collaborator

yonzhan commented Nov 10, 2023

Thank you for opening this issue, we will look into it.

@sfc-gh-aivanou sfc-gh-aivanou changed the title Azure login does not work for user-managed identities f Azure login does not work for user-managed identities when executed from the VM Instance Nov 10, 2023
@yonzhan yonzhan added this to the Backlog milestone Nov 10, 2023
@yonzhan yonzhan removed the bug This issue requires a change to an existing behavior in the product in order to be resolved. label Nov 10, 2023
@sfc-gh-aivanou
Copy link
Author

The issue was that I was providing incorrect user-assigned managed identity id.
In documentation it is said that we need to provide ID, and I thought it is either Client ID or Object(Principal) ID.
But we actually need to provide name of the identity, not id

@jiasli
Copy link
Member

jiasli commented Nov 10, 2023

As documented at https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli-managed-identity, for user-assigned managed identity, Azure CLI supports 3 types of --username:

  1. Client ID
  2. Object(Principal) ID
  3. Resource ID

So I don't think name of the identity works. It should be resource ID. The source code shows the same:

if is_valid_resource_id(identity_id):

I thought it is either Client ID or Object(Principal) ID.

It seems you are providing a resource ID:

cli.knack.cli: Command arguments: ['login', '--identity', '-u', '/subscriptions/MY_SUB/resourcegroups/MY_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/MY_ID', '--debug']

that's why the provided call stack shows it fails right after L202:

msi_creds = MSIAuthenticationWrapper(resource=resource, msi_res_id=identity_id)

If you provide either Client ID or Object(Principal) ID, it should go to the else part:

else:
authenticated = False
from azure.cli.core.azclierror import AzureResponseError
try:
msi_creds = MSIAuthenticationWrapper(resource=resource, client_id=identity_id)
identity_type = MsiAccountTypes.user_assigned_client_id
authenticated = True
except AzureResponseError as ex:
if 'http error: 400, reason: Bad Request' in ex.error_msg:
logger.info('Sniff: not an MSI client id')
else:
raise
if not authenticated:
try:
identity_type = MsiAccountTypes.user_assigned_object_id
msi_creds = MSIAuthenticationWrapper(resource=resource, object_id=identity_id)
authenticated = True
except AzureResponseError as ex:
if 'http error: 400, reason: Bad Request' in ex.error_msg:
logger.info('Sniff: not an MSI object id')
else:
raise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Account az login/account Auto-Assign Auto assign by bot Azure CLI Team The command of the issue is owned by Azure CLI team customer-reported Issues that are reported by GitHub users external to the Azure organization. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that
Projects
None yet
Development

No branches or pull requests

3 participants