LoginSignup
13
13

More than 3 years have passed since last update.

Consul Template チートシート

Last updated at Posted at 2016-05-13

Consul Template のドキュメントと Go Template のドキュメントの両方を往復するのに疲れたのでまとめました。

対応バージョン: 0.21.0

用語の整理

用語 内容
ドット (dot) テンプレート実行中に特定のデータを指し示すカーソル。記法 . で参照できる。
アクション (action) 制御構造のこと
引数 (argument) 単純な値のこと
コマンド (command) 引数 or 関数 or メソッド
パイプライン (pipeline) 複数のコマンドを | で連結したもの。パイプで受け取った値は関数やメソッドの引数の末尾に追加される。
空の値 (empty) false0nilポインタまたはインタフェース値、長さがゼロの配列、スライス、マップ、文字列

アクション

内容 記述例 備考
コメント {{/* 任意のコメント */}} 複数行可
値の出力 {{パイプライン}}
if {{if パイプライン}} T1 {{end}}
else {{if パイプライン}} T1 {{else}} T0 {{end}}
else if {{if パイプライン}} T1 {{else if パイプライン}} T0 {{end}}
ループ {{range パイプライン}} T1 {{end}}
ループ {{range パイプライン}} T1 {{else}} T0 {{end}} パイプラインが空なら T0
テンプレート定義 {{define "名前"}} T1 {{end}} Nested template definitions
テンプレート実行 {{template "名前"}} ドットが nil にセットされる
テンプレート実行 {{template "名前" パイプライン}} ドットがパイプラインの値にセットされる
テンプレート定義+実行 {{block "名前" パイプライン}} T1 {{end}} 以下の記述と同等:
{{define "名前"}} T1 {{end}}
{{template "名前" .}}
ドット設定 {{with パイプライン}} T1 {{end}} パイプラインが空なら何もしない
ドット設定 {{with パイプライン}} T1 {{else}} T0 {{end}} パイプラインが空なら T0
変数の初期化 $variable := パイプライン 任意のアクション内のパイプラインで使用可
range 内の変数の初期化 {{range $index, $element := パイプライン}}

パイプライン

内容 定義 記述例
パイプライン :black_small_square: コマンド
:black_small_square: コマンド | コマンド
{{"\"output\""}}
{{"output" | printf "%q"}}
コマンド :black_small_square: 引数
:black_small_square: .メソッド名 [引数...]
:black_small_square: 関数名 [引数...]
"foo"
.Method
.Method "foo" "bar" "baz"
functionName
functionName "foo" "bar" "baz"

引数

内容 記述例 備考
true, false, "abc", 'a', '\t', 42, 0600, 0xBadFace, 72.40, 6.67428e-11, 6.67428e-11i Goの文法における真偽値、文字列、文字、数値、浮動小数点数、虚数、複素数の定数
nil nil
ドット .
変数 $piOver2, $ ドルマークに続く英数字の文字列(なくてもよい)
フィールド .Field, .Field1.Field2, .$x.Field1.Field2
マップのキー .Key, .Field1.Key1.Field2.Key2, $x.key1.key2 キーは英数字(小文字始まりでも可)
引数なしのメソッド .Method, .Field1.Key1.Method1.Field2.Key2.Method2, $x.Method1.Field
引数なしの関数 fun
グループ (コマンド)
print (.F1 arg1) (.F2 arg2), (.StructValuedMethod "arg").Field

関数

標準関数

関数名 内容 記述例 備考
and 論理積 and x y xが真のときy、そうでなければx
call 最初の引数の関数に残りの引数をパラメータとして与えて実行した結果 .X.Y 1 2 Goで書くと dot.X.Y(1, 2)
html HTML のエスケープ html "foo & bar"
index 最初の引数を続く引数でインデックスした結果 index x 1 2 3 Goの文法では x[1][2][3]
js JavaScript のエスケープ
len 引数の長さ
not 論理否定値
or 論理和 or x y xが真のときx、そうでなければy
print fmt.Sprint
printf fmt.Sprintf
println fmt.Sprintln
urlquery URLエンコード
eq == eq 1 2
ne != ne 1 2
lt < lt 1 2
le <= le 1 2
gt > gt 1 2
ge >= ge 1 2

