brunch

You can make anything
by writing

C.S.Lewis

by Master Seo May 20. 2022

 네이버6탄-테라폼-2.리소스 알아보자  2/4


<1> 테라폼  리소스에 대해 알아보자

<2> 실습 2

<3> 개인 정리



<1> 테라폼  리소스에 대해 알아보자



1

리소스 

타입  

네이버  언더바   

네이버  클라우드 거다 

타입 다음 네임은 고유한 이름이어야 한다.

타입이 다르면  이름이 같아도 된다.



2

버전?

내가 쓰는 버전과 다른 사람이 쓰는 거와 같게 하자.

기능이 같은 상태로 공유하기 위해  명시적으로 버전을 적는다.



3

테라폼  apply는  우선  plan 실행하고,  승인하면 변경사항을 적용한다.


원래 plan  >   out 파일 만든다.

out 파일을   apply 하는 게  순서이다.


파이프라인을 태우는 경우는   플랜에서  out 파일을 만들고 하기도 한다.



4

리소스 삭제는?


terraform  destroy  

승인하면 제거된다.



5

리소스는  무조건 만든다.

리소스는 만드는 작업이구나~~



6

데이터 타입은 기존에 존재하는 리소스이다.

정보를 가져오는 것이다.

데이터는 정보를 가져오는 것이구나.


data. xxxxxxxx   형태로 작성해서 정보를 가져온다.



7

리소스 만들 때  데이터를 가져와야   리소스를 만든다.

그래서 데이터를 먼저 가져와야 한다.  데이터부터 설정하라~

디펜던시가 있으니  데이터부터 설정하라~



8

아웃풋?

아웃풋으로 결과 출력을 볼 수 있다!!!


협업을 하면 

보여주고 싶은 부문만  아웃풋으로 출력한다.



9

디펜던시가 있다.





<2>  실습 2



1

Vscode 실행

LAB02 폴더를 열어라



2

주석을 풀어라.

main.tf의 모든 주석을 제거하세요.

outputs.tf의 모든 주석을 제거하세요.



3

아웃풋   url을   클릭하여 나오는 그림을 확인하는 것이  이번 실습의 목적이다.


참고 사이트 

https://docmoa.github.io/03-Public%20Cloud/NCP/09-Terraform-Workshop/01-intro_to_terraform_on_ncp/03-z-lab_terraform_action.html



4

lab2 폴더에  테라폼 실행파일 복사



5

Vscode 실행하기

Terminal 열기


PS D:\2\workshop-oss-main\lab02> .\terraform.exe init



6

access-key , secret key 지정

PS D:\2\workshop-oss-main\lab02> $Env:NCLOUD_ACCESS_KEY="7qYmcED4A"

PS D:\2\workshop-oss-main\lab02> $Env:NCLOUD_SECRET_KEY="u8n6zn71B"



7

.\terraform.exe plan 

.\terraform.exe apply


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


(10분 걸림)



8

Outputs:

catapp_url = "http://175.45.192.162"


브라우저로 확인





9

vpc등 생성 확인




PS C:\2\workshop-oss-main\lab02> more *.tf

terraform {

  required_providers {

    ncloud = {

      source  = "NaverCloudPlatform/ncloud"

      version = "~> 2.0"

    }

  }

}

provider "ncloud" {

  region      = var.region

  site        = var.site

  support_vpc = true

}

resource "ncloud_vpc" "hashicat" {

  ipv4_cidr_block = var.address_space

  name            = lower("${var.prefix}-vpc-${var.region}")

}

resource "ncloud_network_acl" "hashicat" {

  vpc_no      = ncloud_vpc.hashicat.id

  name        = "${var.prefix}-acl-public"

  description = "for Public"

}

resource "ncloud_subnet" "hashicat" {

  name           = "${var.prefix}-subnet"

  vpc_no         = ncloud_vpc.hashicat.id

  subnet         = "10.0.1.0/24"

  zone           = var.zone

  network_acl_no = ncloud_network_acl.hashicat.id

  subnet_type    = "PUBLIC"

  usage_type     = "GEN"

}

resource "ncloud_nat_gateway" "hashicat" {

  vpc_no = ncloud_vpc.hashicat.id

  zone   = var.zone

  name   = "${var.prefix}-gw"

}

resource "ncloud_route" "hashicat" {

  route_table_no         = ncloud_vpc.hashicat.default_public_route_table_no

  destination_cidr_block = "10.0.1.0/24"

  target_type            = "NATGW" # NATGW (NAT Gateway) | VPCPEERING (VPC Peering) | VGW (Virtual Private Gateway).

  target_name            = ncloud_nat_gateway.hashicat.name

  target_no              = ncloud_nat_gateway.hashicat.id

}

locals {

  public_subnet_inbound = [

    [1, "TCP", "0.0.0.0/0", "80", "ALLOW"],

    [2, "TCP", "0.0.0.0/0", "443", "ALLOW"],

    [3, "TCP", "0.0.0.0/0", "22", "ALLOW"],

    [4, "TCP", "${var.client_ip}/32", "3389", "ALLOW"],

    [5, "TCP", "0.0.0.0/0", "32768-65535", "ALLOW"],

    [197, "TCP", "0.0.0.0/0", "1-65535", "DROP"],

    [198, "UDP", "0.0.0.0/0", "1-65535", "DROP"],

    [199, "ICMP", "0.0.0.0/0", null, "DROP"],

  ]

  public_subnet_outbound = [

    [1, "TCP", "0.0.0.0/0", "80", "ALLOW"],

    [2, "TCP", "0.0.0.0/0", "443", "ALLOW"],

    [3, "TCP", "0.0.0.0/0", "9001-65535", "ALLOW"],

    [4, "TCP", "${ncloud_server.hashicat.network_interface[0].private_ip}/32", "8080", "ALLOW"],

    # Allow 8080 port to private server

    [197, "TCP", "0.0.0.0/0", "1-65535", "DROP"],

    [198, "UDP", "0.0.0.0/0", "1-65535", "DROP"],

    [199, "ICMP", "0.0.0.0/0", null, "DROP"]

  ]

}

data "ncloud_access_control_group" "hashicat" {

  id = ncloud_vpc.hashicat.default_access_control_group_no

}

resource "ncloud_access_control_group_rule" "hashicat" {

  access_control_group_no = data.ncloud_access_control_group.hashicat.id

  dynamic "inbound" {

    for_each = local.public_subnet_inbound

    content {

      protocol   = inbound.value[1]

      ip_block   = inbound.value[2]

      port_range = inbound.value[3]

    }

  }

  outbound {

    protocol    = "TCP"

    ip_block    = "0.0.0.0/0"

    port_range  = "1-65535"

    description = "accept 1-65535 port"

  }

}

resource "ncloud_network_acl_rule" "hashicat" {

  network_acl_no = ncloud_network_acl.hashicat.id

  dynamic "inbound" {

    for_each = local.public_subnet_inbound

    content {

      priority    = inbound.value[0]

      protocol    = inbound.value[1]

      ip_block    = inbound.value[2]

      port_range  = inbound.value[3]

      rule_action = inbound.value[4]

    }

  }

  dynamic "outbound" {

    for_each = local.public_subnet_outbound

    content {

      priority    = outbound.value[0]

      protocol    = outbound.value[1]

      ip_block    = outbound.value[2]

      port_range  = outbound.value[3]

      rule_action = outbound.value[4]

    }

  }

}

resource "ncloud_login_key" "hashicat" {

  key_name = "${var.prefix}-key"

}

data "ncloud_server_images" "hashicat" {

  filter {

    name   = "product_name"

    values = ["ubuntu-18.04?"]

    regex  = true

  }

  filter {

    name   = "product_code"

    values = ["SW.VSVR.OS.LNX64.UBNTU.SVR1804.B050"]

    regex  = true

  }

}

data "ncloud_server_products" "hashicat" {

  server_image_product_code = data.ncloud_server_images.hashicat.server_images[0].product_code

  filter {

    name   = "product_code"

    values = ["SSD"]

    regex  = true

  }

  filter {

    name   = "cpu_count"

    values = ["2"]

  }

  filter {

    name   = "product_type"

    values = ["STAND"]

  }

}

resource "ncloud_server" "hashicat" {

  subnet_no                 = ncloud_subnet.hashicat.id

  name                      = "${var.prefix}-public"

  server_image_product_code = data.ncloud_server_images.hashicat.server_images[0].product_code

  login_key_name            = ncloud_login_key.hashicat.key_name

  server_product_code       = data.ncloud_server_products.hashicat.server_products.0.product_code

}

data "ncloud_root_password" "hashicat" {

  server_instance_no = ncloud_server.hashicat.id

  private_key        = ncloud_login_key.hashicat.private_key

}

