Terraformはその言語であるHCLがシンプルで分かりやすいのでとっつきやすい、と言われることがあります。 一方で、組み込み関数であれこれある割に、これがないの!? というのもあります。
そのなくてたびたび困るのが、startswith
とendswith
関数です。
tl;dr;
- startswithとendswithをビルトイン関数に入れるPRが先ほどマージされたので、Terraformのリリースにいつ入るか楽しみ (ETAは不明)
- これで
startswith("hello world", "hello")
やendswith("hello world", "world")
が書けるようになる
Terraform の組み込み関数
Terraformには組み込み関数がありますが、バージョンが積み重なっても関数が増えにくい印象です。
どんな関数があるかというのは、 Build-in Functionsを見るといいでしょう。
startswith や endswith は組み込み関数に存在しない
この中でString Functions = 文字列操作の関数を見ると、StartsWith
やEndsWith
に相当する関数がないことに気づきます。
ないのでどうするかというと、regex
やsubstr
やtrimprefix
/trimsuffix
あたりでやられることが多いでしょう。1
# regex での startswith 代わり can(regex("^vpc-", var.vpc-id)) # substr での startswith 代わり substr(var.domain2, 0, length(var.domain1) + 1) == "${var.domain1}." # trimprefix での startswith 代わり trimprefix(var.domain2, var.domain1) != var.domain2
これでもいいという意見もありそうですが、さすがにstartswith
で済むものを流し読みしにくい感じで書かれてもうれしくないものです。
# startswith があればこれでいい startswith(var.vpc-id, "vpc-") startswith(var.domain2, var.domain1)
ということでIssueが2021年には立っていたのですが、そこそこスルーされていました。
別のIssueですが、開発チームとしては従来のやり方でできるなら足したくないという意向があるようです。
startswith
でもそれが適用されるのは、あんまりな気もしますがそういう方針なのでしょう。この方針ならとあきらめてました。
We're being pretty cautious about adding new functions that overlap with existing use-cases because Terraform has grown quite an unwieldy collection of builtins over the years, and so we've been considering various ways to allow for externally-defined functions (e.g. #2771) to avoid continuing to grow that set. https://github.com/hashicorp/terraform/issues/28855#issuecomment-856345294
組み込み関数として入れる意向とPRマージ
突然、startswith
とendswith
は組み込み関数に足すのはありという方向に変わります。
I took your comments back to the team, and we revisited this particular decision. We do not need to wait for a function provider framework for these functions. In this case, startswith and endswith meet a sufficiently wide use case need to be considered for built-in functions. https://github.com/hashicorp/terraform/issues/28209#issuecomment-1123022185より引用
ということでPRが提案され、2022/July/15にマージされています。
これにより、次か近いバージョンでstartswith
、endswith
が使えるようになりそうです。
ヤッター。
おまけ: カスタム関数という道
Issueで知ったんですが、プラグインでカスタム関数を入れるという提案が2015年から放置されていたりするんですね。 あったとしても、HCLではあんまり使いたくない気もしますがどうなんでしょう。
- 例を書いておいてなんですが、やっぱりひどい。↩