我可以使用 Azure 的 Python SDK 来控制 UAMI 并与虚拟机交互吗?

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

我正在开发一个命令行工具,它将跨不同的云平台工作来读取、启动和停止(解除分配)虚拟机。我在 AWS 中使用 EC2 实例使用

boto3
,但我还不知道如何在 Azure 中实现同样的功能。

在 AWS 中,我有一个 IAM 用户,其凭证用于 SDK 内的身份验证,并且权限受到限制,因此无法启动或停止任何敏感内容。

在 Azure 中,我的印象是,通过向 UAMI 分配具有有限权限的自定义角色也可以实现同样的效果。但是,到目前为止,我只能通过首先使用

az login
并使用我自己的凭据登录来使用适用于 Azure 的 Python SDK。

有没有一种方法可以仅使用来自 UAMI 的凭据(例如

client_id
subscription_id
tenant_id
)进行身份验证,并使其权限成为我将编写的 Python 脚本的唯一可用权限?

到目前为止,我收到的最好的建议是使用

ManagedIdentityCredential()
进行身份验证,如下所示:

from azure.identity import ManagedIdentityCredential
client_id = <UAMI_client_id>
credential = ManagedIdentityCredential(client_id=client_id)

但这对我来说会导致以下错误:

ImdsCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint.
ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint.
<some traceback>
azure.core.exceptions.ServiceRequestError: <urllib3.connection.HTTPConnection object at 0xffffb9a32110>: Failed to establish a new connection: [Errno 111] Connection refused

我认为这是因为我从本地计算机运行脚本(与我的最终产品的用户的方式大致相同),并且此身份验证方法似乎是为在 Azure 自己的环境中运行的代码设置的。

有什么类似的东西可以让我在不使用任何特定于用户的凭据的情况下进行身份验证吗?

azure authentication azure-python-sdk
1个回答
0
投票

根据此SO答案用户分配的托管身份无法在本地工作,您必须将具有所需角色的Azure功能中的UAMI添加到

Start and Stop VM
示例-贡献者角色。

将 UAMI 分配给 Azure Functions:-

enter image description here

UAMI 分配给 Azure 虚拟机:-

enter image description here

Python Http 触发代码:-

import azure.functions as func
from azure.identity import ManagedIdentityCredential
from azure.mgmt.compute import ComputeManagementClient

def main(req: func.HttpRequest) -> func.HttpResponse:
    # Create a credential object using ManagedIdentityCredential
    credential = ManagedIdentityCredential()

    # Create a ComputeManagementClient using the credential
    compute_client = ComputeManagementClient(credential, '015xxxxxxx7')

    # Now you can use compute_client to manage virtual machines

    return func.HttpResponse("Virtual machine management function executed successfully!")

函数触发器已从函数应用程序成功部署并运行:-

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.