はじめに
後編では、Terraformファイルを作成し、EC2の作成、設定変更、削除を実施していきます。
Terraformの実行環境の構築については、前編をご覧ください。
前編はこちら:【前編】Terraform入門!EC2をコードで作ってみよう!
本記事では、ローカルのWSL(Ubuntu-26.04)からTerraformのコマンドを実行します。
また、作成済みのサブネットとセキュリティグループをEC2の作成時に指定します。
記事の構成
本記事は、前編と後編の2部構成となっています。
前編の内容
- Terraformとは?
- Terraformの環境構築
後編の内容
- Terraformファイルの作成
- EC2インスタンスの作成
- EC2インスタンスの設定変更
- EC2インスタンスの削除
構成図
Terraformを使用して、EC2を作成する際の構成図は以下の通りです。

手順
後編で実施する詳細な手順は以下の通りです。
- Terraformファイルの作成
- 作業ディレクトリの作成
- main.tfの作成
- variables.tfの作成
- terraform.tfvarsの作成
- outputs.tfの作成
- EC2インスタンスの作成
- IAMユーザーの認証情報を設定する
- terraform applyでEC2インスタンスを作成する
- EC2インスタンスの設定変更
- terraform.tfvarsの編集
- terraform applyで変更を反映する
- EC2インスタンスの削除
- ルートボリュームのEBSが削除されるか確認する
- terraform destroyでEC2インスタンスを削除する
Terraformファイル作成
Terraformのファイル構成は以下の通りです。
4つのTerraformファイルを用意し、Terraformのコマンドを実行してEC2を作成します。

