terraform fmtコマンドでtfファイルをフォーマットしてterraform validateで妥当か確認する
terraform fmt
terraform fmtコマンドを実行したカレントディレクトリの設定ファイルのみをフォーマットしてくれます。サブディレクトリも含めたい場合はterraform fmt -recursiveコマンドでフォーマット対象となります。
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
} ★
terraform fmtコマンドを実行します。修正したファイルがあればファイル名が標準出力されます。
$ terraform fmt main.tf
勝手にフォーマット修正してくれます。プロジェクトルートのtfファイルだけフォーマットするので、再帰的にフォーマットしたい場合は-recursiveをつけます。
$ terraform fmt -recursive
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
} ★修正されている
terraform validate
terraform validateコマンドで設定ファイルが妥当かどうか確認することができます。
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = ★ Name未指定
}
}
terraform validateコマンドを実行します。
$ terraform validate ╷ │ Error: Invalid expression │ │ on main.tf line 21, in resource "aws_instance" "app_server": │ 21: Name = │ 22: } │ │ Expected the start of an expression, but found an invalid expression token. ╵
妥当でない場合、エラーが出力されます。main.tfのNameを指定します。
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance" ★Name指定
}
}
terraform validateコマンドを実行します。
$ terraform validate Success! The configuration is valid.
成功メッセージが返ればOKです。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^

コメント