tech.guitarrapc.cóm

Technical updates

Terraform に startswith と endswith が来る

Terraformはその言語であるHCLがシンプルで分かりやすいのでとっつきやすい、と言われることがあります。 一方で、組み込み関数であれこれある割に、これがないの!? というのもあります。

そのなくてたびたび困るのが、startswithendswith関数です。

tl;dr;

  • startswithとendswithをビルトイン関数に入れるPRが先ほどマージされたので、Terraformのリリースにいつ入るか楽しみ (ETAは不明)
  • これでstartswith("hello world", "hello")endswith("hello world", "world")が書けるようになる

Terraform の組み込み関数

Terraformには組み込み関数がありますが、バージョンが積み重なっても関数が増えにくい印象です。

どんな関数があるかというのは、 Build-in Functionsを見るといいでしょう。

www.terraform.io

startswith や endswith は組み込み関数に存在しない

この中でString Functions = 文字列操作の関数を見ると、StartsWithEndsWithに相当する関数がないことに気づきます。 ないのでどうするかというと、regexsubstrtrimprefix/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年には立っていたのですが、そこそこスルーされていました。

github.com

別の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マージ

突然、startswithendswithは組み込み関数に足すのはありという方向に変わります。

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にマージされています。

github.com

これにより、次か近いバージョンでstartswithendswithが使えるようになりそうです。 ヤッター。

おまけ: カスタム関数という道

Issueで知ったんですが、プラグインでカスタム関数を入れるという提案が2015年から放置されていたりするんですね。 あったとしても、HCLではあんまり使いたくない気もしますがどうなんでしょう。

github.com


  1. 例を書いておいてなんですが、やっぱりひどい。