我们正在尝试检索GCP中的账单帐户列表,为此,我们使用服务帐户。我们编写的代码如下:
async function listBillingAccounts(project)
{
let keys = JSON.parse(Buffer.from(process.env.SERVICE_ACCOUNT_BASE64_JSON, "base64").toString("ascii"));
const client = new CloudBillingClient({credentials : keys});
if (project !== undefined)
{
const [accounts] = await client.listBillingAccounts({ project, });
console.log(accounts);
}
else
{
const [accounts] = await client.listBillingAccounts({});
console.log(accounts);
}
console.info(`found ${accounts.length} billing accounts:`);
for (const account of accounts) {
console.info(`${account.displayName}:`);
console.info(`topen: ${account.open}`);
console.info(`tparentBillingAccount: ${account.masterBillingAccount}`);
}
}
SERVICE_ACCOUNT_BASE64_JSON包含服务帐户信息:
{
"type": "service_account",
"project_id": "xxxx",
"private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----n",
"client_email": "xxxxx@xxxxx",
"client_id": "xxxxxxxxxxxxxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxx"
}
无论是否指定项目名称,accounts结果始终是一个空数组。你知道会发生什么吗?我们向IAM Team询问服务帐户是否具有所需的权限,他们确认它具有:
https://www.googleapis.com/auth/cloud-billing.readonly——比;账单帐户使用承诺推荐查看器正确吗?
结果为空,因为服务帐户未被授权查看计费帐户。
您必须以具有billing account Viewer (roles/billing. Viewer)角色的授权用户向每个计费帐户添加服务帐户电子邮件地址。角色添加到计费帐户.
云计费访问控制概述