append string to variable in a grafana query?

12,974

Solution 1

UPDATE 2020-08-17:

There is a new syntax for Grafana variables, new format is to use curly braces after dollar sign:

function{topic=~"${topic}_ERROR"}

Double brackets syntax is deprecated and will be deleted soon.

Also now you can define the format of the variable, which may help to solve some spacial characters issues. Example: ${topic:raw}

Docs: https://grafana.com/docs/grafana/latest/variables/syntax/


If you want to include text in the middle you need to use a different syntax:

function{topic=~"[[topic]]_ERROR"}

Note not only the double brackets but also the change from = to =~. It is documented on the link at the end of my comment, basically it says:

When the Multi-value or Include all value options are enabled, Grafana converts the labels from plain text to a regex compatible string. Which means you have to use =~ instead of =.

You can check the official explanation here: https://grafana.com/docs/grafana/latest/features/datasources/prometheus/#using-variables-in-queries

Solution 2

in the newer grafana you should add ${varname} and () regex

[[varname]] is nearly deprecated this will perform the multivalue variable in prometheus

func{instance=~"(${topic})_ERROR"}

its usualy used in instance metric

let say instance [198.10.99.9,198.10.99.10] if your collector is on 9100 node_memory_MemTotal_bytes{instance=~"(${instance}):9100"} if your collector is on another port example 9111 another_metric{instance=~"(${instance}):9111"}

Solution 3

Got an issue like this in the past.

1st exporter - custom one on my port 2nd node_exporter on 9100

in Grafana variable like:

host label_values(asterisk_active_calls, host)

In dashboard: CPU Busy

100 - (avg(irate(node_cpu_seconds_total{instance=~"$host:9100",mode="idle"}[30m])) * 100)

instance=~"$host:9100" - working like a charm

Share:
12,974

Related videos on Youtube

wizardzz
Author by

wizardzz

Updated on June 04, 2022

Comments

  • wizardzz
    wizardzz almost 2 years

    In Grafana I have a drop down for variable $topic with values "topic_A" "topic_B"

    "topic_A" is selected so $topic = "topic_A"

    I want to query prometheus using

    function{topic=$topic}
    

    and that works fine.

    How would I implement

    function{topic="$topic" + "_ERROR"}
    

    (this fails) where what I want to query would be "topic_A_ERROR" if "topic_A" is selected.

    How do I combine variable $topic and string "_ERROR" in the query?

  • wizardzz
    wizardzz over 4 years
    Thank you. That is exactly it. Definitely not the most straightforward way to do it (changing the syntax).
  • isopropylcyanide
    isopropylcyanide about 2 years
    The link to Grafana templating is broken. grafana.com/docs/grafana/latest/variables
  • Alberto Martin
    Alberto Martin about 2 years
    Thanks @isopropylcyanide for the heads up, I just updated the link