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?

More than 1 year has passed since last update.

Terraform 入門から精通まで(初期設定)

Last updated at Posted at 2022-07-06

概要

今回は、Infrastructure as Codeの代表的なツールであるTerraformについて、まだ触れたことがない方向けに特徴と使い方を簡単に説明したいと思います。
Terraformでawsのリソースを構築、編集、削除などを実行させていただきます。

前提条件

・MAC
・VS code
・リソースを作成するためのAWSの権限設定をもつiamユーザーのアクセスキー

ローカル環境

% sw_vers  
ProductName:	macOS
ProductVersion:	12.4
BuildVersion:	21F79

Terraformをインストール

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Terraformの状況確認

% terraform -version
Terraform v1.2.4
on darwin_arm64

terraform doc

今回、以下のリンクを参照しました。

TerraformでEc2を起動するため、コードを準備

vscodeでmain.tfファイルを作成します。
main.tfに以下のコードを記入します。

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

# Configure the AWS Provider
provider "aws" {
  region = "ap-northeast-1"
  access_key = "xxxxxxxxxxx"
  secret_key = "xxxxxxxxxxxxx"

}
resource "aws_instance" "my-first-terraform-ec2" {
  ami           = "ami-0b7546e839d7ace12"
  instance_type = "t2.micro"

  tags = {
    Name = "my-first-terraform-ec2"
  }
}

terraform初期化

Terraformの実行に必要なプラグインをインターネットから取得します。

% terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.0"...
- Installing hashicorp/aws v3.75.2...
- Installed hashicorp/aws v3.75.2 (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.

定義内容のチェック

terraform planコマンドが定義内容をプレビューできます。

% 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_instance.my-first-terraform-ec2 will be created
  + resource "aws_instance" "my-first-terraform-ec2" {
      + ami                                  = "ami-0b7546e839d7ace12"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t2.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + subnet_id                            = (known after apply)
      + tags                                 = {
          + "Name" = "my-first-terraform-ec2"
        }
      + tags_all                             = {
          + "Name" = "my-first-terraform-ec2"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + vpc_security_group_ids               = (known after apply)

      + capacity_reservation_specification {
          + capacity_reservation_preference = (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id = (known after apply)
            }
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
          + instance_metadata_tags      = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

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

EC2を起動

terraform applyコマンドが定義を適用します。

 % 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_instance.my-first-terraform-ec2 will be created
  + resource "aws_instance" "my-first-terraform-ec2" {
      + ami                                  = "ami-0b7546e839d7ace12"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t2.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + subnet_id                            = (known after apply)
      + tags                                 = {
          + "Name" = "HelloWorld"
        }
      + tags_all                             = {
          + "Name" = "HelloWorld"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + vpc_security_group_ids               = (known after apply)

      + capacity_reservation_specification {
          + capacity_reservation_preference = (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id = (known after apply)
            }
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
          + instance_metadata_tags      = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

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_instance.my-first-terraform-ec2: Creating...
aws_instance.my-first-terraform-ec2: Still creating... [10s elapsed]
aws_instance.my-first-terraform-ec2: Still creating... [20s elapsed]
aws_instance.my-first-terraform-ec2: Still creating... [30s elapsed]
aws_instance.my-first-terraform-ec2: Creation complete after 33s [id=i-054b5babd53a5a942]

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

ec2起動状況確認

aws コンソール画面にログインして、ec2状況を確認します。

截屏2022-07-06 12.00.26.png

ec2が起動してることを確認できました。

terraformでリソースを変更

先ほど、起動したEC2のtag内容を変更します
my-first-terraform-ec2

modify-first-terraform-ec2-tags-name
main.tfファイルにec2のtags名前を変更します

resource "aws_instance" "my-first-terraform-ec2" {
  ami           = "ami-0b7546e839d7ace12"
  instance_type = "t2.micro"

  tags = {
    Name = "modify-first-terraform-ec2-tags-name"
  }
}

変更内容を確認

% terraform plan 
aws_instance.my-first-terraform-ec2: Refreshing state... [id=i-0041e996aac4e5b4b]

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.my-first-terraform-ec2 will be updated in-place
  ~ resource "aws_instance" "my-first-terraform-ec2" {
        id                                   = "i-0041e996aac4e5b4b"
      ~ tags                                 = {
          ~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
        }
      ~ tags_all                             = {
          ~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
        }
        # (27 unchanged attributes hidden)





        # (5 unchanged blocks hidden)
    }

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

##変更内容を実行

% terraform apply
aws_instance.my-first-terraform-ec2: Refreshing state... [id=i-0041e996aac4e5b4b]

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.my-first-terraform-ec2 will be updated in-place
  ~ resource "aws_instance" "my-first-terraform-ec2" {
        id                                   = "i-0041e996aac4e5b4b"
      ~ tags                                 = {
          ~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
        }
      ~ tags_all                             = {
          ~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
        }
        # (27 unchanged attributes hidden)





        # (5 unchanged blocks hidden)
    }

Plan: 0 to add, 1 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_instance.my-first-terraform-ec2: Modifying... [id=i-0041e996aac4e5b4b]
aws_instance.my-first-terraform-ec2: Modifications complete after 1s [id=i-0041e996aac4e5b4b]

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

変更結果を確認

截屏2022-07-06 12.09.11.png

ec2のtag名前はmodify-first-terraform-ec2-tags-nameに変更しました。

terraformでリソースを削除

terraform destroyコマンドでmain.tfファイルで起動したec2を削除します。

% terraform destroy
aws_instance.my-first-terraform-ec2: Refreshing state... [id=i-0041e996aac4e5b4b]

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.my-first-terraform-ec2 will be destroyed
  - resource "aws_instance" "my-first-terraform-ec2" {
      - ami                                  = "ami-0b7546e839d7ace12" -> null
      - arn                                  = "arn:aws:ec2:ap-northeast-1:694047010837:instance/i-0041e996aac4e5b4b" -> null
      - associate_public_ip_address          = true -> null
      - availability_zone                    = "ap-northeast-1c" -> null
      - cpu_core_count                       = 1 -> null
      - cpu_threads_per_core                 = 1 -> null
      - disable_api_termination              = false -> null
      - ebs_optimized                        = false -> null
      - get_password_data                    = false -> null
      - hibernation                          = false -> null
      - id                                   = "i-0041e996aac4e5b4b" -> null
      - instance_initiated_shutdown_behavior = "stop" -> null
      - instance_state                       = "running" -> null
      - instance_type                        = "t2.micro" -> null
      - ipv6_address_count                   = 0 -> null
      - ipv6_addresses                       = [] -> null
      - monitoring                           = false -> null
      - primary_network_interface_id         = "eni-05060a5c79730093c" -> null
      - private_dns                          = "ip-172-31-2-192.ap-northeast-1.compute.internal" -> null
      - private_ip                           = "172.31.2.192" -> null
      - public_dns                           = "ec2-54-95-7-235.ap-northeast-1.compute.amazonaws.com" -> null
      - public_ip                            = "54.95.7.235" -> null
      - secondary_private_ips                = [] -> null
      - security_groups                      = [
          - "default",
        ] -> null
      - source_dest_check                    = true -> null
      - subnet_id                            = "subnet-78a35122" -> null
      - tags                                 = {
          - "Name" = "modify-first-terraform-ec2-tags-name"
        } -> null
      - tags_all                             = {
          - "Name" = "modify-first-terraform-ec2-tags-name"
        } -> null
      - tenancy                              = "default" -> null
      - vpc_security_group_ids               = [
          - "sg-33dac977",
        ] -> null

      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> null
        }

      - credit_specification {
          - cpu_credits = "standard" -> null
        }

      - enclave_options {
          - enabled = false -> null
        }

      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_put_response_hop_limit = 1 -> null
          - http_tokens                 = "optional" -> null
          - instance_metadata_tags      = "disabled" -> null
        }

      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/xvda" -> null
          - encrypted             = false -> null
          - iops                  = 100 -> null
          - tags                  = {} -> null
          - throughput            = 0 -> null
          - volume_id             = "vol-0a35c335542aefab0" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp2" -> null
        }
    }

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_instance.my-first-terraform-ec2: Destroying... [id=i-0041e996aac4e5b4b]
aws_instance.my-first-terraform-ec2: Still destroying... [id=i-0041e996aac4e5b4b, 10s elapsed]
aws_instance.my-first-terraform-ec2: Still destroying... [id=i-0041e996aac4e5b4b, 20s elapsed]
aws_instance.my-first-terraform-ec2: Still destroying... [id=i-0041e996aac4e5b4b, 30s elapsed]
aws_instance.my-first-terraform-ec2: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.

削除結果を確認

aws コンソール画面にEC2が削除されたことを確認しました。
截屏2022-07-06 12.14.12.png

まとめ

今回、Terraformでawsのec2を構築、編集、削除を実行させていただきました。
以上となります。

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?