리셋 되지 말자

[Terraform] NCP - Terraform으로 서버 생성하기 본문

Infra

[Terraform] NCP - Terraform으로 서버 생성하기

kyeongjun-dev 2021. 3. 17. 18:15

NCP를 사용하는 이유

AWS는 프리티어 기간이 끝났다. => 유료다
NCP는 아직 프리티어 기간이다 => 무료다  NCP의 경우 무료 VM을 한개만 사용이 가능합니다. 즉 아래의 실습을 하기 위해서는 유료 요금이 발생하는 VM 2개를 사용해야합니다. 이점 유의해 주시기 바랍니다.

 

사전 준비 사항

1. 당연히 NCP에 가입된 아이디가 있어야 한다.
2. Terraform 0.13 이상 버전 설치
- 설치가 안되어 있다면 (not-to-be-reset.tistory.com/368) 참고하여 설치해주시기 바랍니다.

 

테라폼 파일 작성

아래에 나오는 파일들을 모두 동일한 디렉토리에 작성하면 된다.

$ ls
main.tf  outputs.tf  variables.tf  versions.tf

 

- main.tf

provider "ncloud" {
  access_key = var.access_key
  secret_key = var.secret_key
  region     = var.region
}

data "ncloud_regions" "regions" {
}

data "ncloud_server_images" "server_images" {
}

resource "ncloud_server" "server" {
  name                      = var.server_name
  server_image_product_code = var.server_image_product_code
  server_product_code       = var.server_product_code
}

 

- outputs.tf

output "server_name_list" {
  value = join(",", ncloud_server.server.*.name)
}

 

- variables.tf

variable "access_key" { # export TF_VAR_access_key=...
}

variable "secret_key" { # export TF_VAR_secret_key=...
}

variable "region" {
  default = "KR"
}

variable "server_name" {
  default = "terraform-test"
}

variable "server_image_product_code" {
  default = "SPSW0LINUX000032"
}

variable "server_product_code" {
  default = "SPSVRSTAND000004" #SPSVRSTAND000056
}

 

- versions.tf

terraform {
  required_version = ">= 0.13"
  required_providers {
    ncloud = {
      source = "navercloudplatform/ncloud"
    }
  }
}

 

NCP Access key, Secret key 확인 및 환경 변수 등록

variables.tf에 쓰여진 대로 환경 변수를 설정하면 된다. 리눅스 터미널에서 실행한다.

 

1. Access key, Secret key 확인

NCP 로그인

NCP 홈페이지에 로그인한 뒤, '마이페이지' -> '인증키 관리' 메뉴를 클릭하여 이동한다.

 

신규 API 인증키 생성

위 그림에서 오른쪽 상단에 보이는 '신규 API 인증키 생성'을 클릭하면, API 인증키가 생성된다. Access Key는 바로 보이고, Secret Key는 '보기'버튼 클릭해서 확인하면 된다.
노출되면 한달 사용료 1억도 털릴수 있으니 절.대 유출 금지

 

2. Access key, Secret key를 환경 변수에 등록

export TF_VAR_access_key=ABCD
export TF_VAR_secret_key=ABCDE

위의 'ABCD', 'ABCDE' 대신 NCP에서 확인한 키 값들을 복사해서 넣어주면 된다.

 

Terraform init

$ terraform init

terraform init 명령어를 이용해서 테라폼 provider로 ncloud를 등록한다.

Initializing the backend...

Initializing provider plugins...
- Finding latest version of navercloudplatform/ncloud...
- Installing navercloudplatform/ncloud v2.0.5...
- Installed navercloudplatform/ncloud v2.0.5 (self-signed, key ID 121312131212)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html

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.

init에 성공하면 위와같은 로그들을 확인할 수 있다.

 

Terraform plan

$ terraform plan

'terraform plan' 명령어로 선언한 리소스 생성에 대한 변경 내용을 확인할 수 있다.

 

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # ncloud_server.server will be created
  + resource "ncloud_server" "server" {
      + base_block_storage_disk_detail_type    = (known after apply)
      + base_block_storage_disk_type           = (known after apply)
      + base_block_storage_size                = (known after apply)
      + cpu_count                              = (known after apply)
      + description                            = (known after apply)
      + id                                     = (known after apply)
      + init_script_no                         = (known after apply)
      + instance_no                            = (known after apply)
      + internet_line_type                     = (known after apply)
      + is_encrypted_base_block_storage_volume = (known after apply)
      + is_fee_charging_monitoring             = (known after apply)
      + is_protect_server_termination          = (known after apply)
      + login_key_name                         = (known after apply)
      + memory_size                            = (known after apply)
      + name                                   = "terraform-test"
      + placement_group_no                     = (known after apply)
      + platform_type                          = (known after apply)
      + port_forwarding_external_port          = (known after apply)
      + port_forwarding_internal_port          = (known after apply)
      + port_forwarding_public_ip              = (known after apply)
      + private_ip                             = (known after apply)
      + public_ip                              = (known after apply)
      + region                                 = (known after apply)
      + server_image_name                      = (known after apply)
      + server_image_product_code              = "SPSW0LINUX000032"
      + server_product_code                    = "SPSVRSTAND000004"
      + subnet_no                              = (known after apply)
      + vpc_no                                 = (known after apply)
      + zone                                   = (known after apply)

      + network_interface {
          + network_interface_no = (known after apply)
          + order                = (known after apply)
          + private_ip           = (known after apply)
          + subnet_no            = (known after apply)
        }
    }

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

