Terraform을 활용한 네이버 클라우드 플랫폼 인프라 구성하기

NAVER Cloud
NAVER Cloud
Published in
7 min readMay 13, 2019

안녕하세요, 네이버 클라우드 플랫폼입니다.
​Terraform Provider로 네이버 클라우드 플랫폼이 정식 등록되었습니다!

​그래서 오늘은 “Terraform을 활용해 NAVER CLOUD PLATFORM의 인프라 생성하기”라는 주제로 포스팅하겠습니다.

Terraform 정의나 Infrastructure as a Code (IAC)의 장점에 대한 설명은 하기 블로그에서 참고 부탁 드리며, 이번 글에서는 Terraform을 이용해서 네이버 클라우드 플랫폼 인프라 생성하는 것을 중심으로 살펴 보겠습니다.

Terraform을 이용한 네이버 클라우드 플랫폼 인프라 생성하기 데모

이번 데모에서 Terraform을 이용해서 생성할 아키텍처 입니다.
두 대의 웹 서버를 서로 다른 Availability Zone에 생성하고, Public Load Balancer를 생성해서 두 대의 서버를 바인딩하는 간단한 데모입니다.

■ Demo 순서는 아래와 같습니다.

1. 네이버 클라우드 플랫폼 인증키 생성
2. Working directory 생성 및 Terraform Provider 정의
3. HCL (HashiCorp Configuration Language) 이용 네이버 클라우드 플랫폼 리소스 정의
3.1 한국 리전 두 개의 Availability Zone (kr-1, kr-2)에 각 웹 서버 한대씩 생성3.2 Load Balancer(데모에서는 tf_webinar_lb) 생성 & 웹 서버 두 대 바인딩
4. 리소스에 대한 생성 & 변경 내용 확인(Plan)
5. 실제 인프라 적용(Apply)
6. 인프라 리소스 생성 확인​

시작하겠습니다.

1. 네이버 클라우드 플랫폼 인증키 생성

네이버 클라우드 플랫폼 계정은 이미 가지고 있다고 가정하겠습니다.

계정 로그인 후 [마이페이지] — [인증키 관리] — [신규 API 인증키 생성] (이미 생성된 키가 있다면 해당 키를 그대로 사용하셔도 됩니다.)

2. Working directory 생성 및 Terraform Provider 정의

Terraform은 단일 바이너리 파일로 배포되고 있어 간단하게 설치가 가능합니다. Terraform 다운로드 페이지에서 실행 환경에 맞는 패키지 다운로드를 한 후 압축을 해제하고 별도의 추가 설치 없이 바로 Terraform을 사용할 수 있습니다

데모 환경에서 설치한 Terraform 버전은 0.11.8 입니다.

2–1. Terraform 설치

root@base-linux : ~ # wget https://releases.hashicorp.com/terraform/0.11.8/terraform_0.11.8_linux_amd64.zip
root@base-linux : ~ # unzip terraform_0.11.8_linux_amd64.zip && mv terraform /usr/bin/​

2–2. 설치 확인

root@base-linux : ~ # terraform version
Terraform v0.11.8

2–3. Working directory (데모에서는 terraform) 생성 및 Terraform Provider(ncloud.tf) 및 리소스 정의 파일(infra.tf), user-data 파일 생성

root@base-linux : ~ # mkdir /root/terraform
root@base-linux : ~ # cd /root/terraform && touch ncloud.tf infra.tf user-data.sh
root@base-linux : ~/terraform # cat user-data.sh
#!/bin/bash
yum install -y httpd
/etc/init.d/httpd start
echo “NCP SERVER-$HOSTNAME” > /var/www/html/index.html​

root@base-linux : ~/terraform # tree
.
├── terraform
│ ├── infra.tf
│ ├── ncloud.tf
│ ├── user-data.sh

- Provider 설정 파일(ncloud.tf)에 ncloud 선언 및 설치(init)을 진행합니다.

root@base-linux : ~/terraform # cat ncloud.tf
provider “ncloud” {
access_key = “ACCESS KEY
secret_key = “SECET KEY
region = “Region
}

root@base-linux : ~/terraform # terraform init && terraform version
Initializing provider plugins…

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking changes, it is recommended to add version = “…” constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.ncloud: version = “~> 0.0”

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 v0.11.8
+ provider.ncloud v0.0.1

3. HCL (HashiCorp Configuration Language)

이용 네이버 클라우드 플랫폼 리소스 정의

3–1. 한국 리전 두 개의 Availability Zone(kr-1, kr-2)에 각 웹 서버 한대씩 생성

