Skip to content

Instantly share code, notes, and snippets.

@alileza
Last active August 29, 2023 16:55
Show Gist options
  • Save alileza/23d3a28a341d98b7775cabd14ac24fb3 to your computer and use it in GitHub Desktop.
Save alileza/23d3a28a341d98b7775cabd14ac24fb3 to your computer and use it in GitHub Desktop.
Add env on grafana dashboard for all prometheus query
import argparse
# Create an argument parser
parser = argparse.ArgumentParser(description="Modify JSON file by adding environment variable")
# Add arguments
parser.add_argument("input_file", help="Path to the input JSON file")
parser.add_argument("output_file", help="Path to the output JSON file")
# Parse the command-line arguments
args = parser.parse_args()
# The environment variable value
env_value = "$env"
# Open the input and output files
with open(args.input_file, "r") as input_f, open(args.output_file, "w") as output_f:
# Loop through the lines of the input file
for line in input_f:
if "expr" in line:
modified_line = line.replace("{", '{env="' + env_value + '", ')
output_f.write(modified_line)
else:
output_f.write(line)
print("Modified lines have been written to", args.output_file)
@7onn
Copy link

7onn commented Aug 25, 2023

I think this deserve a directive in a Makefile nearby the dashboards' code.

@iyrys
Copy link

iyrys commented Aug 29, 2023

Hey @alileza , this script is really helpful and I started to use it immediately :). I would like to propose one change to change count in replace method. Since our expressions can be multiline and can consists several queries in one expression we may need to replace multiple times. I just tested in several dashboards and it is working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment