【初心者向け】 Terraform 完全解説
※まだ執筆中
この記事では「terraformでインフラ自動化したいけど、まじで何も分からん。なんならAWSから分からん」という方に向けて、ホンマの0からterraformの使い方を完全解説していきます。
【対象者】
・AWSを利用したインフラのコード化に興味がある
あと、AWS分からないけどTerraform使ってみたいって人にもオススメの記事です。
AWSに関しても0から解説しています。
【前提】
・mac環境
・AWS環境での具体例(GCPとかAzureはこの記事では扱いません)
・ガチの初心者向け(「そんぐらい分かるだろww」というところまで切り込むので熟練お断り)
terraform 環境構築
環境構築の方法を解説します。
terraform インストール
ターミナルで以下を実行する。
homebrew入ってない人はhomebrewをインストール。
tfenvを利用することで、terraformのバージョンを簡単に管理できる様になるので、それをインストールする。
※nvmとノリは同じ
handayuuta@handayuutanoMacBook-Air ~ % brew install tfenv
tfenvが入っているかチェック
handayuuta@handayuutanoMacBook-Air ~ % tfenv -v
tfenv 3.0.0
tfenvをインストールしたことを確認できたらterraformのバージョンをチェック。
handayuuta@handayuutanoMacBook-Air ~ % tfenv list-remote
1.13.0-alpha20250623
1.13.0-alpha20250604
1.13.0-alpha20250521
1.12.2
1.12.1
1.12.0
1.12.0-rc2
1.12.0-rc1
1.12.0-beta3
1.12.0-beta2
1.12.0-beta1
1.12.0-alpha20250319
1.12.0-alpha20250312
1.12.0-alpha20250213
1.11.4
1.11.3
1.11.2
1.11.1
1.11.0
インストールできるterraformのバージョンが出てくるので、最新の安定版を入れる。
安定版はalphaとかついていない無印の最新版
上記だったら、1.12.2が安定版の最新になる。
そしたら、そのバージョンをインストールする。
handayuuta@handayuutanoMacBook-Air ~ % tfenv install 1.12.2
Installing Terraform v1.12.2
Downloading release tarball from https://releases.hashicorp.com/terraform/1.12.2/terraform_1.12.2_darwin_arm64.zip
インストールしただけで使用する設定にはしていないので、デフォルトとしてインストールしたバージョンを使用するようにする。
handayuuta@handayuutanoMacBook-Air ~ % tfenv use 1.12.2
Switching default version to v1.12.2
Default version (when not overridden by .terraform-version or TFENV_TERRAFORM_VERSION) is now: 1.12.2
terraformを始める
tfsateファイルを管理できるようにする
tfstateファイルをリアルタイムに管理するためのs3バケットを作成
tfstateファイルはインフラ環境の状態を1ファイルで表現する神ファイル。
これはgitなどで管理するとリアルタイム性がなく、障害の原因になるので、AWSサービスを利用する場合はS3で管理することになる。
S3はクラウドストレージ。
利用するリージョンでs3バケットを作成する。
バケットタイプ -> 汎用
ACL無効
パブリックアクセスは全てブロック
バージョニングは無効(別になんでもいいが)
暗号化タイプ(Amazon S3 マネージドキーを使用したサーバー側の暗号化 (SSE-S3)
バケットキー有効にする
s3バケットに対して、tfstateファイルを反映するためにawscliをインストールする必要がある。
aws cliをインストール
handayuuta@handayuutanoMacBook-Air terraform % brew install awscli
==> Auto-updating Homebrew...
インストールされたことを確認
handayuuta@handayuutanoMacBook-Air terraform % aws --version
aws-cli/2.27.50 Python/3.13.5 Darwin/24.5.0 source/arm64
インストール後、自分の設定を以下コマンドにて確認する。
handayuuta@handayuutanoMacBook-Air terraform % aws configure list
Name Value Type Location
---- ----- ---- --------
profile <not set> None None
access_key <not set> None None
secret_key <not set> None None
region <not set> None None
何も設定されていないことが確認できるので、以下のコマンドで設定していく。
AWSアカウントにログインしたら、右上アカウントマークのある「セキュリティ認証情報」をクリックし、スクロールするとアクセスキーという項目があるので、それをそのまま利用する。
AWS Access Key ID は認証情報をそのまま利用。
AWS Secret Access Key も認証情報をそのまま利用。
Default region name は日本人なら基本的に ap-northeast-1。
Default output format はjsonとかファイル形式を指定する(僕は未入力にしました。特にこだわりがないので)
handayuuta@handayuutanoMacBook-Air terraform % aws configure
AWS Access Key ID [None]:
AWS Secret Access Key [None]:
Default region name [None]:
Default output format [None]:
実際に設定したら、再度設定されているか確認する。
handayuuta@handayuutanoMacBook-Air terraform % aws configure list
Name Value Type Location
---- ----- ---- --------
profile <not set> None None
access_key ******************** shared-credentials-file
secret_key ******************** shared-credentials-file
region ap-northeast-1 config-file ~/.aws/config
早速、tfファイルを書いていく
terraformを管理したいディレクトリに移動し、terraform.tfファイルを作成。
自分はアプリケーションが格納されているルートディレクトリの直下にterraformディレクトリを作成して、本番環境指定のディレクトリ内にtfファイルを作成しました。
handayuuta@handayuutanoMacBook-Air terraform % tree
.
├── env
│ └── prod
│ ├── backend.tf
│ ├── providers.tf
│ └── terraform.tf
└── README.md
terraform.tfファイル内にて、terraformのバージョンと利用するプロバイダのバージョンを書いていく。
ここの書き方は本当にバージョンによって違うので、注意してください。私は最新バージョンの安定版をどちらも利用しているので、最近terraformを使い始めた方は以下のバージョンを指定するのがいいと思います。
なお、絶対に固定のバージョンを使用するのを推奨します。バージョン〜以上みたいなバージョン指定の方法もありますが、基本的に不具合の温床になります。
// terraform自体の設定ファイル
terraform {
// terraformのバージョンを指定。最新かつ安定版を選んだ
required_version = "1.12.2"
// 利用するプロバイダーを明示する必要がある
required_providers {
aws = {
source = "hashicorp/aws"
version = "6.4.0"
}
}
}
次にbackend.tfファイルを作成します。
terraformでawsリソースを管理するときは、基本的にs3にtfstateファイルを格納することで、リモート上でリソースの状態を共有しておくもの。
今回はtfstateファイルをs3に格納するために、backend.tfファイルを作成する。
terraform {
// 参照するtfstateファイル
backend "s3" {
bucket = "shisha-navi-tfstate"
key = "terraform.state"
region = "ap-northeast-1"
}
}
次に利用するプロバイダーを指定する必要がある。
今回はawsなので、awsにする。
また、リージョン指定も複数指定しておく必要がある。
例えば、Cloudfrontで利用するACMなどはバージニア北部(us-east-1)でないといけなかったりする。
なので、今回は二か所を指定する。
// そのプロバイダーで管理する全リソースに適用する設定を指定
provider "aws" {
region = "ap-northeast-1"
// タグのデフォルトを指定する
default_tags {
tags = {
Terraform = "true"
STAGE = "dev"
MODULE = "shisha-navi-frontend"
}
}
}
provider "aws" {
alias = "us_east_1"
region = "ap-northeast-1"
default_tags {
tags = {
Terraform = "true"
STAGE = "dev"
MODULE = "sqs"
}
}
}
作成したので、terraform initでterraformを作る宣言をする。
handayuuta@handayuutanoMacBook-Air terraform % terraform init
Initializing the backend...
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Finding hashicorp/aws versions matching "6.4.0"...
- Installing hashicorp/aws v6.4.0...
- Installed hashicorp/aws v6.4.0 (signed by HashiCorp)
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.