作業ディレクトリの作成
- 任意の場所に作業ディレクトリを作成する
mkdir terraform-sample-project
- 作成した作業ディレクトリに移動する
cd terraform-sample-project
terraform-sample-projectディレクトリに4つのファイルを作成します。
また、全てのTerraformのコマンドは、terraform-sample-projectディレクトリで実行します。
main.tfの作成
main.tfは、AWSへの接続設定と作成するEC2インスタンスを定義する、構成の中心となるファイルです。
以下の内容でmain.tfを作成します。
「var.〇〇」と記述されている箇所は、変数を参照しています。
変数はvariables.tfで定義し、変数に入れる値はterraform.tfvarsで指定します。
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
required_version = ">= 1.2"
}
provider "aws" {
assume_role {
role_arn = var.assume_role_arn
session_name = "terraform-session"
}
region = var.aws_region
}
resource "aws_instance" "test_server" {
ami = var.ami_id
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = var.security_group_ids
tags = {
Name = "test_server",
TerraformDeploy = "true"
}
}terraformブロック
Terraformブロックで、どのバージョンのTerraformとAWSプロバイダーを使用するか定義します。
- aws:プロバイダーを定義します。今回はAWSに接続するため、awsを指定します
- source:プロバイダーの取得元を指定します
- version:使用可能なプロバイダーのバージョンを指定します
- required_version:使用できるTerraform CLIのバージョンを指定します
providerブロック
providerブロックでAWSへの接続設定を定義します。
provider "aws" {
assume_role {
role_arn = var.assume_role_arn
session_name = "terraform-session"
}
region = var.aws_region
}- provider “aws”:「provider プロバイダー名」で、どのプロバイダーの接続設定をするか定義します。今回は、AWSに接続するためawsを指定します
- assume_role:TerraformでAWSリソースを操作するときに使用するIAMロールを指定します
- role_arn:IAMロールのARNを指定します
- session_name:ロールを引き受けたときのセッション名を指定します。CloudTrailのログに記録されるため、 Terraformが実行した操作を判別しやすくなります
- region:作成するリージョンを指定します
resourceブロック
resourceブロックでEC2インスタンスを定義します。
resource "aws_instance" "test_server" {
ami = var.ami_id
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = var.security_group_ids
tags = {
Name = "test_server",
TerraformDeploy = "true"
}
}- resource “aws_instance” “test_server”:「resource “リソースタイプ” “リソース名”」で作成するリソースタイプとリソース名を指定します
- リソースタイプ(aws_instance):リソースタイプの前半部分(aws)はプロバイダー名に対応しており、後半部分(instance)はプロバイダーが定義したリソースタイプを指定します。プロバイダーが定義したリソースタイプは、Terraform公式のAWS Providerに記載されています
- リソース名(test_server):Terraformでリソースを識別するための名前で、任意の名前を指定できます。outputs.tfなどでaws_instance.test_server.idのように、リソースを参照するときに使用します。作成するEC2のインスタンス名(Nameタグ)とは別物なので注意してください
- パラメータ:変数(var.〇〇)を参照してEC2のAMI(ami)、インスタンスタイプ(instance_type)、サブネット(subnet_id)、セキュリティグループ(vpc_security_group_ids)を定義しています。指定できるパラメータは、Terraform公式のArgument Referenceに記載されています
- tags:EC2に付与するタグを定義します。TerraformDeployタグのようにTerraformで作成されたリソースだとタグで判別できるようにすることで、リソース管理がしやすくなります
variables.tfの作成
variables.tfは、Terraformで使用する変数を定義します。
以下の内容でvariables.tfを作成します。
※{AccountId}はIAMロールを作成したアカウントIDに置換すること
variable "assume_role_arn" {
description = "IAM role ARN to assume"
type = string
default = "arn:aws:iam::{AccountId}:role/TerraformDeployRole"
}
variable "aws_region" {
description = "AWS region to deploy resources"
type = string
default = "ap-northeast-1"
}
variable "ami_id" {
description = "AMI ID for the EC2 instance"
type = string
}
variable "instance_type" {
description = "EC2 instance type"
type = string
}
variable "subnet_id" {
description = "Subnet ID to launch the EC2 instance in"
type = string
}
variable "security_group_ids" {
description = "List of security group IDs to attach to the EC2 instance"
type = list(string)
}- variable “変数名”:「variable “変数名”」で変数名を定義します
- description:変数の説明を記述します
- type:変数の型を定義します。セキュリティグループ(security_group_ids)は、複数指定することを考慮してlist(string)のリスト形式を指定しています
- default:値がどこからも指定されなかったときに使用する値を定義します(今回はterraform.tfvarsで指定しなかった場合に使用されます)。今回は、assume_role_arnとaws_regionのみdefaultを定義しています
terraform.tfvarsの作成
terraform.tfvarsは、variables.tfで定義した変数の値を指定します。
以下の内容でterraform.tfvarsを作成します。
subnet_idとsecurity_group_idsは、既存リソースのリソースIDを指定します。
ami_id = "ami-xxxxxxxxxxxxxxxxx" instance_type = "t3.micro" subnet_id = "subnet-xxxxxxxxxxxxxxxxx" security_group_ids = ["sg-xxxxxxxxxxxxxxxxx"]
- ami_id:EC2に使用するAMIのIDを指定します
- instance_type:インスタンスタイプを指定します
- subnet_id:EC2を作成するサブネットを指定します
- security_group_ids:EC2にアタッチするセキュリティグループをリスト形式で指定します
outputs.tfの作成
outputs.tfは、作成後に確認したい値を出力するための設定を記述します。
リソースを作成するコマンド(terraform apply)実行時に、outputs.tfで指定した値がターミナルに表示されます。
output "instance_id" {
description = "ID of the EC2 instance"
value = aws_instance.test_server.id
}
output "instance_type" {
description = "Instance type of the EC2 instance"
value = aws_instance.test_server.instance_type
}
output "public_ip" {
description = "Public IP address of the EC2 instance"
value = aws_instance.test_server.public_ip
}
output "private_ip" {
description = "Private IP address of the EC2 instance"
value = aws_instance.test_server.private_ip
}
output "tags_all" {
description = "All tags assigned to the EC2 instance"
value = aws_instance.test_server.tags_all
}- output “出力名”:「output “出力名”」で出力する値の名前を定義します
- description:出力値の説明を記述します
- value:出力する値を指定します。「リソースタイプ.リソース名.属性名」の形式で、main.tfで作成したリソースの属性を参照します。参照できる属性は、Attribute Referenceに記載されています
EC2インスタンスを作成する
IAMユーザーの認証情報を設定する
今回、IAMユーザー(TerraformUser)の認証情報を使ってTerraformDeployRoleを引き受け(AssumeRole)、一時的な認証情報でEC2を作成します。
そのため、まずはIAMユーザー作成時に取得したアクセスキーをAWS CLIに設定します。
- 以下のコマンドを実行し、前編のIAMユーザー作成時にメモしたアクセスキーとシークレットアクセスキーを入力する
aws configure
AWS Access Key ID [None]: <アクセスキー> AWS Secret Access Key [None]: <シークレットアクセスキー> Default region name [None]: ap-northeast-1 Default output format [None]: json
続けて「Configure AWS skills and the AWS MCP server for your AI coding agent(s)?」と聞かれる場合があります。これはAIコーディングエージェント(Claude Code、Cursorなど)にAWS用のスキルやMCPサーバーを設定するかどうかの確認で、今回のハンズオンでは不要なため「n」を入力します。
- 認証情報が設定されたことを確認する
aws sts get-caller-identity
実行後、ArnにTerraformUserが表示されることを確認します。
{
"UserId": "XXXXXXXXXXXXXXXXXXXXX",
"Account": "{AccountId}",
"Arn": "arn:aws:iam::{AccountId}:user/TerraformUser"
}- TerraformDeployRoleを引き受けられることを確認する
aws sts assume-role \
--role-arn arn:aws:iam::{AccountId}:role/TerraformDeployRole \
--role-session-name test-session
実行後、Credentialsに一時的な認証情報(AccessKeyId、SecretAccessKey、SessionToken)が出力されれば、IAMユーザーからIAMロールを引き受ける準備は完了です。
terraform applyでEC2を作成する
- 読みやすさを確保するため、Terraformファイルに一貫した書式を設定する
実行すると、Terraformを使用して設定ファイルをフォーマットします。
変更したファイルがあればそのファイル名が出力されます。
terraform fmt
- 作業ディレクトリを初期化する
以下のコマンドで作業ディレクトリを初期化する必要があります。
初期化の一環として、main.tfで定義されたプロバイダーを現在のディレクトリにダウンロードしてインストールします。
terraform init
コマンド実行後、「Terraform has been successfully initialized!」と出力されたら成功です。
- 設定内容を検証する
terraform validate
実行後、「Success! The configuration is valid.」と出力されたら設定内容に問題なしです。
- EC2を作成する
terraform apply
コマンドを実行すると、作成するリソースの情報が出力され、実行してもよいか聞かれるのでyesを入力してEnterを押下します。
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
「Apply complete! Resources: 1 added, 0 changed, 0 destroyed.」と出力されていれば成功です。
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
instance_id = "i-xxxxxxxxxxxxxxxxx"
instance_type = "t3.micro"
private_ip = "xxxx.xxxx.xxxx.xxxx"
public_ip = ""
tags_all = tomap({
"Name" = "test_server"
"TerraformDeploy" = "true"
})Outputsにoutputs.tfで定義したEC2リソースの情報が出力されていることが確認できます。
今回はプライベートサブネットにEC2を作成したため、パブリックIPアドレスの情報が出力されていません。
パブリック IPv4 アドレスの自動割り当てを有効にすれば、public_ipに値が出力されます。
- EC2が作成されているか確認する
マネジメントコンソールのEC2のページで、作成されているか確認します。

terraform.tfvarsで指定したインスタンスタイプと、main.tfで定義したタグが付与されていることが確認できます。
EC2インスタンスの設定変更
作成したEC2のインスタンスタイプを変更します。
terraform.tfvarsの編集
- terraform.tfvarsのinstance_typeの値をt3.smallに変更する
ami_id = "ami-xxxxxxxxxxxxxxxxx" instance_type = "t3.small" subnet_id = "subnet-xxxxxxxxxxxxxxxxx" security_group_ids = ["sg-xxxxxxxxxxxxxxxxx"]
- 差分確認をする
terraform plan
実行すると、以下の出力がされます。
aws_instance.test_server: Refreshing state... [id=i-xxxxxxxxxxxxxxxxx]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
~ update in-place
Terraform will perform the following actions:
# aws_instance.test_server will be updated in-place
~ resource "aws_instance" "test_server" {
id = "i-xxxxxxxxxxxxxxxxx"
~ instance_type = "t3.micro" -> "t3.small"
tags = {
"Name" = "test_server"
"TerraformDeploy" = "true"
}
# (39 unchanged attributes hidden)
# (9 unchanged blocks hidden)
}
Plan: 0 to add, 1 to change, 0 to destroy.
Changes to Outputs:
~ instance_type = "t3.micro" -> "t3.small"terraform planの結果で見るポイントは以下の通りです。
- Plan: 0 to add, 1 to change, 0 to destroy.:「追加:0件・変更:1件・削除:0件」つまり、1つのリソースが変更されることを示しています
- Changes to Outputs:出力値(outputs.tfで定義した値)の変更内容です。今回は「~ instance_type = “t3.micro” -> “t3.small”」と表示されており、インスタンスタイプがt3.microからt3.smallに変わることがわかります
terraform applyで変更を反映する
- EC2の設定変更を実施する
EC2を作成したときと、同様のコマンドを実行します。
terraform apply
コマンドを実行すると、変更するリソースの情報が出力され、実行してもよいか聞かれるのでyesを入力してEnterを押下します。
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
「Apply complete! Resources: 0 added, 1 changed, 0 destroyed.」と出力されていれば成功です。
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
Outputs:
instance_id = "i-xxxxxxxxxxxxxxxxx"
instance_type = "t3.small"
private_ip = "xxxx.xxxx.xxxx.xxxx"
public_ip = ""
tags_all = tomap({
"Name" = "test_server"
"TerraformDeploy" = "true"
})Outputs:を確認すると、インスタンスタイプがt3.smallに変更になっていることがわかります。
- EC2のインスタンスタイプが変更されているか確認する
マネジメントコンソールのEC2のページで、インスタンスタイプが変更になっているか確認します。

