使用什么 Azure 帐户在多个 Azure 租户资源上运行 Python 脚本?

问题描述 投票:0回答:2

我正在测试一个 python 脚本,它将检查 Azure 中每个资源的标签。此脚本从 CSV 文件获取资源列表,其中列出了来自不同租户的资源。

出于测试目的,我使用的 Azure 帐户仅存在于一个租户中,因此当我访问其他租户中的资源时,脚本会失败。

我应该使用什么帐户/解决方案从我的脚本中获取不同租户的信息?

有什么想法吗?

我尝试使用 az login 连接到每个租户的不同帐户,但保留的令牌只是我最后登录的帐户之一,因此无法使用 Azure CLI 登录多个帐户。

我想这与服务主体相同,因为只有一个租户知道它。

python azure azure-cli azure-sdk azure-service-principal
2个回答
0
投票

是的,您可以利用一个多租户应用程序来访问多个 Azure 租户上的资源。

TenantA

中创建
多租户 Microsoft Entra ID 应用程序

enter image description here

使用

TenantB
命令在
New-AzADServicePrincipal -ApplicationId <AppIdOFMultitenantappFromTenantA>
中创建企业应用程序。

读者角色分配给

TenantB
中的企业应用程序:

enter image description here

要访问

TenantB
资源,请按以下方式登录:

enter image description here

az login --service-principal -u ServicePrincipalID -p "ClientSecret" -t TenantBID

我使用下面的示例代码来获取

TenantB
的资源和资源标签:

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient

credential = DefaultAzureCredential()
resource_client = ResourceManagementClient(credential, "b83c1ed3-c5b6-44fb-b5ba-2b83a074c23f")
resources = resource_client.resources.list()

for resource in resources:
    print(f"Resource name: {resource.name}")
    print(f"Resource tags: {resource.tags}")

enter image description here

参考:

使用多租户应用程序进行 Azure 身份验证 |通过云之旅 |中等


0
投票

我最终在我的脚本中分别连接到每个租户。

if current_tenant != tenant:
                if tenant == 'PROD':
                    print("login into azure CORP")
                    os.system('az login --tenant xxxx')
                    
                elif tenant == 'HML':
                    print("login into azure hml")
                    os.system('az login --tenant yyyyyyy')
                
                elif tenant == 'DEV':
                    print("login into azure dev")
                    os.system('az login --tenant ccccccc')
                elif tenant == 'REC':
                    print("login into azure Rec")
                    os.system('az login --tenant wwwwwwwww')
© www.soinside.com 2019 - 2024. All rights reserved.