Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Command to export all grafana 2 dashboard to JSON using curl
KEY=XXXXXXXXXXXX
HOST="https://metrics.crisidev.org"
mkdir -p dashboards && for dash in $(curl -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']' '\n' |cut -d "," -f 5 |grep slug |cut -d\" -f 4); do
curl -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/db/$dash > dashboards/$dash.json
done
@gerr1t

This comment has been minimized.

Copy link

gerr1t commented May 4, 2016

Thanks, was looking for something simple like this 👍

@saargrin

This comment has been minimized.

Copy link

saargrin commented Aug 14, 2016

thanks for this script,saved me a bunch of time
perhaps you should mention that API key should be created for each org

another thing is , i found it useful to save the JSONs in human readable format by piping them through |python -m json.tool

@theonlydoo

This comment has been minimized.

Copy link

theonlydoo commented Aug 30, 2016

Here is an upgraded version for the latest version of grafana :

KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXX
HOST="https://my.super.duper.grafana.com"

if [ !-d dashboards ] ; then
    mkdir -p dashboards
fi

for dash in $(curl -sSL -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq '.' |grep -i uri|awk -F '"uri": "' '{ print $2 }'|awk -F '"' '{print $1 }'); do
  curl -sSL -k -H "Authorization: Bearer ${KEY}" "${HOST}/api/dashboards/${dash}" > dashboards/$(echo ${dash}|sed 's,db/,,g').json
done
@hagen1778

This comment has been minimized.

Copy link

hagen1778 commented Sep 12, 2016

I hope you don't mind that I've used your scripts for my repo: https://github.com/hagen1778/grafana-import-export

@arnaudlemaignen

This comment has been minimized.

Copy link

arnaudlemaignen commented Oct 6, 2016

Thanks all for the precious scripts, the export was working but then the import script is always rejected the dashboards for me in Grafana 3.1.1.
The fix was setting the id to null and adding the overwrite flag to true to be able either to create the dashboard from scratch or replace it if existing.
If you want to block the importation if already existing, you can simply set the overwrite flag to false.

Here is the code in the export script so the import script can run smoothly.
This code does not need the jq framework.

KEY=XXXX
HOST="http://XXXX:3000"

if [ !-d dashboards ] ; then
    mkdir -p dashboards
fi

for dash in $(curl -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']' '\n' |cut -d "," -f 5 | grep db |cut -d\" -f 4 |cut -d\/ -f2); do 
  curl -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/db/$dash | sed 's/"id":[0-9]\+,/"id":null,/' | sed 's/\(.*\)}/\1,"overwrite": true}/' > dashboards/$dash.json 
done
@skraiman

This comment has been minimized.

Copy link

skraiman commented Jul 13, 2017

I found that the previous script did not capture the first dashboard. This version fixes the problem:


SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
KEY=$(<~/.grafanakey)
HOST="http://localhost:3000"


if [ ! -d $SCRIPT_DIR/dashboards ] ; then
    mkdir -p $SCRIPT_DIR/dashboards
fi

for dash in $(curl -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |sed 's/{"id"/\\\n{"id"/g' |cut -d "," -f 3 | grep db |cut -d\" -f 4 |cut -d\/ -f2); do
  curl -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/db/$dash | sed 's/"id":[0-9]\+,/"id":null,/' | sed 's/\(.*\)}/\1,"overwrite": true}/' > $SCRIPT_DIR/dashboards/$dash.json
done
@shashanks93

This comment has been minimized.

Copy link

shashanks93 commented Jul 17, 2017

Can anyone please let me what's KEY and HOST here in the script ?

@olegmayko

This comment has been minimized.

Copy link

olegmayko commented Jul 18, 2017

@shashanks93
KEY is Grafana authorisation token. it is described well here http://docs.grafana.org/http_api/auth/
HOST is node on which your grafana instance is running. Basically, host of UI.
i

@infa-dsokolov

This comment has been minimized.

Copy link

infa-dsokolov commented Sep 15, 2017

Was able to achieve this by this script

#!/usr/bin/env bash
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
KEY=$(<~/.grafanakey)
HOST="https://mdmdev.cloudtrust.rocks"


if [ ! -d $SCRIPT_DIR/dashboards ] ; then
    mkdir -p $SCRIPT_DIR/dashboards
fi

for dash in $(curl -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq -r '.[] | .uri'); do
  curl -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/$dash | sed 's/"id":[0-9]\+,/"id":null,/' | sed 's/\(.*\)}/\1,"overwrite": true}/' > dashboards/$(echo ${dash} |cut -d\" -f 4 |cut -d\/ -f2).json
done
@SebastianUA

This comment has been minimized.

Copy link

SebastianUA commented Nov 26, 2017

#!/bin/bash -x
#
# http://linux-notes.org/
#
#Vitaliy Natarov
#Set some colors for status OK, FAIL and titles
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

SETCOLOR_TITLE="echo -en \\033[1;36m" #Fuscia
SETCOLOR_TITLE_GREEN="echo -en \\033[0;32m" #green
SETCOLOR_TITLE_PURPLE="echo -en \\033[0;35m" #purple 
SETCOLOR_NUMBERS="echo -en \\033[0;34m" #BLUE

KEY="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
HOST="http://graffana_url"
DASH_DIR="~/Grafana/dashboards"

if [ ! -d "$DASH_DIR" ]; then
	 mkdir -p dashboards 
else
	 $SETCOLOR_TITLE_PURPLE
	 echo "|-------------------------------------------------------------------------------|";
	 echo "| A $DASH_DIR directory is already exist! |";
	 echo "|-------------------------------------------------------------------------------|";
	 $SETCOLOR_NORMAL
fi
  
#curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']{' '\n'| cut -d ':' -f4| cut -d ',' -f1| cut -d '"' -f2 | grep -Ev "(^$|\[)"| cut -c 4-

for dash in $(curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']{' '\n'| cut -d ':' -f4| cut -d ',' -f1| cut -d '"' -f2 | grep -Ev "(^$|\[)"| cut -c 4-); do
	curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/db/$dash > dashboards/$dash.json
	$SETCOLOR_TITLE_GREEN
	echo "The [ $dash ] dashboard has been exported"  
	$SETCOLOR_NORMAL
done

$SETCOLOR_TITLE
echo "|-------------------------------------------------------------------------------|";
echo "|----------------------------------FINISHED-------------------------------------|";
echo "|-------------------------------------------------------------------------------|";
$SETCOLOR_NORMAL
@satish-chef

This comment has been minimized.

Copy link

satish-chef commented Jan 15, 2018

@SebastianUA, can you please share the restore script as well which can be used to restore dashboards backup taken by your script.
Thanks in Advance !

@timeforce

This comment has been minimized.

Copy link

timeforce commented Feb 11, 2018

how did you create a new dashboard with exported json file?
I try this but got the error. However, when I manually insert the json file through UI, it works.

curl -k -H "Content-Type: application/json" -H "Authorization: Bearer $KEY" -X POST -d dashboards/$DASHBOARD.json $HOST:$PORT/api/dashboards/db

[{"classification":"DeserializationError","message":"invalid character 'd' looking for beginning of value"},{"fieldNames":["Dashboard"],"classification":"RequiredError","message":"Required"}]

@kosuke-

This comment has been minimized.

Copy link

kosuke- commented Mar 1, 2018

@timeforce

Please add the following to the end of json file.
I could.

  },
  "overwrite": true
}
@kosuke-

This comment has been minimized.

Copy link

kosuke- commented Mar 1, 2018

Thank you for creating.
I improved visibility of json file.

#!/usr/bin/env bash
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
KEY=$(<~/.grafanakey)
HOST="https://mdmdev.cloudtrust.rocks"


if [ ! -d $SCRIPT_DIR/dashboards ] ; then
    mkdir -p $SCRIPT_DIR/dashboards
fi

for dash in $(curl -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq -r '.[] | .uri'); do
  curl -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/$dash | sed 's/"id":[0-9]\+,/"id":null,/' | sed 's/\(.*\)}/\1,"overwrite": true}/' | jq . > dashboards/$(echo ${dash} |cut -d\" -f 4 |cut -d\/ -f2).json
done
@esroberts

This comment has been minimized.

Copy link

esroberts commented Mar 12, 2018

Updating on @SebastianUA's solution to work with grafana 5.0 (access dashboards by uid)

#!/bin/bash -x
#
# http://linux-notes.org/
#
#Vitaliy Natarov
#Set some colors for status OK, FAIL and titles
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

SETCOLOR_TITLE="echo -en \\033[1;36m" #Fuscia
SETCOLOR_TITLE_GREEN="echo -en \\033[0;32m" #green
SETCOLOR_TITLE_PURPLE="echo -en \\033[0;35m" #purple 
SETCOLOR_NUMBERS="echo -en \\033[0;34m" #BLUE

KEY="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
HOST="http://graffana_url"
DASH_DIR="~/Grafana/dashboards"

if [ ! -d "$DASH_DIR" ]; then
	 mkdir -p dashboards 
else
	 $SETCOLOR_TITLE_PURPLE
	 echo "|-------------------------------------------------------------------------------|";
	 echo "| A $DASH_DIR directory is already exist! |";
	 echo "|-------------------------------------------------------------------------------|";
	 $SETCOLOR_NORMAL
fi
  
#curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']{' '\n'| cut -d ':' -f3| cut -d ',' -f1| cut -d '"' -f2 | grep -Ev "(^$|\[)"| cut -c 4-

for dash in $(curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']{' '\n'| cut -d ':' -f3| cut -d ',' -f1| cut -d '"' -f2 | grep -Ev "(^$|\[)"| cut -c 4-); do
	curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/dashboards/uid/$dash > dashboards/$dash.json
	$SETCOLOR_TITLE_GREEN
	echo "The [ $dash ] dashboard has been exported"  
	$SETCOLOR_NORMAL
done

$SETCOLOR_TITLE
echo "|-------------------------------------------------------------------------------|";
echo "|----------------------------------FINISHED-------------------------------------|";
echo "|-------------------------------------------------------------------------------|";
$SETCOLOR_NORMAL
@Vehyla

This comment has been minimized.

Copy link

Vehyla commented Mar 13, 2018

I played with a couple of these scripts and I did get dashboards. But I noticed that all my templated dashboards do not have their variables. Which is most of our dashboards. Has anyone had experience pulling a dashboard with template variables?

@crisidev

This comment has been minimized.

Copy link
Owner Author

crisidev commented Apr 14, 2018

I've lost track of this gist. It is awesome to see such engagement and improvements!

@jensschulze

This comment has been minimized.

Copy link

jensschulze commented May 24, 2018

For Grafana 5.0.0 I had to remove the cut -c 4-.

#!/bin/bash
#
# Vitaliy Natarov
# see https://gist.github.com/crisidev/bd52bdcc7f029be2f295
#
# add the "-x" option to the shebang line if you want a more verbose output
#
# set some colors for status OK, FAIL and titles
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

SETCOLOR_TITLE="echo -en \\033[1;36m" # fuchsia
SETCOLOR_TITLE_GREEN="echo -en \\033[0;32m" # green
SETCOLOR_TITLE_PURPLE="echo -en \\033[0;35m" # purple 
SETCOLOR_NUMBERS="echo -en \\033[0;34m" # blue

KEY="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
HOST="http://grafana_url:grafana_port"
DASH_DIR="${HOME}/Documents/Grafana/dashboards" # adapt to your needs!

if [ ! -d "${DASH_DIR}" ]; then
	 mkdir -p "${DASH_DIR}" 
else
	 ${SETCOLOR_TITLE_PURPLE}
	 echo "|-------------------------------------------------------------------------------|";
	 echo "| A $DASH_DIR directory already exists! |";
	 echo "|-------------------------------------------------------------------------------|";
	 ${SETCOLOR_NORMAL}
fi
  
#curl -sS -k -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& |tr ']{' '\n'| cut -d ':' -f3| cut -d ',' -f1| cut -d '"' -f2 | grep -Ev "(^$|\[)"
#exit 0

for dash in $(curl -sS -k -H "Authorization: Bearer ${KEY}" ${HOST}/api/search\?query\=\& |tr ']{' '\n'| cut -d ':' -f3| cut -d ',' -f1| cut -d '"' -f2 | grep -Ev "(^$|\[)"); do
	curl -sS -k -H "Authorization: Bearer ${KEY}" "${HOST}/api/dashboards/uid/${dash}" -o "${DASH_DIR}/${dash}.json"
	${SETCOLOR_TITLE_GREEN}
	echo "The [ ${dash} ] dashboard has been exported as ${DASH_DIR}/${dash}.json"  
	${SETCOLOR_NORMAL}
done

$SETCOLOR_TITLE
echo "|-------------------------------------------------------------------------------|";
echo "|----------------------------------FINISHED-------------------------------------|";
echo "|-------------------------------------------------------------------------------|";
$SETCOLOR_NORMAL
@vanugrah

This comment has been minimized.

Copy link

vanugrah commented Sep 14, 2018

Made a few updates:

  • Makes $HOST and $KEY as command line arguments.
  • Updates JSON parsing to use jq.
  • Filters out the folders from the search query so only dashboards are saved.
  • Saves dashboard using dashboard title instead of uid.
  • Gets the folder name and preserves the folder organization when saving dashboards. Really useful if you have a ton of dashboards and folders
  • Some refactoring to include an init function and common log functions with timestamps.
#!/bin/bash
#
# Anugrah Vijay
# add the "-x" option to the shebang line if you want a more verbose output
#
# set some colors for status OK, FAIL and titles
SETCOLOR_SUCCESS="echo -en \\033[0;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"
SETCOLOR_TITLE_PURPLE="echo -en \\033[0;35m" # purple 

# usage log "string to log" "color option"
function log_success() {
	if [ $# -lt 1 ]; then
	    ${SETCOLOR_FAILURE}
	    echo "Not enough arguments for log function! Expecting 1 argument got $#"
	    exit 1
	fi

	timestamp=$(date "+%Y-%m-%d %H:%M:%S %Z")

	${SETCOLOR_SUCCESS}
	printf "[${timestamp}] $1\n"
	${SETCOLOR_NORMAL}
}

function log_failure() {
	if [ $# -lt 1 ]; then
	    ${SETCOLOR_FAILURE}
	    echo "Not enough arguments for log function! Expecting 1 argument got $#"
	    exit 1
	fi

	timestamp=$(date "+%Y-%m-%d %H:%M:%S %Z")

	${SETCOLOR_FAILURE}
	printf "[${timestamp}] $1\n"
	${SETCOLOR_NORMAL}
}

function log_title() {
	if [ $# -lt 1 ]; then
	    ${SETCOLOR_FAILURE}
	    log_failure "Not enough arguments for log function! Expecting 1 argument got $#"
	    exit 1
	fi

	${SETCOLOR_TITLE_PURPLE}
	printf "|-------------------------------------------------------------------------|\n"
	printf "|$1|\n";
	printf "|-------------------------------------------------------------------------|\n"
	${SETCOLOR_NORMAL}
}

function init() {
	# Check if hostname and key are provided 
	if [ $1 -lt 2 ]; then
	    ${SETCOLOR_FAILURE}
	    log_failure "Not enough command line arguments! Expecting two: \$HOSTNAME and \$KEY. Recieved only $1."
	    exit 1
	fi

	DASH_DIR=$(echo $HOST | awk -F[/:] '{print $4}')

	if [ ! -d "${DASH_DIR}" ]; then
		 mkdir "${DASH_DIR}" 
	else
		log_title "----------------- A $DASH_DIR directory already exists! -----------------"
	fi
}


HOST=$1
KEY=$2
init $# $HOST $KEY

for dashboard_uid in $(curl -sS -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq -r '.[] | select( .type | contains("dash-db")) | .uid'); do 

	dashboard_json="$(curl -sS -H "Authorization: Bearer $KEY" $HOST/api/dashboards/uid/$dashboard_uid)"
	dashboard_title="$(echo $dashboard_json | jq -r '.dashboard | .title')"
	folder_title="$(echo $dashboard_json | jq -r '.meta | .folderTitle')"

	mkdir -p "$DASH_DIR/$folder_title"
	echo $dashboard_json > "$DASH_DIR/$folder_title/$dashboard_title.json"

	log_success "Dashboard has been saved\t\t title=\"${dashboard_title}\", uid=\"${dashboard_uid}\", path=\"${DASH_DIR}/$folder_title/${dashboard_title}.json\"." 
done

log_title "------------------------------ FINISHED ---------------------------------";
@ksandrmatveyev

This comment has been minimized.

Copy link

ksandrmatveyev commented Jan 2, 2019

@van

Made a a couple tweaks:

  • counter of saved dashboards
  • replace some special symbols if they exist in a title
  • version of saved dashboard in its filename

#!/bin/bash
#
# add the "-x" option to the shebang line if you want a more verbose output
#
# set some colors for status OK, FAIL and titles
SETCOLOR_SUCCESS="echo -en \\033[0;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"
SETCOLOR_TITLE_PURPLE="echo -en \\033[0;35m" # purple 

# usage log "string to log" "color option"
function log_success() {
   if [ $# -lt 1 ]; then
       ${SETCOLOR_FAILURE}
       echo "Not enough arguments for log function! Expecting 1 argument got $#"
       exit 1
   fi

   timestamp=$(date "+%Y-%m-%d %H:%M:%S %Z")

   ${SETCOLOR_SUCCESS}
   printf "[${timestamp}] $1\n"
   ${SETCOLOR_NORMAL}
}

function log_failure() {
   if [ $# -lt 1 ]; then
       ${SETCOLOR_FAILURE}
       echo "Not enough arguments for log function! Expecting 1 argument got $#"
       exit 1
   fi

   timestamp=$(date "+%Y-%m-%d %H:%M:%S %Z")

   ${SETCOLOR_FAILURE}
   printf "[${timestamp}] $1\n"
   ${SETCOLOR_NORMAL}
}

function log_title() {
   if [ $# -lt 1 ]; then
       ${SETCOLOR_FAILURE}
       log_failure "Not enough arguments for log function! Expecting 1 argument got $#"
       exit 1
   fi

   ${SETCOLOR_TITLE_PURPLE}
   printf "|-------------------------------------------------------------------------|\n"
   printf "|$1|\n";
   printf "|-------------------------------------------------------------------------|\n"
   ${SETCOLOR_NORMAL}
}

function init() {
   # Check if hostname and key are provided 
   if [ $1 -lt 2 ]; then
       ${SETCOLOR_FAILURE}
       log_failure "Not enough command line arguments! Expecting two: \$HOSTNAME and \$KEY. Recieved only $1."
       exit 1
   fi

   DASH_DIR=$(echo $HOST | awk -F[/:] '{print $4}')

   if [ ! -d "${DASH_DIR}" ]; then
   	 mkdir "${DASH_DIR}" 
   else
   	log_title "----------------- A $DASH_DIR directory already exists! -----------------"
   fi
}


HOST=$1
KEY=$2
init $# $HOST $KEY

counter=0

for dashboard_uid in $(curl -sS -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq -r '.[] | select( .type | contains("dash-db")) | .uid'); do 

   counter=$((counter + 1))
   dashboard_json="$(curl -sS -H "Authorization: Bearer $KEY" $HOST/api/dashboards/uid/$dashboard_uid)"
   dashboard_title="$(echo $dashboard_json | jq -r '.dashboard | .title' | sed -r 's/[ \/]+/_/g' )"
   dashboard_version="$(echo $dashboard_json | jq -r '.dashboard | .version')"
   folder_title="$(echo $dashboard_json | jq -r '.meta | .folderTitle')"

   mkdir -p "$DASH_DIR/$folder_title"
   echo $dashboard_json > "$DASH_DIR/$folder_title/${dashboard_title}_v${dashboard_version}.json"

   log_success "Dashboard has been saved\t\t title=\"${dashboard_title}\", uid=\"${dashboard_uid}\", path=\"${DASH_DIR}/$folder_title/${dashboard_title}_v${dashboard_version}.json\"." 
done

log_title "${counter} dashboards were saved";

log_title "------------------------------ FINISHED ---------------------------------";
@RudW0lf

This comment has been minimized.

Copy link

RudW0lf commented Mar 8, 2019

Hi, seems need to add special key to disable ssl verification which add --insecure key to curl.

@adityagundecha

This comment has been minimized.

Copy link

adityagundecha commented Jun 6, 2019

Made a change to ease the life of Windows users!

#/bin/bash
#
# add the "-x" option to the shebang line if you want a more verbose output
#
# set some colors for status OK, FAIL and titles
SETCOLOR_SUCCESS="echo -en \\033[0;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"
SETCOLOR_TITLE_PURPLE="echo -en \\033[0;35m" # purple 

# usage log "string to log" "color option"
function log_success() {
   if [ $# -lt 1 ]; then
       ${SETCOLOR_FAILURE}
       echo "Not enough arguments for log function! Expecting 1 argument got $#"
       exit 1
   fi

   timestamp=$(date "+%Y-%m-%d %H:%M:%S %Z")

   ${SETCOLOR_SUCCESS}
   printf "[${timestamp}] $1\n"
   ${SETCOLOR_NORMAL}
}

function log_failure() {
   if [ $# -lt 1 ]; then
       ${SETCOLOR_FAILURE}
       echo "Not enough arguments for log function! Expecting 1 argument got $#"
       exit 1
   fi

   timestamp=$(date "+%Y-%m-%d %H:%M:%S %Z")

   ${SETCOLOR_FAILURE}
   printf "[${timestamp}] $1\n"
   ${SETCOLOR_NORMAL}
}

function log_title() {
   if [ $# -lt 1 ]; then
       ${SETCOLOR_FAILURE}
       log_failure "Not enough arguments for log function! Expecting 1 argument got $#"
       exit 1
   fi

   ${SETCOLOR_TITLE_PURPLE}
   printf "|-------------------------------------------------------------------------|\n"
   printf "|$1|\n";
   printf "|-------------------------------------------------------------------------|\n"
   ${SETCOLOR_NORMAL}
}

function init() {
   # Check if hostname and key are provided 
   if [ $1 -lt 2 ]; then
       ${SETCOLOR_FAILURE}
       log_failure "Not enough command line arguments! Expecting two: \$HOSTNAME and \$KEY. Recieved only $1."
       exit 1
   fi

   DASH_DIR=$(echo $HOST | awk -F[/:] '{print $4}')

   if [ ! -d "${DASH_DIR}" ]; then
   	 mkdir "${DASH_DIR}" 
   else
   	log_title "----------------- A $DASH_DIR directory already exists! -----------------"
   fi
}


HOST=$1
KEY=$2
init $# $HOST $KEY

counter=0

for dashboard_uid in $(curl -sS -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq -r '.[] | select( .type | contains("dash-db")) | .uid'); do 

   counter=$((counter + 1))
   url=`echo $HOST/api/dashboards/uid/$dashboard_uid | tr -d '\r'`
   dashboard_json=$(curl -sS -H "Authorization: Bearer $KEY" $url)
   dashboard_title=$(echo $dashboard_json | jq -r '.dashboard | .title' | sed -r 's/[ \/]+/_/g' )
   dashboard_version=$(echo $dashboard_json | jq -r '.dashboard | .version')
   folder_title=$(echo $dashboard_json | jq -r '.meta | .folderTitle')

   mkdir -p "$DASH_DIR/$folder_title"
   echo $dashboard_json > "$DASH_DIR/$folder_title/${dashboard_title}_v${dashboard_version}.json"

   log_success "Dashboard has been saved\t\t title=\"${dashboard_title}\", uid=\"${dashboard_uid}\", path=\"${DASH_DIR}/$folder_title/${dashboard_title}_v${dashboard_version}.json\"." 
done

log_title "${counter} dashboards were saved";

log_title "------------------------------ FINISHED ---------------------------------";```
@wnasich

This comment has been minimized.

Copy link

wnasich commented Jun 16, 2019

Another tool to export dashboards, now with PHP -> https://github.com/wnasich/grafana_dd

@wumfi

This comment has been minimized.

Copy link

wumfi commented Aug 14, 2019

It's possible that I was doing something wrong, but just in case, I'm adding to this discussion to save others the hassle that I've just been through.

Whilst this explains a way of exporting the JSON from the dashboards, the format it comes out in will not directly import back in.

After playing around, I found that the simply piping out to:

jq .

Created a JSON file that was one level too high. When I attempted to import the resulting file back into Grafana, it created the dashboard completely empty. Instead, if we do:

jq .dashboard

Then you get a JSON file in the format that Grafana wants. I have tested this by creating several dashboards, using the script to export them (with the above fix), deleting them and then re-importing them. All now works fine.

@thedoc31

This comment has been minimized.

Copy link

thedoc31 commented Aug 29, 2019

If running on a Mac, the antiquated BSD version of sed included with OSX does not support extended regex. Therefore, you first need to install brew and gnu-sed, then change sed to gsed in the line below.

dashboard_title=$(echo $dashboard_json | jq -r '.dashboard | .title' | sed -r 's/[ \/]+/_/g' )

becomes

dashboard_title=$(echo $dashboard_json | jq -r '.dashboard | .title' | gsed -r 's/[ \/]+/_/g' )

@thedoc31

This comment has been minimized.

Copy link

thedoc31 commented Aug 30, 2019

Also, if you're looking for a batch import dashboard script to go along with this (perhaps you're migrating Grafana servers like I am), I've written a gist based on this one to batch import JSON dashboard files.

Grafana Import Dashboard Gist: https://gist.github.com/thedoc31/628beeee934f9c84648c108d4ad89f05

@crisidev

This comment has been minimized.

Copy link
Owner Author

crisidev commented Sep 2, 2019

Wow!!! I was not expecting this kind of engagement from this ;)

@xmfreak

This comment has been minimized.

Copy link

xmfreak commented Sep 19, 2019

Just want to give my two cents on this. I have multiple orgs in Grafana (hence multiple api keys) so I did the following modifications to the scripts above to backup dashboards for each org.

# Declare a list with the api keys using as a prefix the organization name plus "_" character
declare -a StringArray=("MAIN_<api-key>" "OtherOrg_<api-key>" "YetOnAnother_<api-key>")

# Iterate through api keys:
for API_KEY in "${StringArray[@]}"; do
    ORG=$(echo $API_KEY | cut -d "_" -f1) # Name of the organization based on the prefix
    KEY=$(echo $API_KEY | cut -d "_" -f2) # API Key for that organization after removing the prefix

    # Iterate through dashboards using the current API Key
    for dashboard_uid in $(curl -sS -H "Authorization: Bearer $KEY" $HOST/api/search\?query\=\& | jq -r '.[] | select( .type | contains("dash-db")) | .uid'); do

        url=`echo $HOST/api/dashboards/uid/$dashboard_uid | tr -d '\r'`
        dashboard_json=$(curl -sS -H "Authorization: Bearer $KEY" $url)
        dashboard_title=$(echo $dashboard_json | jq -r '.dashboard | .title' | sed -r 's/[ \/]+/_/g' )
        dashboard_version=$(echo $dashboard_json | jq -r '.dashboard | .version')

        # You can export the files like this to keep them organized by organization:
        mkdir -p "$DASH_DIR/dashboards_$ORG"
        echo $dashboard_json > "$DASH_DIR}/dashboards_$ORG/${dashboard_title}_v${dashboard_version}.json"
    done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.