You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grafana容器启动时预配置仅具查看权限的普通用户方案问询

在Grafana容器启动时自动创建仅查看权限的普通用户

问题描述

需要启动一个预配置了仅具查看权限普通用户的Grafana容器,管理员用户可通过GF_SECURITY_ADMIN_USER/GF_SECURITY_ADMIN_PASSWORD环境变量或grafana.ini轻松配置,但找不到直接添加初始普通用户的官方选项。尝试过通过provisioning YAML文件配置,该方式仅适用于Grafana 7.x,在10.x版本中无效;也考虑过用额外容器调用API,但希望避免多容器配置,且仅需首次启动时执行用户创建逻辑。

解决方案:利用Grafana容器的初始化脚本钩子

Grafana官方Docker镜像支持将自定义脚本挂载到/docker-entrypoint.d/目录,容器启动时会自动执行该目录下的可执行脚本。我们可以编写脚本,在容器内部等待Grafana服务启动后,调用官方API创建用户并设置权限,同时加入判断逻辑避免重复执行。

步骤1:创建初始化脚本

创建init-grafana-users.sh文件,内容如下:

#!/bin/sh

# 等待Grafana服务完全启动
until curl -s "http://localhost:3000/api/health" | grep -q "ok"; do
  echo "等待Grafana服务启动..."
  sleep 5
done

# 检查目标用户是否已存在
USER_EXISTS=$(curl -s -u "${GF_SECURITY_ADMIN_USER}:${GF_SECURITY_ADMIN_PASSWORD}" "http://localhost:3000/api/users/lookup?loginOrEmail=TestUser" | grep -q '"id"'; echo $?)

if [ $USER_EXISTS -ne 0 ]; then
  echo "开始创建TestUser用户..."
  # 创建普通用户
  curl -X POST \
    -u "${GF_SECURITY_ADMIN_USER}:${GF_SECURITY_ADMIN_PASSWORD}" \
    "http://localhost:3000/api/admin/users" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "TestUser",
      "login": "TestUser",
      "password": "TestUserPassword"
    }'

  # 获取用户ID并设置为Viewer权限
  USER_ID=$(curl -s -u "${GF_SECURITY_ADMIN_USER}:${GF_SECURITY_ADMIN_PASSWORD}" "http://localhost:3000/api/users/lookup?loginOrEmail=TestUser" | grep -o '"id":[0-9]*' | cut -d: -f2)
  curl -X PUT \
    -u "${GF_SECURITY_ADMIN_USER}:${GF_SECURITY_ADMIN_PASSWORD}" \
    "http://localhost:3000/api/users/${USER_ID}/permissions" \
    -H "Content-Type: application/json" \
    -d '{
      "items": [
        {
          "permission": 1,
          "role": "Viewer",
          "scope": "global"
        }
      ]
    }'
  echo "TestUser用户创建并配置完成"
else
  echo "TestUser用户已存在,跳过创建步骤"
fi

步骤2:修改docker-compose配置

更新docker-compose.yml,将脚本挂载到容器的/docker-entrypoint.d/目录,并确保脚本可执行:

version: '3'
services:
  grafana:
    image: grafana/grafana-oss:10.2.0
    container_name: grafana
    volumes:
      - ./grafana.ini:/etc/grafana/grafana.ini:ro
      - ./init-grafana-users.sh:/docker-entrypoint.d/init-grafana-users.sh:ro
    environment:
      - GF_SECURITY_ADMIN_USER=AdminUser
      - GF_SECURITY_ADMIN_PASSWORD=PASSW0RD
    command: ["sh", "-c", "chmod +x /docker-entrypoint.d/init-grafana-users.sh && /run.sh"]

方案优势

  • 无需额外配置容器,所有操作在Grafana容器内部完成
  • 通过用户存在性检查,确保仅首次启动时执行创建逻辑,避免重复操作
  • 基于Grafana官方REST API实现,兼容8.x及以上版本(包括10.x)

注意事项

  • 确保脚本中的用户名、密码与实际需求匹配,密码需符合Grafana的密码复杂度要求
  • 如果使用自定义端口,需修改脚本中的localhost:3000为对应端口
  • Grafana 8.x及以后版本已移除通过provisioning YAML配置普通用户的功能,因此之前推荐的users.yaml方式仅适用于7.x及更早版本,新版本中无效

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 03:28:32