k8s中可以安装grafana,但是数据源和dashboard需要在UI界面中配置,这样就造成了重启grafana后,数据源和dashboard就会消失,需要重新配置,当然可以配置数据持久化解决这一问题,但是怎样让grafana启动就加载这些配置而不用每次都重新配置呢?
首先配置数据源,以prometheus为例,grafana-datasources-configmaps.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: grafana-datasource
namespace: kube-system
labels:
grafana_datasource: "1"
app: prometheus-operator-grafana
data:
datasource.yaml: |-
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
url: http://192.168.20.58/ops/prometheus
access: proxy
然后需要在grafana.yaml中加载数据源
volumeMounts:
- name: sc-datasources-volume
mountPath: /etc/grafana/provisioning/datasources
volumes:
- name: sc-datasources-volume
configMap:
name: grafana-datasource
这样就可以加载prometheus数据源了。
配置dashboard就稍微麻烦一下,需要先将dashboard的json文件挂载到k8s的pod中,假设某个dashboard的json文件sample.json本机存放位置为/var/lib/grafana/dashboards/,需要现在grafana中挂载它,grafana.yaml配置如下
volumeMounts:
- name: sc-dashboards-provider
mountPath: /etc/grafana/provisioning/dashboardsJson
volumes:
- name: sc-dashboards-provider
hostPath:
path: /var/lib/grafana/dashboards/
将dashboard挂载之后,就需要配置dashboard的configmap了,将dashboard的配置文件挂载到对应位置,grafana-dashboards-configmaps.yaml内容如下。
apiVersion: v1
kind: ConfigMap
metadata:
name: grafana-dashboard
namespace: kube-system
labels:
app: grafana-operator-dashboard
data:
dashboard.yaml: |-
apiVersion: 1
providers:
- name: 'defalut'
orgId: 1
folderUid: ''
type: file
options:
path: /etc/grafana/provisioning/dashboardsJson
在grafana.yaml中加载配置。
volumeMounts:
- name: sc-dashboards-volume
mountPath: /etc/grafana/provisioning/dashboards
volumes:
- name: sc-dashboards-volume
configMap:
name: grafana-dashboard
这样dashboard就配置完毕了,重启grafana既可看到效果
tips: 在grafana.yaml文件中加载dashboard的json文件的配置一定要写在加载dashboard的configmap文件之前,否则会报错