0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「AWSではじめるインフラ構築入門」第2版 で始める Terraform生活 その1

Last updated at Posted at 2025-09-30

この記事は自己学習の課程で実際に手を動かしながら自分の理解を深めていくだけの記事です。

学習環境

スクリーンショット 2025-09-29 22.02.41.png

AWS CLIやTerraformの環境構築は一通り完了している前提です。
課題図書はこちら。

課題図書自体は一般的なAWSコンソール(ブラウザ)でインフラ構築しているのですが、所属しているのプロジェクトがTerraformゴリゴリで勉強しなきゃなーと思っていた矢先だったので、せっかくならTerraformでやったれ!というのが今回の趣旨。無事完走できるかな?

今回は課題図書の「4.2 VPC」でVPCを実際にAWSで作って、削除するところまで。(書籍では削除は扱っていません)

とりあえず、ファイル構成。

drwxr-xr-x  10 genki  staff   320 Sep 30 19:46 .
drwxr-xr-x@ 11 genki  staff   352 Sep 29 21:30 ..
drwxr-xr-x  13 genki  staff   416 Sep 30 19:50 .git
-rw-r--r--@  1 genki  staff  1113 Sep 30 19:47 .gitignore
drwxr-xr-x@  3 genki  staff    96 Sep 29 21:52 .terraform
-rw-r--r--@  1 genki  staff  1377 Sep 29 21:52 .terraform.lock.hcl
-rw-r--r--   1 genki  staff    47 Sep 29 21:30 README.md
-rw-r--r--@  1 genki  staff   302 Sep 29 21:48 main.tf
-rw-r--r--@  1 genki  staff   181 Sep 29 21:57 terraform.tfstate
-rw-r--r--@  1 genki  staff  1820 Sep 29 21:57 terraform.tfstate.backup

まず、.gitignore。こちらは、まだTerraformに明るくないので、こちらのサイトから、Terraform用のものをそのまま頂きました。

.gitignore
# Created by https://www.toptal.com/developers/gitignore/api/terraform
# Edit at https://www.toptal.com/developers/gitignore?templates=terraform

### Terraform ###
# Local .terraform directories
**/.terraform/*

# .tfstate files
*.tfstate
*.tfstate.*

# Crash log files
crash.log
crash.*.log

# Exclude all .tfvars files, which are likely to contain sensitive data, such as
# password, private keys, and other secrets. These should not be part of version
# control as they are data points which are potentially sensitive and subject
# to change depending on the environment.
*.tfvars
*.tfvars.json

# Ignore override files as they are usually used to override resources locally and so
# are not checked in
override.tf
override.tf.json
*_override.tf
*_override.tf.json

# Include override files you do wish to add to version control using negated pattern
# !example_override.tf

# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan
# example: *tfplan*

# Ignore CLI configuration files
.terraformrc
terraform.rc

# End of https://www.toptal.com/developers/gitignore/api/terraform

次にmain.tf

main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_vpc" "sample_vpc" {
  cidr_block           = "10.0.0.0/16" // IPv4 CIDRブロック : 10.0.0.0/16
  instance_tenancy     = "default" // テナンシー:デフォルト

  assign_generated_ipv6_cidr_block = false // IPv6 CIDRブロック:使用しない

  tags = {
    Name = "sample-vpc" // 名前タグ
  }
}

providerセクションでAWSリソース(今回の場合はVPCのみ)を作るリージョンをap-northeast-1(東京)に指定しています。
resourceで課題図書4.2.2作成内容の記載内容にそってVPCの設定項目を設定しています。

main.tfができあがったら、

% terraform init
Initializing the backend...
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v6.14.1

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.

からの

% 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:

  # aws_vpc.sample_vpc will be created
  + resource "aws_vpc" "sample_vpc" {
      + arn                                  = (known after apply)
      + assign_generated_ipv6_cidr_block     = false
      + cidr_block                           = "10.0.0.0/16"
      + 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_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)
      + region                               = "ap-northeast-1"
      + tags                                 = {
          + "Name" = "sample-vpc"
        }
      + tags_all                             = {
          + "Name" = "sample-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.

で、最後にapplyでVPC作成します。

% 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:

  # aws_vpc.sample_vpc will be created
  + resource "aws_vpc" "sample_vpc" {
      + arn                                  = (known after apply)
      + assign_generated_ipv6_cidr_block     = false
      + cidr_block                           = "10.0.0.0/16"
      + 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_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)
      + region                               = "ap-northeast-1"
      + tags                                 = {
          + "Name" = "sample-vpc"
        }
      + tags_all                             = {
          + "Name" = "sample-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

aws_vpc.sample_vpc: Creating...
aws_vpc.sample_vpc: Creation complete after 2s [id=vpc-072f34af4c449aabd]

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

途中、Enter a valueでyesの入力を求められるので入力しましょう。AWSのコンソールでVPCを確認しにいくと

スクリーンショット 2025-09-30 20.21.40.png

確かにTerraformで設定したとおりのVPCが作成されています。課題図書に沿うならここまでですが、せっかくTerraformを使っているのでリソースの削除も行いましょう。

% terraform destroy
aws_vpc.sample_vpc: Refreshing state... [id=vpc-072f34af4c449aabd]

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_vpc.sample_vpc will be destroyed
  - resource "aws_vpc" "sample_vpc" {
      - arn                                  = "arn:aws:ec2:ap-northeast-1:466118398011:vpc/vpc-072f34af4c449aabd" -> null
      - assign_generated_ipv6_cidr_block     = false -> null
      - cidr_block                           = "10.0.0.0/16" -> null
      - default_network_acl_id               = "acl-02118be417f81687e" -> null
      - default_route_table_id               = "rtb-09d1434e08045fd4c" -> null
      - default_security_group_id            = "sg-09a8529079474e550" -> null
      - dhcp_options_id                      = "dopt-269ca341" -> null
      - enable_dns_hostnames                 = false -> null
      - enable_dns_support                   = true -> null
      - enable_network_address_usage_metrics = false -> null
      - id                                   = "vpc-072f34af4c449aabd" -> null
      - instance_tenancy                     = "default" -> null
      - ipv6_netmask_length                  = 0 -> null
      - main_route_table_id                  = "rtb-09d1434e08045fd4c" -> null
      - owner_id                             = "466118398011" -> null
      - region                               = "ap-northeast-1" -> null
      - tags                                 = {
          - "Name" = "sample-vpc"
        } -> null
      - tags_all                             = {
          - "Name" = "sample-vpc"
        } -> null
        # (4 unchanged attributes hidden)
    }

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

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

aws_vpc.sample_vpc: Destroying... [id=vpc-072f34af4c449aabd]
aws_vpc.sample_vpc: Destruction complete after 0s

Destroy complete! Resources: 1 destroyed.

terraform destroyの際もapplyの時と同様にyesの入力が求められます。

AWSのコンソールから確認氏に行くと該当VPCが削除されている事が分かります。

実は、今回Terraformでやってみようと思った理由がもう1つあります。課題図書にも記載がありますが、読み進めていくと、使っている(保持している)だけで課金が走るリソース(Elastic IP等)があります。これらを学習で使うときコンソールから作っては学習おわったので消して…とやっていたら途方もなく面倒くさいな、というのもあり、作成/削除の繰り返しに便利なTerraformにした…というのもあります。

次回は「4.3サブネットとアベイラビリティゾーン」の内容に沿ってマルチAZ環境でプライベートとパブリックなサブネットの作成をしてみようと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?