resource "ncloud_public_ip" "hashicat" {

  server_instance_no = ncloud_server.hashicat.id

  description        = "${var.prefix}-public-ip"

}

resource "null_resource" "configure-cat-app" {

  depends_on = [ncloud_public_ip.hashicat]

  triggers = {

    build_number = timestamp()

  }

  provisioner "file" {

    source      = "files/"

    destination = "/tmp"

    connection {

      type     = "ssh"

      user     = "root"

      port     = "22"

      password = data.ncloud_root_password.hashicat.root_password

      host     = ncloud_public_ip.hashicat.public_ip

    }

  }

  provisioner "remote-exec" {

    inline = [

      "sudo apt -y update",

      "sleep 15",

      "sudo apt -y update",

      "sudo apt -y install apache2",

      "sudo systemctl start apache2",

      "chmod +x /tmp/*.sh",

      "PLACEHOLDER=${var.placeholder} WIDTH=${var.width} HEIGHT=${var.height} PREFIX=${var.prefix} /tmp/deploy_app.sh",

    ]

    connection {

      type     = "ssh"

      user     = "root"

      port     = "22"

      password = data.ncloud_root_password.hashicat.root_password

      host     = ncloud_public_ip.hashicat.public_ip

    }

  }

}

 output "catapp_url" {

   value = "http://${ncloud_public_ip.hashicat.public_ip}"

 }

##############################################################################

# Variables File

#

# Here is where we store the default values for all the variables used in our

# Terraform code. If you create a variable with no default, the user will be

# prompted to enter it (or define it via config file or command line flags.)

variable "prefix" {

  description = "This prefix will be included in the name of most resources."

}

variable "client_ip" {

  description = "https://search.naver.com/search.naver?where=nexearch&sm=top_sug.pre&fbm=1&acr=1&acq=ip&qdt=0&ie=utf8&query=ip+%EC%A3%BC%EC%86%8C+%ED%99%95%EC%9D%B8"

  default = "118.130.103.106"

}

variable "region" {

  description = "The region where the resources are created."

  default     = "KR"

}

variable "zone" {

  description = "The zone where the resources are created."

  default     = "KR-2"

}

variable "site" {

  description = "Ncloud site. By default, the value is public. You can specify only the following value: public, gov, fin. public is for 

www.ncloud.com. gov is for www.gov-ncloud.com. fin is for www.fin-ncloud.com."

  default     = "public"

}

a new resource to be created."

  default     = "10.0.0.0/16"

}

variable "height" {

  default     = "400"

  description = "Image height in pixels."

}

variable "width" {

  default     = "600"

  description = "Image width in pixels."

}

variable "placeholder" {

  default     = "placekitten.com"

  description = "Image-as-a-service URL. Some other fun ones to try are fillmurray.com, placecage.com, placebeard.it, loremflickr.com, baconmockup.com, placeimg.com, placebear.com, placeskull.com, stevensegallery.com, placedog.net"

}


PS C:\2\workshop-oss-main\lab02> dir

    디렉터리: C:\2\workshop-oss-main\lab02

Mode                 LastWriteTime         Length Name

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

d-----        2022-05-20   오후 5:23                .terraform

d-----        2022-05-20   오후 3:57                files

-a----        2022-05-20   오후 5:23           2312 .terraform.lock.hcl

-a----        2022-05-20   오후 5:21           5844 main.tf

-a----        2022-05-20   오후 5:21             84 outputs.tf

-a----        2022-05-19   오전 6:03       61461472 terraform.exe

-a----        2022-05-20   오후 5:33          25991 terraform.tfstate

-a----        2022-05-20   오후 5:21            175 terraform.tfvars

------        2022-05-19   오후 7:31           1818 variables.tf






10

재 생성 해보자 !!


vpc등 이름 대체 ?

terraform.tfvars 에서  prfix 변경


.\terraform.exe apply





11

삭제?

PS D:\2\workshop-oss-main\lab02> .\terraform.exe destroy

yes





<3> 개인 정리



1

리소스는  무조건 만든다.

리소스는 만드는 작업이구나~~



2

데이터 타입은 기존에 존재하는 리소스이다.

정보를 가져오는 것이다.

데이터는 정보를 가져오는 것이구나.


data. xxxxxxxx   형태로 작성해서 정보를 가져온다.




다음 공부

https://brunch.co.kr/@topasvga/2448




전체 보기

https://brunch.co.kr/@topasvga/2450


감사합니다.

매거진의 이전글 네이버6탄-테라폼-테라폼으로 관리 1/4

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari