
Prometheusのクエリを書いていた時、共通するprefix / postfixを持つmetricsやjobを集計したくなり、ワイルドカードを使いたくなった。
Prometheusでワイルドカードを直接使う方法を見つけることができなかったため、正規表現を使うことで対応した。
まずはヒントを求めて公式ドキュメントを見てみる。
It is also possible to negatively match a label value, or to match label values against regular expressions. The following label matching operators exist:
=: Select labels that are exactly equal to the provided string.
!=: Select labels that are not equal to the provided string.
=~: Select labels that regex-match the provided string.
!~: Select labels that do not regex-match the provided string.Regex matches are fully anchored. A match of
env=~"foo"is treated asenv=~"^foo$".
チルダ記号を使えば正規表現が使えそう。
All regular expressions in Prometheus use RE2 syntax.
準拠する正規表現はRE2。
ワイルドカードを実現するために、任意の文字列を繰り返すような表現を探す。
| kinds of single-character expressions | examples | 
|---|---|
| any character, possibly including newline (s=true) | . | 
任意の1文字は . で良さそう。
| Repetitions | |
|---|---|
| x* | zero or more x, prefer more | 
| x+ | one or more x, prefer more | 
| x? | zero or one x, prefer one | 
繰り返し記号はいくつかあり、 * は0個以上、 + は1個以上、 ? は0個または1個を表す。
以上より .* や .+ を使えばワイルドカードとして使えそう。
ただし、* を使う時は空の文字列が帰ってこないよう注意する。
{job=~".*"} # Bad!
{job=~".+"} # Good!実際に使ってみる。
client01~10のjobの情報を一括で取得したければ
{job=~"client.*"}複数箇所の温度temp1,2,3,…を得たければ
{__name__=~"temp.*"}これで、Prometheusでワイルドカードを擬似的に使う準備が出来た。
Grafanaでダッシュボードを作りやすくなった。


コメント