Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Aref-Riant/12504c5ba90f58329d57eff7d267cfb2 to your computer and use it in GitHub Desktop.
Save Aref-Riant/12504c5ba90f58329d57eff7d267cfb2 to your computer and use it in GitHub Desktop.
python script to add a label match to grafana dashboard json files
import json
import re
import glob
import os
def add_environment_label(dashboard_file, new_label: str):
# Read the dashboard JSON
with open(dashboard_file, 'r', encoding='utf-8') as f:
dashboard = json.load(f)
# Regular expression to find metric expressions and add environment label
metric_pattern = re.compile(r'([a-zA-Z_][a-zA-Z0-9_]*)\{([^}]*)\}')
modified = False
# Recursively search for targets in panels
def process_targets(data, new_label: str):
nonlocal modified
if isinstance(data, dict):
if 'targets' in data:
for target in data['targets']:
if 'expr' in target:
# Process the expression
def replacer(m):
base = m.group(1)
labels = m.group(2)
new_labels = f'{labels}, ' if labels else ''
new_labels += new_label
return f'{base}{{{new_labels}}}'
new_expr = metric_pattern.sub(replacer, target['expr'])
if new_expr != target['expr']:
target['expr'] = new_expr
modified = True
for key, value in data.items():
process_targets(value, new_label)
elif isinstance(data, list):
for item in data:
process_targets(item, new_label)
process_targets(dashboard, new_label)
if modified:
# Backup original file
backup_file = dashboard_file + '.bak'
if not os.path.exists(backup_file):
os.rename(dashboard_file, backup_file)
# Write modified dashboard
with open(dashboard_file, 'w', encoding='utf-8') as f:
json.dump(dashboard, f, indent=2, ensure_ascii=False)
print(f"Modified {dashboard_file}")
else:
print(f"No changes needed for {dashboard_file}")
# Process all JSON files in the current directory
# define your label as below:
new_label = 'environment="$environment"'
for dashboard_file in glob.glob('*.json'):
add_environment_label(dashboard_file, new_label)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment