MORE

BLOG

IaCツールでインフラ構築してみた①

  • IaC
  • Shopify
  • Tips
  • インフラ
  • ツール
  • 開発
25.03.25

1. はじめに

1.1 記事について

テックディレクションではプロジェクトマネジメント業務に加えて、SaaS型ECプラットフォームShopifyを中心にECストアの構築および標準機能では対応できない要件を満たすアプリケーション開発も行っております。

業務で得たアプリケーションの開発方法のノウハウを複数記事に分けて投稿しようと思います!「IaCでインフラ構築やってみた」シリーズではアプリケーションのインフラをIaC(Terraform、SAM、Serverless Frameworkなど)での構築手順を解説します。

本記事では、Terraformを用いてAWS VPCを構築する方法について記載しています。

1.2 記事の対象

  • アプリケーションエンジニアだがインフラに興味があるまたは構築をしなければならない方
  • ざっくりTerraformでのインフラ構築手順を知りたい方

この記事で触れないこと

・AWS各サービスの説明

・Terraform(利用する場合はtenvも)の文法

1.3 記事

この記事を読み終えるまでに、約15分です。

2. IaC とは?

Infrastructure as Codeの略で、クラウドリソースをコードで管理・構築する手法です。

本記事ではTerraformというIaCツールを用います。今回はAWSリソースを扱いますが、GCPやAzureなど他のクラウドリソースも対応可能です。マルチプラットフォーム嬉しいですね〜

開発会社HashiCorpの名前を取ってHCLという言語を使い、.tfファイルに定義内容を記述します。

3. 前提条件

・動作環境: MacBook Air Apple M3 Sequoia

・AWSアカウント作成済

・AWS IAMユーザー作成済

・作成したIAMユーザーのアクセスキー/シークレットキーを発行済かつPCに設定済

4. 環境構築

4-1. Terraform インストール

2つ方法を紹介します。

4-1-1. Homebrew でterraformをインストールする

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

# バージョン確認
$ terraform --version
Terraform v1.10.5

💡 2025/03/17時点で公式の方法を記載します。アップデートにより操作が変わる可能性あるので、公式の方法を参考にしてください

4-1-2. tenv を用いてインストールする(推奨)

tenvとは?

→Terraformのバージョン管理ツールです。複数案件でバージョンの異なるTerraformを使う場合バージョンを使い分けることができます。便利ですね〜

# tenv インストール
$ brew install tenv

# インストール可能バージョンの確認
$ tenv tf list-remote

# Terraform インストール
$ tenv tf install 1.10.5

# インストール済バージョンの確認
$ tenv tf list
1.10.5 (used 2025-03-17)

# バージョン切り替え
tenv tf use x.x.x

4-2. ソース作成

ディレクトリ構成

root
 ├─ modules
 │   ├─ variables.tf
 │   └─ vpc.tf
 ├─ main.tf
 ├─ terraform.tfvars
 └─ variables.tf

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  # S3 にバックアップファイルを作成する
  backend "s3" {
    bucket       = "test-tf-tfstate"
    key          = "test.tfstate"
    region       = "ap-northeast-1"
    use_lockfile = true
  }

  required_version = "1.10.5"
}

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

module "vpc" {
  source = "./vpc"

  app_name = var.app_name
  vpc_cidr = var.vpc_cidr
}

terraform.tfvars

region   = "ap-northeast-1"
app_name = "test"
vpc_cidr = "10.201.0.0/22"

variables.tf

variable "region" {}
variable "app_name" {}
variable "vpc_cidr" {}

modules/variables.tf

variable "app_name" {
  type = string
}

variable "vpc_cidr" {
  type = string
}

modules/vpc.tf

resource "aws_vpc" "vpc" {
  cidr_block = var.vpc_cidr

  tags = {
    Name = "${var.app_name}_vpc"
  }
}

4-3. S3パケット作成

backendに記載したバケット名「test-tf-tfstate」と同名のS3バケットを作成します。 💡 S3バケットを作成しようとしたときに「同じ名前のバケットが既に存在しています」エラーが出た!!! →S3は全AWSアカウントで共通です。誰かが同名バケットを既に作成していたらその名前は使えません。諦めて別の名前を使いましょう。(筆者も最初「test-app-tfstate」バケットを作ろうとしたところ上記のエラーが出ました。。。)

4-4. 環境変数を設定する

# AWS クレデンシャルを環境に設定する
export AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxx
export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxx

4-5. 作業ディレクトリで初期化コマンドを実行する

