LoginSignup
3
2

More than 3 years have passed since last update.

TerraformのHCLファイルをフォーマットしたい

Last updated at Posted at 2020-08-04

はじめに

実践Terraform AWSにおけるシステム設計とベストプラクティス を少し進めているのですが、Terraformのコードを写経する中で「フォーマットをいちいち揃えるの面倒だな…何か良い方法あるだろう…」と思い調べたので。

要するに、半角スペースを連打している時の虚無感をなくしたい。

環境

Mac OS X 10.14.1 x86_64

$ terraform -version
Terraform v0.12.29
+ provider.aws v3.0.0

公式が用意しているのがあった…

あっさり見つかりました。
terraform fmt と打つだけ。
https://www.terraform.io/docs/commands/index.html

$ terraform
Usage: terraform [-version] [-help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    login              Obtain and save credentials for a remote host
    logout             Remove locally-stored credentials for a remote host
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    0.12upgrade        Rewrites pre-0.12 module source code for v0.12
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    push               Obsolete command for Terraform Enterprise legacy (v1)
    state              Advanced state management

使ってみる

フォーマットできていない状態。ちょっと汚くしてみました。

main.tf
data "aws_iam_policy_document" "allow_describe_regions" {
  statement {
    effect = "Allow"
    actions = ["ec2:DescribeRegions"]
 resources = ["*"]
}
}


resource "aws_iam_policy"   "example" {
  name = "takkii1010-policy"
  policy = data.aws_iam_policy_document.allow_describe_regions.json
}

terraform fmtを実行

$ terraform fmt
main.tf

結果

流石に無駄な改行までは直してくれなかったけど、綺麗になりました。

main.tf
data "aws_iam_policy_document" "allow_describe_regions" {
  statement {
    effect    = "Allow"
    actions   = ["ec2:DescribeRegions"]
    resources = ["*"]
  }
}


resource "aws_iam_policy" "example" {
  name   = "takkii1010-policy"
  policy = data.aws_iam_policy_document.allow_describe_regions.json
}

そのほかの方法

IntelliJ IDEAやAtomにもプラグインがあったので使ってみました。
ほかのエディタにも色々用意されているみたいなので、好みで選択すればOK。

IntelliJ IDEAの場合

HashiCorp Terraform / HCL language support というプラグイン。
https://plugins.jetbrains.com/plugin/7808-hashicorp-terraform--hcl-language-support/

Alt+Cmd+L でフォーマットしたら、あれ、想定とちょっと違う結果に…。

main.tf
data "aws_iam_policy_document" "allow_describe_regions" {
  statement {
    effect = "Allow"
    actions = [
      "ec2:DescribeRegions"]
    resources = [
      "*"]
  }
}


resource "aws_iam_policy" "example" {
  name = "takkii1010-policy"
  policy = data.aws_iam_policy_document.allow_describe_regions.json
}

Atom

ファイル保存時に自動でフォーマッタかけてくれるので便利。
https://atom.io/packages/terraform-fmt

このプラグインで実行しているのは terraform fmt なので、公式と同じ結果になりました。
保存時に実行してるので、すぐにフォーマットされた状態にはならないです。少し待つ必要があります。

main.tf
data "aws_iam_policy_document" "allow_describe_regions" {
  statement {
    effect    = "Allow"
    actions   = ["ec2:DescribeRegions"]
    resources = ["*"]
  }
}


resource "aws_iam_policy" "example" {
  name   = "takkii1010-policy"
  policy = data.aws_iam_policy_document.allow_describe_regions.json
}

写経中はAtomを使っているので、このプラグインで良さげ。

余談ですが、QiitaのシンタックスハイライトにTerraformのHCLは対応していないみたいですねー。

3
2
2

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
3
2