[小ネタ]でかいterraform plan結果をコピペしたい

2022.09.26

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

困っていたこと

terraform planコマンドの結果をSlackやGitHubのPR等に貼り付けたい時があります。

小さいplan結果だったらコンソール出力内容をコピペすれば良いです。が、巨大なplan結果の場合、コマンド実行完了時には最初の方のコンソール出力がもう見れなくなってしまっている場合があります。

というわけで、

% terraform plan > planresult.txt

などとやってみるのですが、

less planresult.txtの一部

ESC[1m  # module.base.aws_security_group_rule.ingress_from_albESC[0m will be createdESC[0mESC[0m
ESC[0m  ESC[32m+ESC[0mESC[0m resource "aws_security_group_rule" "ingress_from_alb" {
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0mdescriptionESC[0mESC[0m              = "inbound from ALB"
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0mfrom_portESC[0mESC[0m                = 8080
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0midESC[0mESC[0m                       = (known after apply)
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0mprotocolESC[0mESC[0m                 = "tcp"
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0msecurity_group_idESC[0mESC[0m        = "sg-09d9059a49bde6399
"
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0mselfESC[0mESC[0m                     = false
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0msource_security_group_idESC[0mESC[0m = "sg-055fee76b18dbcc99
"
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0mto_portESC[0mESC[0m                  = 8080
      ESC[32m+ESC[0m ESC[0mESC[1mESC[0mtypeESC[0mESC[0m                     = "ingress"
    }

こんな感じで要らない文字がたくさんついて非常に読みにくく実用に耐えません。

解決方法: no-colorオプションを使う

この「要らない文字」をうまく取り除く方法が無いかなーと模索していたのですが、ありました。terraform plan-no-colorオプションを追加します。

% terraform plan -no-color > nocolor-planresult.txt

すると、こういう出力になります。これですよ求めていたのは!「要らない文字」は色情報だったみたいですね。

less nocolor-planresult.txtの一部

  # module.base.aws_security_group_rule.ingress_from_alb will be created
  + resource "aws_security_group_rule" "ingress_from_alb" {
      + description              = "inbound from ALB"
      + from_port                = 8080
      + id                       = (known after apply)
      + protocol                 = "tcp"
      + security_group_id        = "sg-09d9059a49bde6399"
      + self                     = false
      + source_security_group_id = "sg-055fee76b18dbcc99"
      + to_port                  = 8080
      + type                     = "ingress"
    }

どこかに貼り付けたいだけなら

いちいち一度ファイル出力しなくてもこうした方が早いですね。

% terraform plan -no-color | pbcopy

私のPCはMacなのでpbcopyですが、Windowsだとclipというコマンドのようですね。