AdSense

網頁

2021/11/13

Terraform 建立EC2範例

Terraform 建立EC2 instance(執行個體)範例如下。


範例環境:

  • macOS Big Sur
  • AWS CLI 2.2.44
  • Terraform v1.0.10


事前要求

安裝好Terraform並確認AWS CLI設定好access key並可存取AWS服務。


建立配置

在任意資料夾(範例為terraform-demo)新增一個main.tf Terraform配置文件內容如下。此配置文件用來設定terraform配置、provider aws及要建立的EC2 resource aws_instance

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" // Tokyo
}

resource "aws_instance" "app_server" {
  ami           = "ami-0e60b6d05dc38ff11"
  instance_type = "t2.micro"

  tags = {
    Name = "TerraformProvisionDemo"
  }
}

EC2使用的AMI為Amazon Linux 2,AMI ID查詢方式參考「AWS 查詢Amazon Linux 2的AMI ID」。


檢驗配置

輸入terraform init將此目錄初始化為Terraform工作目錄,此時會根據配置的provider定義下載aws provider。

~/../terraform-demo$ terraform init

Initializing the backend...

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

輸入terraform fmt統一配置文件排版格式。

~/../terraform-demo$ terraform fmt

輸入terraform validate驗證配置文件語法是否正確。

~/../terraform-demo$ terraform validate
Success! The configuration is valid.


建立EC2

輸入terraform apply產生配置執行計畫並詢問是否執行,輸入yes確定執行。

~/../terraform-demo$ 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.app_server will be created
  + resource "aws_instance" "app_server" {
      + ami                                  = "ami-0e60b6d05dc38ff11"
      + 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" = "TerraformProvisionDemo"
        }
      + tags_all                             = {
          + "Name" = "TerraformProvisionDemo"
        }
      + 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)
        }

      + 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: Still creating... [40s elapsed]
aws_instance.app_server: Creation complete after 45s [id=i-09f43428032994849]

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

執行完後可在AWS console的EC2服務檢視instance,可看到透過Terraform建立的執行個體。




檢視狀態

配置計畫執行後Terraform會產生一個terraform.tfstate來記錄資源狀態以便進行管理。通常這份檔案應存放在遠端並限制存取人員以確保安全性。

輸入terraform show可檢視目前的狀態。

~/../terraform-demo$ terraform show
# aws_instance.app_server:
resource "aws_instance" "app_server" {
    ami                                  = "ami-0e60b6d05dc38ff11"
    arn                                  = "arn:aws:ec2:ap-northeast-1:400361196721:instance/i-09f43428032994849"
    associate_public_ip_address          = true
    availability_zone                    = "ap-northeast-1a"
    cpu_core_count                       = 1
    cpu_threads_per_core                 = 1
    disable_api_termination              = false
    ebs_optimized                        = false
    get_password_data                    = false
    hibernation                          = false
    id                                   = "i-09f43428032994849"
    instance_initiated_shutdown_behavior = "stop"
    instance_state                       = "running"
    instance_type                        = "t2.micro"
    ipv6_address_count                   = 0
    ipv6_addresses                       = []
    monitoring                           = false
    primary_network_interface_id         = "eni-025924c6134cb18e7"
    private_dns                          = "ip-172-31-22-142.ap-northeast-1.compute.internal"
    private_ip                           = "172.31.22.143"
    public_dns                           = "ec2-54-249-15-178.ap-northeast-1.compute.amazonaws.com"
    public_ip                            = "54.249.15.178"
    secondary_private_ips                = []
    security_groups                      = [
        "default",
    ]
    source_dest_check                    = true
    subnet_id                            = "subnet-af8d91d9"
    tags                                 = {
        "Name" = "TerraformProvisionDemo"
    }
    tags_all                             = {
        "Name" = "TerraformProvisionDemo"
    }
    tenancy                              = "default"
    vpc_security_group_ids               = [
        "sg-37ed5850",
    ]

    capacity_reservation_specification {
        capacity_reservation_preference = "open"
    }

    credit_specification {
        cpu_credits = "standard"
    }

    enclave_options {
        enabled = false
    }

    metadata_options {
        http_endpoint               = "enabled"
        http_put_response_hop_limit = 1
        http_tokens                 = "optional"
    }

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

github


沒有留言:

AdSense