데모에서는 infra.tf 파일에 인프라를 정의하고, 참조 변수를 정의합니다. 참조 변수값(value)에 대한 확인은 NCP CLI를 통해 확인 가능합니다. (네이버 클라우드 플랫폼 CLI 활용)

root@base-linux : ~/terraform # cat infra.tf
###Terraform을 활용한 Naver Cloud Platform Server 생성하기
variable “ncloud_zones” {
type = “list”
default = [“KR-1”, “KR-2”]
}

variable “server_image_prodict_code” {
default = “SPSW0LINUX000032”
}

variable “server_product_code” {
default = “SPSVRSTAND000004”
}

# keypair create
resource “ncloud_login_key” “loginkey” {
“key_name” = “webinar”
}

data “template_file” “user_data” {
template = “${file(“user-data.sh”)}”
}

#server create
resource “ncloud_server” “server” {
“count” = “2”
“server_name” = “tf-webinar-vm-${count.index+1}”
“server_image_product_code” = “${var.server_image_prodict_code}”
“server_product_code” = “${var.server_product_code}”
“server_description” = “tf-webinar-vm-${count.index+1}”
“login_key_name” = “${ncloud_login_key.loginkey.key_name}”
“access_control_group_configuration_no_list” = [“13054”]
“zone_code” = “${var.ncloud_zones[count.index]}”
“user_data” = “${data.template_file.user_data.rendered}”
}

3–2. Load Balancer(데모에서는 tf_webinar_lb) 생성 & 웹 서버 두 대 바인딩

### LB create
resource “ncloud_load_balancer” “lb” {
“load_balancer_name” = “ttf_webinar_lb”
“load_balancer_algorithm_type_code” = “RR
“load_balancer_description” = “tf_webinar_lb”

“load_balancer_rule_list” = [

{
“protocol_type_code” = “HTTP”
“load_balancer_port” = 80
“server_port” = 80
“l7_health_check_path” = “/”
},
]

“server_instance_no_list” = [“${ncloud_server.server.*.id[0]}”,
“${ncloud_server.server.*.id[1]}”]
“internet_line_type_code” = “PUBLC”
“network_usage_type_code” = “PBLIP”
“region_no” = “1”
}

4. 리소스에 대한 생성 & 변경 내용 확인(Plan)

실제 인프라에 대한 생성&변경 전 변경되는 부분에 대해서 사전 확인할 수 있는 Plan을 실행합니다.

인프라에 대한 총 4건의 신규 생성이 있다는 것을 사전에 확인할 수 있습니다. (“4 to add, 0 to change, 0 to destroy.”)

root@base-linux : ~/terraform # terraform plan
Refreshing Terraform state in-memory prior to plan…
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

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_load_balancer.lb
id: <computed>
certificate_name: <computed>
connection_timeout: <computed>
create_date: <computed>
domain_name: <computed>
internet_line_type.%: <computed>
internet_line_type_code: “PUBLC”
is_http_keep_alive: <computed>
load_balanced_server_instance_list.#: <computed>
load_balancer_algorithm_type.%: <computed>
load_balancer_algorithm_type_code: “RR”
load_balancer_description: “tf_webinar_lb”
load_balancer_instance_no: <computed>
load_balancer_instance_operation.%: <computed>
load_balancer_instance_status.%: <computed>
load_balancer_instance_status_name: <computed>
load_balancer_name: “ttf_webinar_lb”
load_balancer_rule_list.#: “1”
load_balancer_rule_list.0.l7_health_check_path: “/”
load_balancer_rule_list.0.load_balancer_port: “80”
load_balancer_rule_list.0.protocol_type.%: <computed>
load_balancer_rule_list.0.protocol_type_code: “HTTP”
load_balancer_rule_list.0.server_port: “80”
network_usage_type.%: <computed>
network_usage_type_code: “PBLIP”
region_no: “1”
server_instance_no_list.#: <computed>
virtual_ip: <computed>

+ ncloud_login_key.loginkey
id: <computed>
create_date: <computed>
fingerprint: <computed>
key_name: “webinar”
private_key: <computed>

+ ncloud_server.server[0]
id: <computed>
access_control_group_configuration_no_list.#: “1”
access_control_group_configuration_no_list.0: “13054”
base_block_storage_disk_detail_type.%: <computed>
base_block_storage_disk_type.%: <computed>
base_block_storage_size: <computed>
cpu_count: <computed>
create_date: <computed>
internet_line_type.%: <computed>
is_fee_charging_monitoring: <computed>
login_key_name: “webinar”
memory_size: <computed>
platform_type.%: <computed>
port_forwarding_external_port: <computed>
port_forwarding_internal_port: <computed>
port_forwarding_public_ip: <computed>
private_ip: <computed>
public_ip: <computed>
region.%: <computed>
server_description: “tf-webinar-vm-1”
server_image_name: <computed>
server_image_product_code: “SPSW0LINUX000032”
server_instance_no: <computed>
server_instance_operation.%: <computed>
server_instance_status.%: <computed>
server_instance_status_name: <computed>
server_name: “tf-webinar-vm-1”
server_product_code: “SPSVRSTAND000004”
uptime: <computed>
user_data : “#!/bin/bash\nyum install -y httpd\n/etc/init.d/httpd start\necho \”NCP SERVER-$HOSTNAME\” > /var/www/html/index.html\n”
zone.%: <computed>
zone_code: “KR-1”

+ ncloud_server.server[1]
id: <computed>
access_control_group_configuration_no_list.#: “1”
access_control_group_configuration_no_list.0: “13054”
base_block_storage_disk_detail_type.%: <computed>
base_block_storage_disk_type.%: <computed>
base_block_storage_size: <computed>
cpu_count: <computed>
create_date: <computed>
internet_line_type.%: <computed>
is_fee_charging_monitoring: <computed>
login_key_name: “webinar”
memory_size: <computed>
platform_type.%: <computed>
port_forwarding_external_port: <computed>
port_forwarding_internal_port: <computed>
port_forwarding_public_ip: <computed>
private_ip: <computed>
public_ip: <computed>
region.%: <computed>
server_description: “tf-webinar-vm-2”
server_image_name: <computed>
server_image_product_code: “SPSW0LINUX000032”
server_instance_no: <computed>
server_instance_operation.%: <computed>
server_instance_status.%: <computed>
server_instance_status_name: <computed>
server_name: “tf-webinar-vm-2”
server_product_code: “SPSVRSTAND000004”
uptime: <computed>
user_data: “#!/bin/bash\nyum install -y httpd\n/etc/init.d/httpd start\necho \”NCP SERVER-$HOSTNAME\” > /var/www/html/index.html\n”
zone.%: <computed>
zone_code: “KR-2”

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

5. 실제 인프라 생성(Apply)

terraform plan 실행 결과로 추가, 변경되는 인프라 리소스에 대한 사전 확인을 한 후, 리얼 인프라 리소스를 생성하기 위해 terraform apply를 실행합니다.

root@base-linux : ~/terraform # terraform apply

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_load_balancer.lb

```

+ + ncloud_login_key.loginkey

```

++ ncloud_server.server[0]

```

++ ncloud_server.server[1]

```

Plan: 5 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

ncloud_login_key.loginkey: Creating…

```

ncloud_server.server[0]: Creating…

```

ncloud_load_balancer.lb: Creating…

```

ncloud_load_balancer.lb: Still creating… (10s elapsed)

```

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

6. 인프라 생성 확인

이제 네이버 클라우드 플랫폼 로그인 후 Terraform으로 생성한 서버 두 대와 Load Balancer를 확인할 수 있습니다.

그리고 Load Balancer의 퍼블릭 도메인에 접속해보면 두 대의 웹서버 페이지가 Round Robin으로 분기되는 것을 확인할 수 있습니다.

- 서버 생성 확인

- 로드 밸런서 생성 확인 & 접속 테스트

글을 마무리하며…

오늘은 Terraform을 활용해 네이버 클라우드 플랫폼의 인프라 생성하는 법을 알아봤는데요, 도움이 되셨나요?

Terraform을 사용하여 코드로 인프라 구성을 관리해보시기 바랍니다. 서비스 사용 및 구축 중에 이슈가 발생하신 경우 네이버 클라우드 플랫폼 고객지원으로 문의하시면 빠른 지원 받으실 수 있습니다. 앞으로도 네이버 클라우드 플랫폼에 많은 관심 부탁드립니다!

※ 본 콘텐츠는 네이버 클라우드 플랫폼 온라인 교육 페이지에서 영상으로 시청이 가능합니다.

[NAVER CLOUD PLATFORM 온라인 교육 수강] “Terraform을 활용한 네이버 클라우드 플랫폼 인프라 만들기” >> 수강하기

[NAVER CLOUD PLATFORM 온라인 교육 수강] “Packer를 활용하여 내서버이미지 만들기” >> 수강하기

[NAVER CLOUD PLATFORM 온라인 교육 수강] “네이버클라우드플랫폼으로 CI/CD 구현하기” >> 수강하기

* 온라인 무료 교육 영상 시청을 위해서는 ncloud.com 회원 가입 및 로그인이 필요합니다

[NBP 기술 & 경험] 국내 클라우드 업체 최초 Terraform Provider 리스트 등재

--

--

NAVER Cloud
NAVER Cloud

We provide cloud-based information technology services for industry leaders from startups to enterprises.