Terraformのインストールと最初のコード(Hello World)

1. 概要

この記事では、以下の内容を解説します。

  • macOS・Linux・WindowsへのTerraform CLIのインストール手順
  • インストール確認(terraform version
  • 最初の.tfファイルの書き方(Hello World)
  • terraform init / plan / apply / destroyの流れ
  • terraform consoleで関数を試す方法

2. Terraform CLIのインストール

macOS(Homebrew推奨)

# Homebrewのインストール(未インストールの場合)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Terraformのインストール
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# インストール確認
terraform version
# Terraform v1.9.x

Linux(apt / apt-getの場合)

# HashiCorpのGPGキーとリポジトリを追加
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list

# インストール
sudo apt-get update && sudo apt-get install terraform

# インストール確認
terraform version

Linux(yumの場合 / Amazon Linux・RHEL・CentOS)

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform

terraform version

Windows(winget推奨)

# Windows Package Manager (winget) を使う
winget install HashiCorp.Terraform

# または Chocolatey
choco install terraform

# インストール確認
terraform version

💡 バージョン管理ツール(tfenv): 複数のTerraformバージョンを使い分けたい場合は、tfenvの使用を検討してください。


3. 最初の.tfファイルを書く

ローカルファイルを作るだけの最小構成例

AWSの認証が不要なローカルプロバイダーで、まずTerraformの流れを体験します。

hello-terraform/
└── main.tf
# main.tf
terraform {
  required_version = ">= 1.9"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.0"
    }
  }
}

# ローカルにファイルを作成するリソース
resource "local_file" "hello" {
  content  = "Hello, Terraform!\n"
  filename = "${path.module}/hello.txt"
}

# 作成したファイルパスを出力
output "file_path" {
  value = local_file.hello.filename
}

4. 基本コマンドを実行する

terraform init — 初期化

cd hello-terraform/
terraform init

# 出力例
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/local versions matching "~> 2.0"...
- Installing hashicorp/local v2.5.1...
- Installed hashicorp/local v2.5.1 (signed by HashiCorp)

Terraform has been successfully initialized!

init.terraform/ディレクトリとプロバイダーのバイナリが作成されます。


terraform plan — 実行計画の確認

terraform plan

# 出力例
Terraform used the selected providers to generate the following execution plan.

  # local_file.hello will be created
+ resource "local_file" "hello" {
    + content              = "Hello, Terraform!\n"
    + filename             = "./hello.txt"
    + id                   = (known after apply)
  }

Plan: 1 to add, 0 to change, 0 to destroy.

+は「新規作成」を意味します。何も変更しないので安心して実行できます。


terraform apply — 実際に作成

terraform apply

# plan内容が表示される
Do you want to perform these actions?
  Enter a value: yes  ← "yes" と入力

# 出力例
local_file.hello: Creating...
local_file.hello: Creation complete after 0s

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:
file_path = "./hello.txt"

apply後、hello.txtが作成されていることを確認します。

cat hello.txt
# Hello, Terraform!

terraform destroy — 削除

terraform destroy

Do you really want to destroy all resources?
  Enter a value: yes

local_file.hello: Destroying...
local_file.hello: Destruction complete after 0s

Destroy complete! Resources: 1 destroyed.

destroyでTerraformが管理するリソースをすべて削除します。


5. AWSリソースで試す

AWSの認証設定が済んだら、EC2インスタンスを作成してみます。

# AWS CLIの設定(初回のみ)
aws configure
# AWS Access Key ID: <your-key>
# AWS Secret Access Key: <your-secret>
# Default region name: ap-northeast-1
# Default output format: json
# main.tf(AWSで最小構成)
terraform {
  required_version = ">= 1.9"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}

data "aws_ami" "amazon_linux_2023" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}

resource "aws_instance" "hello" {
  ami           = data.aws_ami.amazon_linux_2023.id
  instance_type = "t3.micro"

  tags = {
    Name      = "hello-terraform"
    ManagedBy = "terraform"
  }
}

output "instance_id" {
  value = aws_instance.hello.id
}
terraform init
terraform plan    # 作成内容を確認
terraform apply   # 実際にEC2を作成(費用が発生)
terraform destroy # 確認後は必ず削除

⚠️ 注意: EC2インスタンスは作成後から課金されます。確認が終わったら必ずterraform destroyで削除してください。


6. terraform console で関数を試す

terraform consoleはTerraformの式や関数をインタラクティブに試せるツールです。

terraform console

# プロンプトが表示される(Ctrl+C で終了)
> upper("hello")
"HELLO"

> length(["a", "b", "c"])
3

> toset(["dev", "stg", "prd", "dev"])  # 重複が消える
toset([
  "dev",
  "prd",
  "stg",
])

> { for s in ["web", "app"] : s => "${s}-server" }
{
  "app" = "app-server"
  "web" = "web-server"
}

7. 次のステップ

Terraformの基本操作が確認できたら、以下の記事で理解を深めましょう。


8. まとめ

  • macOSはbrew install hashicorp/tap/terraform、Linuxはaptまたはyum、WindowsはwingetでインストールできるL
  • terraform initplanapplydestroyが基本の流れ
  • planはAWSに何も変更しないので自由に実行できる
  • applyで実際のリソースが作成される(費用が発生する場合がある)
  • terraform consoleで関数や式をインタラクティブに試せる

動作確認バージョン: Terraform >= 1.9 公式ドキュメント: https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli