Open8

Terraform Tutorial(AWS)を試してみる

ryskitryskit

anyenvでtfenvをインストールする

anyenv install tfenv

Terraformをインストールする

tfenv install 0.15.3
ryskitryskit

以下のチュートリアルをもとに進める。
https://learn.hashicorp.com/tutorials/terraform/aws-build

作業用ディレクトリを作成

$ mkdir learn-terraform-aws-instance
$ learn-terraform-aws-instance

ファイルを作成

$ touch main.tf

main.tfを開いて以下を記述する

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

  required_version = ">= 0.14.9"
}

provider "aws" {
  profile = "default"
  region  = "ap-northeast-1" // us-west-2 -> ap-northeast-1に変更
  assume_role {
    role_arn = "arn:aws:iam::[AWS ACCOUNT ID]:role/[AWS IAM ROLE NAME]" // assume roleして実行したかったので追記
  }
}

resource "aws_instance" "app_server" {
  ami           = "ami-0ca38c7440de1749a" // 6/3時点で「Amazon Linux 2 AMI (HVM), SSD Volume Type 」最新のAMI IDを指定
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}
ryskitryskit

terraform initを実行

$ terraform init 

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.27"...
- Installing hashicorp/aws v3.43.0...
- Installed hashicorp/aws v3.43.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.

terraform applyを実行

このコマンドを実行することで、AWS上にリソースが作成される。

挙動的には、VPCとかよしなに作ってくれるのか?と思ったけど、そもそも定義してないのでよしなには作ってくれない。

AWSのアカウント作成時にデフォルトであるVPCなどを使用してEC2を起動するようです。

$ terraform apply

terraform apply                                                                                                   1 ↵  131920:25:49

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.app_server will be created
  + resource "aws_instance" "app_server" {
      + ami                                  = "ami-0ca38c7440de1749a"
      + 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)
      + 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)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (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" = "ExampleAppServerInstance"
        }
      + tags_all                             = {
          + "Name" = "ExampleAppServerInstance"
        }
      + tenancy                              = (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)
        }

      + 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.app_server: Creating...
aws_instance.app_server: Still creating... [10s elapsed]
aws_instance.app_server: Still creating... [20s elapsed]
aws_instance.app_server: Still creating... [30s elapsed]
aws_instance.app_server: Creation complete after 32s [id=i-XXXXXXXXXXXXXXXX]

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

Stateを調べる

terraform apply を実行すると、Terraformは terraform.tfstate というファイルに作成したリソースのIDやプロパティ等を書いて管理するみたいです。

terraform show を使うことで現在のStateを確認できる。

ryskitryskit

次は以下のチュートリアルをもとに進める。
https://learn.hashicorp.com/tutorials/terraform/aws-change

AMI IDを変更する

resource "aws_instance" "app_server" {
  ami           = "ami-071c5ffb884b16119" // before: ami-0ca38c7440de1749
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }

terraform applyを再実行

$ terraform apply
ryskitryskit

次は以下のチュートリアルをもとに進める。
https://learn.hashicorp.com/tutorials/terraform/aws-destroy?in=terraform/aws-get-started

terraform destroyを実行する

terraform apply コマンドと逆で、管理しているリソースを削除する。

$ terraform destroy

aws_instance.app_server: Refreshing state... [id=i-XXXXXXXXXXXXXX]

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.app_server will be destroyed
  - resource "aws_instance" "app_server" {
...
...
...

Destroy complete! Resources: 1 destroyed.
ryskitryskit

次は以下のチュートリアルをもとに進める。
https://learn.hashicorp.com/tutorials/terraform/aws-variables?in=terraform/aws-get-started

variables.tf を作成

$ touch variables.tf

variables.tf を開いて以下の内容を記述する

variable "instance_name" {
    description = "Value of the Name tag for the EC2 instance"
    type        = string
    default     = "ExampleAppServerInstance"
}

main.tf のresource.tagsを修正

resource "aws_instance" "app_server" {
  ami           = "ami-071c5ffb884b16119"
  instance_type = "t2.micro"
  tags = {
    // - Name = "ExampleAppServerInstance"
    Name = var.instance_name
  }
}

修正したら実行してインスタンスを作成する。

$ terraform apply

コマンド実行時に変数を渡す

instance_nameという変数の値をコマンド実行時に -var を指定して渡してあげることでデフォルト値を上書きすることができる。

$ terraform apply -var "instance_name=YetAnotherName"
ryskitryskit

次は以下のチュートリアルをもとに進める。
https://learn.hashicorp.com/tutorials/terraform/aws-outputs?in=terraform/aws-get-started

EC2の設定を出力する

ファイル outputs.tf を作成する

$ touch outputs.tf

outputs.tf に以下を記述する

output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.app_server.id
}

output "instance_public_ip" {
  description = "Public IP address of the EC2 instance"
  value       = aws_instance.app_server.public_ip
}

terraform apply を実行する

Outputとして instance_idinstance_public_ip が出力される。

$ terraform apply

...
...
...
Changes to Outputs:
  + instance_id        = "i-XXXXXXXXX"
  + instance_public_ip = "XX.XX.XX.XXX"

terraform output を実行する

コマンドを実行すると、先程applyで出力された同様のOutputsが表示される

$ terraform output
instance_id = "i-XXXXXXXXXXXXXXXX"
instance_public_ip = "XX.XXX.XX.XXX"