-
-
Save al4/14ef99d72c1a5db5961e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python | |
import sqlite3 | |
import json | |
""" | |
Quick quick script to set the datasource for grafana dashboards | |
""" | |
OLD_DATASOURCE = 'null' | |
NEW_DATASOURCE = 'graphite' | |
SQLITE_DB = '/opt/grafana/data/grafana.db' | |
conn = None | |
try: | |
conn = sqlite3.connect(SQLITE_DB) | |
cur = conn.cursor() | |
cur.execute('SELECT id, data FROM dashboard;') | |
data = cur.fetchall() | |
except: | |
raise | |
for dash_id, dash_data in data: | |
dash = json.loads(dash_data) | |
for row in dash['rows']: | |
for panel in row['panels']: | |
try: | |
datasource = panel['datasource'] | |
except KeyError: | |
print("Skipping dashboard: {}, row: {}, panel: {}".format( | |
dash['title'], row['title'], panel['title'])) | |
if not datasource or datasource == OLD_DATASOURCE: | |
print("Updating dashboard: {}, row: {}, panel: {}".format( | |
dash['title'], row['title'], panel['title'])) | |
panel['datasource'] = NEW_DATASOURCE | |
cur.execute("UPDATE dashboard SET data=? WHERE id=?", (json.dumps(dash), dash_id)) |
I found this the same (and incompatible with python3). However, what I ended up doing:
# sqlite3 grafana.db .dump | sed -e 's/old datasource/new datasource/g' > grafana.db.new
and then dropping and importing the grafana.db.new with sqlite3
# mv grafana.db grafana.db.backup
# sqlite3 grafana.db < grafana.db.new
This works well if you had a previously unique datasource name (mine contained location i.e. "Prometheus-us-ord1")
Ah, funny that you guys found this and sorry that it doesn't work! I haven't used it since it was written, and can't actually remember writing it to be honest. It wouldn't surpise me if the data structure has changed, so it probably needs updating.
Hello folks!
I found an easy way to change data source for all dashboards. The method below tested only on sqlite database and grafana version 7.0.1.
Make a backup of grafanadb
cp grafana.db grafana.db.backup
connect to current database
sqlite3 grafana.db
execute sql query
update dashboard set data = replace(data,'"Graphite"','null');
where Graphite
is the name of datasource which you want to replace and null
means default datasource in grafana.
I know this was posted a few years ago but I could really use this now. I have a handful of dashboards that have dozens of panels using the default datasource. I need to set the default to a different datasource but right now this will require me to manually set the datasource on every single panel. it will take forever.
The above script works to retrieve the dashboards from the database. I am able to print(dash) and it displays all of the dashboards but I keep getting KeyError at "for row in dash['rows']". So i'm not able to traverse the json and find/update the datasource in the panels.