インスタンスタイプがt3.microからt3.smallに変わっていることが、確認できます。
本来、インスタンスタイプを変更するにはEC2の停止・起動が必要ですが、Terraformでは自動で実行してくれます。
EC2インスタンスの削除
EC2を削除するときに注意したい点は、ルートボリュームのEBSが削除されるかどうかです。
EBSは未アタッチの状態でも料金が発生します。
EBSを引き続き使用する場合は残しておきますが、今回のような一時的な検証時には、コストを削減するためにEC2削除に併せて削除することが推奨されます。
そのため、ルートボリュームのEBSが削除されるか確認して、削除を実施します。
ルートボリュームのEBSが削除されるか確認する
- EC2削除時にルートボリュームのEBSが削除されるか確認する
以下のコマンドで、Terraformで作成したリソースの情報が記載されているstateファイルを確認し、EC2削除時にルートボリュームのEBSが削除されるか確認します。
terraform state show aws_instance.test_server | grep -A12 root_block_device
実行すると以下の出力がされます。
root_block_device {
delete_on_termination = true
device_name = "/dev/xvda"
encrypted = false
iops = 3000
kms_key_id = null
tags = {}
tags_all = {}
throughput = 125
volume_id = "vol-xxxxxxxxxxxxxxxxx"
volume_size = 8
volume_type = "gp3"
}delete_on_terminationがtrueになっているため、EC2を削除すると同時にルートボリュームのEBSも削除されます。
delete_on_terminationの値は、指定したAMIで定義されています。
EBSが削除されたか確認するために、volume_idの値をメモしておきます。
AMIの定義に左右されず、ルートボリュームのEBS削除をコードで指定することができます。
例えば、ルートボリュームの削除をしない場合は、main.tfのroot_block_deviceブロックでdelete_on_terminationをfalseにします。
resource "aws_instance" "test_server" {
ami = var.ami_id
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = var.security_group_ids
root_block_device {
delete_on_termination = false
}
tags = {
Name = "test_server",
TerraformDeploy = "true"
}
}terraform destroyでEC2インスタンスを削除する
- 削除されるリソースを確認する
terraform plan -destroy
実行すると、以下の出力がされます。
aws_instance.test_server: Refreshing state... [id=i-xxxxxxxxxxxxxxxxx]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_instance.test_server will be destroyed
- resource "aws_instance" "test_server" {
- ami = "ami-xxxxxxxxxxxxxxxxx" -> null
- arn = "arn:aws:ec2:ap-northeast-1:{AccountId}:instance/i-xxxxxxxxxxxxxxxxx" -> null
- associate_public_ip_address = false -> null
- availability_zone = "ap-northeast-1a" -> null
- disable_api_stop = false -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- force_destroy = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-xxxxxxxxxxxxxxxxx" -> null
- instance_initiated_shutdown_behavior = "stop" -> null
- instance_state = "running" -> null
- instance_type = "t3.small" -> null
- ipv6_address_count = 0 -> null
- ipv6_addresses = [] -> null
- monitoring = false -> null
- placement_partition_number = 0 -> null
- primary_network_interface_id = "eni-xxxxxxxxxxxxxxxxx" -> null
- private_dns = "ip-xxxx-xxxx-xxxx-xxxx.ap-northeast-1.compute.internal" -> null
- private_ip = "xxxx.xxxx.xxxx.xxxx" -> null
- region = "ap-northeast-1" -> null
- secondary_private_ips = [] -> null
- security_groups = [] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-xxxxxxxxxxxxxxxxx" -> null
- tags = {
- "Name" = "test_server"
- "TerraformDeploy" = "true"
} -> null
- tags_all = {
- "Name" = "test_server"
- "TerraformDeploy" = "true"
} -> null
- tenancy = "default" -> null
- user_data_replace_on_change = false -> null
- vpc_security_group_ids = [
- "sg-xxxxxxxxxxxxxxxxx",
] -> null
# (11 unchanged attributes hidden)
- capacity_reservation_specification {
- capacity_reservation_preference = "open" -> null
}
- cpu_options {
- core_count = 1 -> null
- threads_per_core = 2 -> null
# (2 unchanged attributes hidden)
}
- credit_specification {
- cpu_credits = "unlimited" -> null
}
- enclave_options {
- enabled = false -> null
}
- maintenance_options {
- auto_recovery = "default" -> null
}
- metadata_options {
- http_endpoint = "enabled" -> null
- http_protocol_ipv6 = "disabled" -> null
- http_put_response_hop_limit = 2 -> null
- http_tokens = "required" -> null
- instance_metadata_tags = "disabled" -> null
}
- primary_network_interface {
- delete_on_termination = true -> null
- network_interface_id = "eni-xxxxxxxxxxxxxxxxx" -> null
}
- private_dns_name_options {
- enable_resource_name_dns_a_record = false -> null
- enable_resource_name_dns_aaaa_record = false -> null
- hostname_type = "ip-name" -> null
}
- root_block_device {
- delete_on_termination = true -> null
- device_name = "/dev/xvda" -> null
- encrypted = false -> null
- iops = 3000 -> null
- tags = {} -> null
- tags_all = {} -> null
- throughput = 125 -> null
- volume_id = "vol-xxxxxxxxxxxxxxxxx" -> null
- volume_size = 8 -> null
- volume_type = "gp3" -> null
# (1 unchanged attribute hidden)
}
}
Plan: 0 to add, 0 to change, 1 to destroy.
Changes to Outputs:
- instance_id = "i-xxxxxxxxxxxxxxxxx" -> null
- instance_type = "t3.small" -> null
- private_ip = "xxxx.xxxx.xxxx.xxxx" -> null
- public_ip = "" -> null
- tags_all = {
- Name = "test_server"
- TerraformDeploy = "true"
} -> nullterraform plan -destroyの結果で見るポイントは以下の通りです。
- # aws_instance.test_server will be destroyed:削除されるリソースを示しています。今回はEC2インスタンス(test_server)が削除対象です
- – 属性 = 値 -> null:各設定値が削除されることを示しています。# (数字 unchanged attribute hidden)と表示される場合がありますが、変更のない属性が省略されているだけなので問題ありません
- Plan: 0 to add, 0 to change, 1 to destroy.:「追加:0件・変更:0件・削除:1件」、つまり1つのリソース(test_server)が削除されることを示しています
- EC2インスタンスを削除する
terraform destroy
コマンドを実行すると、削除するリソースの情報が出力され、実行してもよいか聞かれるのでyesを入力してEnterを押下します。
Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value:yes
実行後、「Destroy complete! Resources: 1 destroyed.」と出力されたら成功です。
- EC2が削除されたか確認する
マネジメントコンソールのEC2のページで、削除されているか確認します。
インスタンスの状態が終了済みになっており、削除されていることがわかります。

