Terraform (2) - Updating and Removing

random-developer·2022년 12월 8일
0

Google Cloud

목록 보기
4/4
  1. Create configuration file
terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
    }
  }
}
provider "google" {
  version = "3.5.0"
  project = "<PROJECT_ID>"
  region  = "us-central1"
  zone    = "us-central1-c"
}
resource "google_compute_network" "vpc_network" {
  name = "terraform-network"
}

resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "f1-micro"
  tags         = ["web", "dev"]
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }
  network_interface {
    network = google_compute_network.vpc_network.name
    access_config {
    }
  }
}

access_config{} 으로만 써두면, 인터넷으로부터의 모든 접속을 허가한다는 설정이다.

~ 으로 표시되는건, 테라폼이 리소스를 in-place 로 업데이트하겠다는 의미이다.
-/+ 으로 표시되면, 테라폼이 해당 리소스는 업데이트하는게 불가능하니 replace(remove & re-create) 하겠다는 의미이다.

terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
    }
  }
}
provider "google" {
  version = "3.5.0"
  project = "<PROJECT_ID>"
  region  = "us-central1"
  zone    = "us-central1-c"
}
resource "google_compute_network" "vpc_network" {
  name = "terraform-network"
}

resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "f1-micro"
  tags         = ["web", "dev"]
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }
  network_interface {
    network = google_compute_network.vpc_network.self_link
    access_config {
      nat_ip = google_compute_address.vm_static_ip.address
    }
  }
}

resource "google_compute_address" "vm_static_ip" {
  name = "terraform-static-ip"
}

위 설정에선, nat_ip = google_compute_address.vm_static_ip.address 이라는 interpolation expressions 을통해, vm 과 vm_static_ip 간에 implicit dependency 관계가 있다는걸 테라폼이 추론하여, 리소스 생성의 순서를 결정한다.

terraform destroy
terraform plan -out static_ip
terraform apply "static_ip"

때로는 의존관계가 인프라 레벨에선 알수 없고 어플리케이션 코드등에서 알수있는등의 상황이 있다. 이런 경우엔, 명시적으로 depends_on argument 를 활용한다.

# New resource for the storage bucket our application will use.
resource "google_storage_bucket" "example_bucket" {
  name     = "<UNIQUE-BUCKET-NAME>"
  location = "US"
  website {
    main_page_suffix = "index.html"
    not_found_page   = "404.html"
  }
}
# Create a new instance that uses the bucket
resource "google_compute_instance" "another_instance" {
  # Tells Terraform that this VM instance must be created only after the
  # storage bucket has been created.
  depends_on = [google_storage_bucket.example_bucket]
  name         = "terraform-instance-2"
  machine_type = "f1-micro"
  boot_disk {
    initialize_params {
      image = "cos-cloud/cos-stable"
    }
  }
  network_interface {
    network = google_compute_network.vpc_network.self_link
    access_config {
    }
  }
}
profile
getRandomDeveloper()

0개의 댓글