在 NodeJS 中列出 Azure 中的所有资源

Listing all resources in Azure in NodeJS

我正在尝试使用 Javascript 的 Azure SDK 列出 Azure 订阅中的所有资源。我的方法是使用 @azure/ms-rest-nodeauth 包进行身份验证,然后从 @azure/arm-resources 包调用 ResourceManagementClient 但我遇到了几个问题。

1。应用注册

我选择使用 msRestNodeAuth.loginWithServicePrincipalSecretWithAuthResponse()。我进入 AzureAD 并创建了一个新的应用程序注册,然后在其中创建了一个秘密。这给了我一个 clientId、一个秘密和一个我可以提供给函数的 tenantId。

但是,我觉得我将面临的问题(一旦我真正让我的代码工作)是许可。我不知道需要对此应用程序注册应用什么权限才能允许它查询这样的资源。

我在我看过的任何文档中都看不到这个描述。

2。 ESM / CJS 问题

我是 运行 NodeJS v12.16.1。为了使用 ESM 导入语法,我提供了 --experimental-modules 标志和 es-module-specifier-resolution=node 以便在导入时不需要提供文件扩展名(package.json 文件也有 type: "module"设置)。这在许多包中都运行良好,但在上面的两个包中,导入似乎有一个包装器,这意味着我需要调用 .default 才能访问实际功能:

例如:

import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";
const res = await msRestNodeAuth.loginWithServicePrincipalSecretWithAuthResponse(_clientId, _secretValue, _tennantId);

...必须成为:

import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";
const res = await msRestNodeAuth.default.loginWithServicePrincipalSecretWithAuthResponse(_clientId, _secretValue, _tennantId);

代码在执行此操作时有效,但我的猜测是包的构建方式/我的 NodeJS 设置的配置方式有问题。我也无法从 @azure/arm-resources 导入 ResourceManagementClient,而必须这样做:

// This errors:
// import { ResourceManagementClient } from "@azure/arm-resources";
// ...but I can access it like:
import * as armResources from "@azure/arm-resources";

const client = new armResources.default.ResourceManagementClient();

3。把它们放在一起

当我尝试将它们放在一起并获取资源组列表时,出现错误:

const res = await msRestNodeAuth.default.loginWithServicePrincipalSecretWithAuthResponse(_clientId, _secretValue, _tennantId);

const client = new armResources.default.ResourceManagementClient(res.credentials, _subscriptionId);

const resourceGroups = await client.resourceGroups.list();

The client 'XYZ123' with object id 'abc678' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/read' over scope '/subscriptions/123213123' or the scope is invalid. If access was recently granted, please refresh your credentials.

我希望这只是一个身份验证错误,当问题 #1 得到解决时,它会得到解决 - 即应用程序注册获得所需的权限。

对于这个问题的广泛范围表示歉意;我习惯在 AWS 中这样做,所以我试图同时掌握 Azure 和这个 SDK。非常感谢任何帮助!

如果您想在一个订阅中列出所有 Azure 资源,您需要在订阅级别分配读取角色。更多详情请参考here and here

关于如何给sp分配角色,我们可以用PowerShell来实现

$id=(Get-AzADServicePrincipal -DisplayName <principalName>).id
New-AzRoleAssignment -ObjectId $id `
-RoleDefinitionName Reader `
-Scope /subscriptions/<subscriptionId>