- ルートボリュームのEBSが削除されたか確認する
EC2ページのサイドメニューから「ボリューム」を選択し、ボリュームの一覧ページに移動します。
検索欄をクリックし、「ボリュームID=」を選択後、メモしたボリュームIDを検索欄に入力して確認します。
「一致するボリュームが見つかりません」と出力されたら、EC2インスタンスと同時にルートボリュームのEBSが削除できたことがわかります。

おわりに
本記事では、Terraformを使ってEC2インスタンスの作成、設定変更、削除をする方法を紹介しました。
実際に初めてTerraformを使って感じたメリットは以下の通りです。
- Terraformファイル(main.tf)と変数定義ファイル(variables.tf)を分けることで、作成するリソース情報が理解しやすく、変更もしやすい
- terraform.tfvarsの値を書き換えるだけで、同じコードから環境に合わせたリソースを作成できる
- terraform planで実行前に変更内容を確認でき、実行後も「Apply complete! Resources: 1 added, 0 changed, 0 destroyed.」のように追加・変更・削除の件数が表示されるため、何が起きたのかを把握しやすい
- インスタンスタイプ変更時など、必要な停止・起動を自動で実施してくれる
今後は、複数のリソースをModulesでまとめて再利用できるように管理することや、GitHub Actionsを使ったデプロイの自動化にも挑戦してみたいと考えています。
AWSの案件では、TerraformなどのIaCを使用してリソースを作成、管理することが増えています。
そのため、日々の学習でもマネジメントコンソールで直接設定せず、IaCでリソースを作成することを意識していきたいです。
本記事が、これからTerraformを始める方の参考になれば嬉しいです。
We Are Hiring!
Terraformファイル作成からEC2の作成・設定変更・削除までを体験して、IaCでリソースを作成・管理するスキルをさらに身につけたいと感じた方もいると思います。
こうしたスキルは、学び続けられる環境があることで着実に身につきます。
FindConsultingでは、入社後も継続的に学べる充実した研修制度を整えています。
座学・ハンズオン形式の技術研修から、研修の中でAWS最難関資格の取得支援まで、成長をしっかりバックアップする環境があります。
「技術を学び続けたい」「仕事を通じてスキルアップしたい」と感じているエンジニアの方、ぜひ一緒に成長しませんか?
現在、FindConsultingでは学ぶ意欲のある仲間を募集しています。
まずはカジュアル面談からでも、ぜひお気軽にお声がけください。