Changes to Outputs:
  + server_name_list = "terraform-test"

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

해석해보자면 'terraform-test'라는 이름의 server 하나가 추가될 것이라는 것이다. (Plan : 1 to add)

 

Terraform apply

$ terraform apply

apply 명령어를 사용하여 plan을 실제로 적용하여 서버를 생성해보자

 

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # ncloud_server.server will be created
  + resource "ncloud_server" "server" {
      + base_block_storage_disk_detail_type    = (known after apply)
      + base_block_storage_disk_type           = (known after apply)
      + base_block_storage_size                = (known after apply)
      + cpu_count                              = (known after apply)
      + description                            = (known after apply)
      + id                                     = (known after apply)
      + init_script_no                         = (known after apply)
      + instance_no                            = (known after apply)
      + internet_line_type                     = (known after apply)
      + is_encrypted_base_block_storage_volume = (known after apply)
      + is_fee_charging_monitoring             = (known after apply)
      + is_protect_server_termination          = (known after apply)
      + login_key_name                         = (known after apply)
      + memory_size                            = (known after apply)
      + name                                   = "terraform-test"
      + placement_group_no                     = (known after apply)
      + platform_type                          = (known after apply)
      + port_forwarding_external_port          = (known after apply)
      + port_forwarding_internal_port          = (known after apply)
      + port_forwarding_public_ip              = (known after apply)
      + private_ip                             = (known after apply)
      + public_ip                              = (known after apply)
      + region                                 = (known after apply)
      + server_image_name                      = (known after apply)
      + server_image_product_code              = "SPSW0LINUX000032"
      + server_product_code                    = "SPSVRSTAND000004"
      + subnet_no                              = (known after apply)
      + vpc_no                                 = (known after apply)
      + zone                                   = (known after apply)

      + network_interface {
          + network_interface_no = (known after apply)
          + order                = (known after apply)
          + private_ip           = (known after apply)
          + subnet_no            = (known after apply)
        }
    }

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

Changes to Outputs:
  + server_name_list = "terraform-test"

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

ncloud_server.server: Creating...
ncloud_server.server: Still creating... [10s elapsed]
ncloud_server.server: Still creating... [20s elapsed]
ncloud_server.server: Still creating... [30s elapsed]
ncloud_server.server: Still creating... [40s elapsed]
ncloud_server.server: Still creating... [50s elapsed]
ncloud_server.server: Still creating... [1m0s elapsed]
ncloud_server.server: Still creating... [1m10s elapsed]
ncloud_server.server: Still creating... [1m20s elapsed]
ncloud_server.server: Still creating... [1m30s elapsed]
ncloud_server.server: Still creating... [1m40s elapsed]
ncloud_server.server: Still creating... [1m50s elapsed]
ncloud_server.server: Still creating... [2m0s elapsed]
ncloud_server.server: Still creating... [2m10s elapsed]
ncloud_server.server: Still creating... [2m20s elapsed]
ncloud_server.server: Still creating... [2m30s elapsed]
ncloud_server.server: Still creating... [2m40s elapsed]
ncloud_server.server: Still creating... [2m50s elapsed]
ncloud_server.server: Still creating... [3m0s elapsed]
ncloud_server.server: Still creating... [3m10s elapsed]
ncloud_server.server: Creation complete after 3m18s [id=6236714]

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

Outputs:

server_name_list = "terraform-test"

생성 되었다.

 

NCP 콘솔에서 확인

NCP 대시보드 -> Server 확인

실제로 'terraform-test'라는 이름의 서버가 하나 생성된 것을 확인할 수 있다.

 

결과 확인

$ ls
main.tf  outputs.tf  terraform.tfstate  variables.tf  versions.tf

apply가 끝나면, 'terraform.tfstate'라는 파일이 생성되어 있는것을 확인할 수 있다.
이 파일에서 apply가 어떻게 진행 되었는지 확인할 수 있다.

서버 한대만 생성했지만, 여러 서버와 LB 등 여러 인프라 구성요소를 한번에 구성 및 설치하는 것도 가능하다. 앞으로 계속 시간날때마다 포스팅 하겠따

Comments