Azure Python SDK - connecting to USGov with CLI Credentials fails?

591 views Asked by At

I've tried using AzureCliCredential() as noted in previous questions/the documentation - this works great in the normal azure cloud. If I'm using the USGov cloud (portal.azure.us), the same code just returns nothing; I've tried http tracing and it looks like it's still pointing at management.azure.com and not management.core.usgovcloudapi.net - but it doesn't say anything. Pretty much all things that require a subscription scope are telling me the subscription doesn't exist, and yet 'az account list' shows all of the subscriptions correctly. I've got all the python modules updated to the latest.. not sure what's wrong at this point, any ideas?

just to sum up, procedure is:

  1. login with az login --use-device-code
  2. go to microsoft.com/deviceloginus (usgov device login) and put in code
  3. shell is authenticated
  4. az account list shows all of my subscriptions
  5. Run test code to list subscriptions - get no results. Trace shows that things still point at management.azure.com - if I force base_url to https://management.usgovcloudapi.net, I get an InvalidAuthenticationTokenAudience exception.

Code I'm using:


import logging
from azure.identity import AzureCliCredential
from azure.mgmt.subscription import SubscriptionClient

credential = AzureCliCredential()
client = SubscriptionClient(credential=credential, logging_enable=True, base_url="https://management.usgovcloudapi.net/")
logging.basicConfig(filename='test_sub_debug.log', level=logging.DEBUG)
aba_logger = logging.getLogger('azure.mgmt.subscription')
aba_logger.setLevel(logging.DEBUG)
sub_list = client.subscriptions.list()
for subscription in sub_list:
    print(subscription)

# (obviously remove the base_url= parameter for the default behavior)
1

There are 1 answers

0
Mike On

I was able to get this to work, but when I logout of the AZ CLI it was still able to authenticate, so I can't be certain that it uses the same credentials. Here's the article that have more details: https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-sovereign-domain

import os
from msrestazure.azure_cloud import AZURE_US_GOV_CLOUD as CLOUD
from azure.mgmt.resource import SubscriptionClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential(authority=CLOUD.endpoints.active_directory)

subscription_client = SubscriptionClient(
    credential,
    base_url=CLOUD.endpoints.resource_manager,
    credential_scopes=[CLOUD.endpoints.resource_manager + "/.default"])

sub_list = subscription_client.subscriptions.list()
for subscription in sub_list:
    print(subscription)