教程:以编程方式调用 Grafana API

在本教程中,你将了解如何执行以下操作:

  • 将 Azure 托管 Grafana 角色分配给应用程序的服务主体
  • 检索应用程序详细信息
  • 获取访问令牌
  • 调用 Grafana API

先决条件

登录 Azure

使用 Azure 帐户登录到 https://portal.azure.cn/ 的 Azure 门户。

将 Azure 托管 Grafana 角色分配给应用程序的服务主体

  1. 在 Azure 门户中打开你的托管 Grafana 实例。

  2. 在导航菜单中,选择“访问控制(IAM)”。

  3. 依次选择“添加”、“添加角色分配”。

  4. 选择“Grafana 编辑者”角色,然后选择“下一步”。

  5. 在“将访问权限分配给”下,选择“用户、组或服务主体”。

  6. 选择“选择成员”,选择你的服务主体,然后单击“选择”。

  7. 选择“查看 + 分配”。

    Screenshot of Add role assignment in the Azure platform.

检索应用程序详细信息

现在需要收集一些信息,用于获取 Grafana API 访问令牌并调用 Grafana API。

  1. 查找租户 ID:

    1. 在 Azure 门户中的“搜索资源、服务和文档(G+/)”中输入“Microsoft Entra ID”。
    2. 选择“Microsoft Entra ID”。
    3. 在左侧菜单中选择“属性”。
    4. 找到字段“租户 ID”并保存其值。

    Screenshot of the Azure portal, getting tenant ID.

  2. 查找客户端 ID:

    1. 在 Azure 门户的“Microsoft Entra ID”中,从左侧菜单选择“应用注册”。
    2. 选择应用。
    3. 在“概述”中,找到“应用程序(客户端) ID”字段并保存其值。

    Screenshot of the Azure portal, getting client ID.

  3. 创建应用程序机密:

    1. 在 Azure 门户的“Microsoft Entra ID”中,从左侧菜单中选择“应用注册”。
    2. 选择应用。
    3. 从左菜单中选择“证书和机密”
    4. 选择“新建客户端机密”。
    5. 创建新的客户端密码并保存其值。

    Screenshot of the Azure portal, creating a secret.

    注意

    只能在创建机密后立即访问其值。 请在离开页面之前复制该值,以便在本教程的下一步中使用该值。

  4. 查找 Grafana 终结点 URL:

    1. 在Azure 门户中的“搜索资源、服务和文档(G+/)”栏中输入“Azure 托管 Grafana”。
    2. 选择“Azure 托管 Grafana”并打开托管 Grafana 工作区。
    3. 从左侧菜单中选择“概述”并保存“终结点”值。

    Screenshot of the Azure platform. Endpoint displayed in the Overview page.

获取访问令牌

若要访问 Grafana API,需要获取访问令牌。 可以使用 Azure CLI 或发出 POST 请求获取访问令牌。

通过运行 az login 命令登录到 Azure CLI,并将 <client-id><client-secret><tenant-id> 替换为在上一步中收集的应用程序(客户端)ID、客户端密码和租户 ID:

az login --service-principal --username "<client-id>" --password "<client-secret>" --tenant "<tenant-id>"

使用命令 az grafana api-key create 创建密钥。 下面是示例输出:

az grafana api-key create --key keyname --name <name> --resource-group <rg> --role editor --output json

{
  "id": 3,
  "key": "<redacted>",
  "name": "keyname"
}

注意

只能在此处查看此密钥一次。 请将其保存在安全位置。

调用 Grafana API

现在,可以使用上一步中检索到的访问令牌作为 Authorization 标头调用 Grafana API。 例如:

curl -X GET \
-H 'Authorization: Bearer <access-token>' \
https://<grafana-url>/api/user

<access-token> 替换为上一步中检索到的访问令牌,并将 <grafana-url> 替换为 Grafana 实例的终结点 URL。 例如,https://my-grafana-abcd.cuse.grafana.azure.com

清理资源

如果你不打算继续使用这些资源,请按以下步骤删除它们:

  1. 删除 Azure 托管 Grafana:

    1. 在Azure 门户的“Azure 托管 Grafana”中,从左侧菜单选择“概述”。
    2. 选择“删除”。
    3. 输入资源名称以确认删除,然后选择“删除”。
  2. 删除 Microsoft Entra 应用程序:

    1. 在 Azure 门户的“Microsoft Entra ID”中,从左侧菜单中选择“应用注册”。
    2. 选择应用。
    3. 在“概述”选项卡上,选择“删除”。
    4. 选择“删除”。

后续步骤