[gcp] terraform으로 인프라 구축

cch_chan·2023년 4월 7일
0

GCP

목록 보기
14/14

환경 구성

  • gcp cli 설치 필요

  • vscode에서 gcloud 연동

gcloud auth application-default login

  • terraform 설치

Install | Terraform | HashiCorp Developer

공식 홈페이지에서 해당 os에 맞는 terraform 설치

기본 정보

명령어

terraform init → terraform을 초기화 해주고 상태 파일 생성등 현재 상태관리를 폴더 단위로 생성

terraform plan → 작성한 코드가 실제로 어떻게 생성될지에 대한 예측 결과를 보여줌

terraform apply → 코드로 실제 인프라를 생성

terraform destroy → 생성된 자원들을 state 파일 기준으로 모두 삭제

terraform import → 이미 생성된 자원을 테라폼 state 파일로 옮겨주는 명령어

Code

VPC 생성

network.tf

 
resource "google_compute_network" "vpc_network" {
  name                    = "my-custom-mode-network"
  auto_create_subnetworks = false
  mtu                     = 1460
}

resource "google_compute_subnetwork" "default" {
  name          = "my-custom-subnet"
  ip_cidr_range = "10.0.1.0/24"
  region        = "asia-northeast3"
  network       = google_compute_network.vpc_network.id
}

VM 생성

instance.tf

# Create a single Compute Engine instance
resource "google_compute_instance" "default" {
  name         = "flask-vm"
  machine_type = "f1-micro"
  zone         = "asia-northeast3-a"
  tags         = ["ssh"]

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }

  # Install Flask
  metadata_startup_script = "sudo apt-get update; sudo apt-get install -yq build-essential python3-pip rsync; pip install flask"

  network_interface {
    subnetwork = google_compute_subnetwork.default.id

    access_config {
      # Include this section to give the VM an external IP address
    }
  }
}

Test

리소스 확인

terraform plan

(vpc, subnet, vm) 리소스 3개

리소스 배포

terraform apply

리소스 삭제

terraform destory

apply할때 생성되는 .tfstate 파일을 바탕으로 생성된 리소스 삭제

Trouble

Error: Project: required field is not set

terraform apply 를 했을때 어떤 프로젝트인지 명시 되어 있지 않을때 나타나는 에러

해결책

main.tf

provider "google" {
  credentials = "${file("<key.json>")}"
  project     = "<project-name>"
  region      = "asia-northeast3"
}

Provider를 구글로 설정하고 project 설정 후 서비스계정 키 생성 후 입력

profile
꾸준히 새로운 기술을 배워나가는중입니다.

0개의 댓글