Consul Template 関数

API Functions

関数名 内容 記述例 備考
datacenters データセンターリストを返す {{datacenters}}
file ローカルファイルを読み込んで返す {{file "/path/to/local/file"}}
key KV の値を返す {{key "service/redis/maxconns@east-aws"}}
{{key "service/redis/maxconns"}}
keyExists KV のキーがあるかどうか返す {{ if keyExists "app/beta_active" }}
# ...
{{ else }}
# ...<br>{{ end }}
keyOrDefault Consul の KV の値を返す。キーがなければデフォルト値を返す {{keyOrDefault "service/redis/maxconns@east-aws" "5"}}
ls key-value ペアを返す {{range ls "service/redis@east-aws"}}{{.Key}} {{.Value}}{{end}}
node 単一ノードの値を返す {{node "node1"}}
{{node}}
{{node "node1" "@east-aws"}}
ノード名を省略すると自分自身のノード
nodes 全ノードのリストを返す {{nodes}}
{{nodes "@east-aws"}}
secret Vaultの値(単一)を返す {{with secret "secret/passwords"}}
{{.Data.password}}{{end}}
secrets Vaultの値(複数)を返す {{range secrets "secret/"}}
{{.}}{{end}}
service サービスのリストを返す {{service "release.web@east-aws"}}
`{{service "web
any"}}<br>{{service "web
services 全サービスのリストを返す {{services}}
{{services "@east-aws"}}
tree KV のツリーを返す {{range tree "service/redis@east-aws"}}
{{.Key}} {{.Value}}{{end}}
ネストしたキーは / で区切られる

Scratch

テンプレート内で使えるテンポラリな Key-Value ストア。

関数名 内容 記述例 備考
scratch.Key キーの有無を返す {{ scratch.Key "foo" }}
scratch.Get 値を返す {{ scratch.Get "foo" }}
scratch.Set 値を設定 (上書きあり) {{ scratch.Set "foo" "bar" }}
scratch.SetX 値を設定 (上書きなし) {{ scratch.SetX "foo" "bar" }}
scratch.MapSet マップに値を設定 (上書きあり) {{ scratch.MapSet "vars" "foo" "bar" }}
scratch.MapSetX マップに値を設定 (上書きなし) {{ scratch.MapSetX "vars" "foo" "bar" }}
scratch.MapValues マップの値をリストで返す {{ scratch.MapValues "vars" }}

Helper Functions

関数名 内容 記述例 備考
base64Decode BASE64 デコード {{ base64Decode "aGVsbG8=" }}
base64Encode BASE64 エンコード {{ base64Encode "hello" }}
base64URLDecode BASE64 デコード (URL セーフ) {{ base64URLDecode "aGVsbG8=" }}
base64URLEncode BASE64 エンコード (URL セーフ) {{ base64Encode "hello" }}
byKey tree 関数の返した値を第1階層のキーでグループ化 {{range $key, $pairs := tree "groups" | byKey}}
{{$key}}:
{{range $pair := $pairs}} {{.Key}}={{.Value}}
{{end}}{{end}}
byTag service, services 関数の返した値をタグでグループ化 {{range $tag, $services := service "web" | byTag}}{{$tag}}
{{range $services}} server {{.Name}} {{.Address}}:{{.Port}}
{{end}}{{end}}
contains リストが引数に指定した値を含むかどうか {{ if .Tags | contains "production" }}
# ...
{{ end }}
containsAll リストが引数に指定したリストをすべて含むかどうか {{ if containsAll $requiredTags .Tags }}
# ...
{{ end }}
containsAny リストが引数に指定したリストを一つでも含むかどうか {{ if containsAny $acceptableTags .Tags }}
# ...
{{ end }}
containsNone リストが引数に指定したリストを全く含まないかどうか {{ if containsNone $forbiddenTags .Tags }}
# ...
{{ end }}
env 環境変数を返す {{env "CLUSTER_ID"}}
executeTemplate 定義したテンプレートを実行 {{ define "custom" }}my custom template{{ end }}

This is my other template:
{{ executeTemplate "custom" }}

And I can call it multiple times:
{{ executeTemplate "custom" }}

Even with a new context:
{{ executeTemplate "custom" 42 }}

Or save it to a variable:
{{ $var := executeTemplate "custom" }}
explode tree, ls 関数の返した値をネストしたマップに変換する {{ tree "config" | explode }}
in 値が引数に指定したリストに含まれるかどうか {{ if in .Tags "production" }}
# ...
{{ end }}
contains 関数と引数の順番が逆
indent インデント {{ tree "foo" explode
loop 指定回数繰り返す {{range loop 5}}
# Comment{{end}}

{{range $i := loop 5 8}}
stanza-{{$i}}{{end}}
loop a b だと a から b - 1 まで繰り返す
join 文字列リストを連結 {{$items | join ","}}
trimSpace 空白を削除 {{ file "/etc/ec2_version"| trimSpace }}
parseBool 文字列を boolean に変換 {{if key "feature/enabled" | parseBool}}{{end}}
parseFloat 文字列を float64 に変換 {{"1.2" | parseFloat}}
parseInt 文字列を int64 に変換 {{range $i := loop key "config/pool_size" | parseInt}}
# ...{{end}}
parseJSON JSON をパース {{with $d := key "user/info" | parseJSON}}{{$d.name}}{{end}}
parseUint 文字列を uint64 に変換 {{"1" | parseUint}}
plugin Consul Template plugin を実行 {{tree "foo" | explode | toJSON | plugin "my-plugin"}} プラグインは外部コマンドとして実装できる
regexMatch 正規表現マッチ {{"foo.bar" | regexMatch "foo([.a-z]+)"}}
regexReplaceAll 正規表現で置換 {{"foo.bar" | regexReplaceAll "foo([.a-z]+)" "$1"}}
replaceAll 文字列置換 {{"foo.bar" | replaceAll "." "_"}}
split 文字列を分割 {{"foo\nbar\n" | split "\n"}}
timestamp タイムスタンプを RFC3339 形式 (1970-01-01T00:00:00Z) の文字列で返す {{timestamp}}
{{timestamp "2006-01-02"}}
{{timestamp "unix"}}
引数を指定すると、time.Format()のフォーマットで返す。unix とすると UNIX Timestamp (ただし文字列) で返す。
toJSON tree, ls 関数の返した値を JSON 形式の文字列に変換 {{ tree "config" | explode | toJSON }}
toJSONPretty tree, ls 関数の返した値をインデントされた JSON 形式の文字列に変換 {{ tree "config" | explode | toJSONPretty }}
toLower 小文字に変換 {{key "user/name" | toLower}}
toTitle Titlecase に変換 {{key "user/name" | toTitle}}
toTOML tree, ls 関数の返した値を TOML 形式の文字列に変換 {{ tree "config" explode
toUpper 大文字に変換 {{key "user/name" | toUpper}}
toYAML tree, ls 関数の返した値を YAML 形式の文字列に変換 {{ tree "config" | explode | toYAML }}

Math Functions

関数名 内容 記述例 備考
add 足し算 {{ add 1 2 }} → 3
{{ 1 | add 2 }} → 3
subtract 引き算 {{ subtract 2 5 }} → 3
{{ 5 | subtract 2 }} → 3
引数の順番に注意
multiply 掛け算 {{ multiply 2 2 }} → 4
{{ 2 | multiply 2 }} → 4
divide 割り算 {{ divide 2 10 }} → 5
{{ 10 | divide 2 }} → 5
引数の順番に注意
modulo 剰余 {{ modulo 2 5 }} → 1
{{ 5 | modulo 2 }}→ 1
引数の順番に注意

空白の制御

Go 1.6 / Consul Template 0.13.0 以降で利用可能。

  • {{ の代わりに {{- を使うと直前の連続する空白が削除される
  • }} の代わりに -}} を使うと直後の連続する空白が削除される
  • 削除される空白は space, horizontal tab, carriage return, and newline
  • {{-, -}} とテンプレート記述本体の間はスペースで区切る必要がある
記述例 出力
{{23 -}} < {{- 45}} 23<45

参照

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13