$ terraform init
Initializing the backend...

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing modules...
- vpc in vpc
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Installing hashicorp/aws v4.67.0...
- Installed hashicorp/aws v4.67.0 (signed by HashiCorp)

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.

このコマンドでは以下を実行します。

・backend構成

・構成で参照されているすべてのプロバイダーおよびモジュールのインストール

・バージョンロックファイルの作成

4-6. 確認コマンドを実行する

$ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
with the following symbols:
  + create

Terraform will perform the following actions:

  # module.vpc.aws_vpc.main will be created
  + resource "aws_vpc" "main" {
      + arn                                  = (known after apply)
      + cidr_block                           = "10.201.0.0/22"
      + default_network_acl_id               = (known after apply)
      + default_route_table_id               = (known after apply)
      + default_security_group_id            = (known after apply)
      + dhcp_options_id                      = (known after apply)
      + enable_classiclink                   = (known after apply)
      + enable_classiclink_dns_support       = (known after apply)
      + enable_dns_hostnames                 = (known after apply)
      + enable_dns_support                   = true
      + enable_network_address_usage_metrics = (known after apply)
      + id                                   = (known after apply)
      + instance_tenancy                     = "default"
      + ipv6_association_id                  = (known after apply)
      + ipv6_cidr_block                      = (known after apply)
      + ipv6_cidr_block_network_border_group = (known after apply)
      + main_route_table_id                  = (known after apply)
      + owner_id                             = (known after apply)
      + tags                                 = {
          + "Name" = "test_vpc"
        }
      + tags_all                             = {
          + "Name" = "test_vpc"
        }
    }

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

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions
if you run "terraform apply" now.

Terraformの記述内容から作成されるリソースと各種設定が表示されます。

4-7. リソース作成コマンドを実行する

$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
with the following symbols:
  + create

Terraform will perform the following actions:

  # module.vpc.aws_vpc.main will be created
  + resource "aws_vpc" "main" {
      + arn                                  = (known after apply)
      + cidr_block                           = "10.201.0.0/22"
      + default_network_acl_id               = (known after apply)
      + default_route_table_id               = (known after apply)
      + default_security_group_id            = (known after apply)
      + dhcp_options_id                      = (known after apply)
      + enable_classiclink                   = (known after apply)
      + enable_classiclink_dns_support       = (known after apply)
      + enable_dns_hostnames                 = (known after apply)
      + enable_dns_support                   = true
      + enable_network_address_usage_metrics = (known after apply)
      + id                                   = (known after apply)
      + instance_tenancy                     = "default"
      + ipv6_association_id                  = (known after apply)
      + ipv6_cidr_block                      = (known after apply)
      + ipv6_cidr_block_network_border_group = (known after apply)
      + main_route_table_id                  = (known after apply)
      + owner_id                             = (known after apply)
      + tags                                 = {
          + "Name" = "test_vpc"
        }
      + tags_all                             = {
          + "Name" = "test_vpc"
        }
    }

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

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:

上記で入力待機するので「yes」と入力する

  Enter a value: yes

module.vpc.aws_vpc.main: Creating...
module.vpc.aws_vpc.main: Creation complete after 1s [id=vpc-0625e06c95053e41f]

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

planで確認した内容の通り各リソースが作成され、合わせてS3にtfstateファイルが作成されます。

注意

・簡単にリソースが作成できる一方で、起動で料金が発生するサービス(EC2, NAT Gateway…など)の取り扱いには気をつけなければなりません。起動したはいいが停止するを忘れて想定外の料金が発生した…とならないように使わないときは停止するようにしましょう。コスト発生に懸念がある方は予めコスト試算を出すことをお勧めします。なお今回取り扱ったVPCのみであれば料金は発生しません。

・(手動の場合も一緒ですが)不要な権限を与えない、などセキュリティ設定をしっかり行いましょう。

まとめ

Terraformで簡単にインフラを構築できました。今回はVPCのみでしたが、実際に複数リソースを環境ごと(開発環境、検証環境、本番環境など)にインフラ構築する際にソースで管理していればコマンド数回実行で簡単に構築できます。

次回は実際にアプリケーション構築で使うようなインフラを構築します!

著者:なべちゃん

弊社では、ECサイトのリプレース案件から、Shopifyカスタムアプリ開発、保守案件に至るまで、EC中心にプロジェクトの質にこだわり、お客様に笑顔になってもらえるよう日々邁進しております。

皆様からのお問い合わせ・ご相談をお待ちしております。

お問い合わせはこちら