본문 바로가기
CSP (Cloud Service Provider)/GCP

GCP SDK-terraform 연결

by BTC_안민규 2022. 7. 22.

 

 

 

google cloud sdk 공식문서입니다. 해당 문서에 들어가서 sdk 설치 프로그램을 받아 설치해주세요.

sdk를 사용하려면 PC에 Python 도 설치되어있어야하는데 sdk를 설치하는 과정에서 bundle python을 설치하게 되어있습니다. 이번 실습에서는 기본설정에 대해서는 건들지않고 설치하도록 하겠습니다.

sdk에 연결되어 있는 계정과 프로젝트id 그리고 컨피규레이션을 어떻게할건지 묻습니다. 사용하고자하는 아이디와 프로젝트가 맞다면 1번을 선택해주시고 아니면 2번을 눌러 나오는 안내에 맞게 설정하시면 됩니다.

혹여나 실수로 잘못된 아이디나 프로젝트을 그대로 사용하셨더라도

Cloud SDK> gcloud init

위의 명령어를 통해 다시 설정하는 것이 가능합니다.

이것으로 1차적인 설치가 완료되었습니다. 이제는 vscode로 가보겠습니다.

01_main.tf 파일을 생성하여 아래의 코드를 입력하세요.

provider "google" { }

porivder를 통해 gcp를 사용하겠다고 선언하였습니다. 우선 init를 진행하세요 보통은 문제가 없을겁니다.

C:\Users\USER\gcptf\01_GCP>terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/google...
- Installing hashicorp/google v3.89.0...
- Installed hashicorp/google v3.89.0 (signed by HashiCorp)

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.

default vpc에 간단한 instance를 올려보도록 하겠습니다.

02_vm.tf 를 생성하여 아래의 코드를 입력해주세요.

 } }
resource "google_compute_instance" "vm_instance" {
    name         = "mkahn-instance"
    machine_type = "f1-micro"
    zone         = "asia-northeast3-a"
  boot_disk {
    initialize_params {
      image = "centos-cloud/centos-7"
    }
  }

  network_interface {
    # A default network is created for all GCP projects
    network = "default"
    access_config {
    }
  }
   
}
C:\Users\USER\gcptf\01_GCP>terraform plan
╷
│ Error: Attempted to load application default credentials since neither `credentials` nor `access_token` was set in the provider block.  No credentials loaded. To use your gcloud credentials, run 'gcloud auth application-default login'.  Original error: google: could not find default credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
│
│   with provider["registry.terraform.io/hashicorp/google"],
│   on 01_main.tf line 1, in provider "google":
│    1: provider "google" {

이러한 오류가 나올텐데 당황하지않고 차분히 읽어보면 무슨말인지 보입니다. 문서를 참조하여 해결해도 좋겠지만 저는 terraform에서 작성한 gcp문서를 바탕으로 해결하겠습니다 sdk에 다음을 입력해주세요

cloud auth application-default login

로그인을 하라는 화면이 나올텐데 진행하시면 됩니다. 로그인이 끝나셨다면 다시 plan을 진행해주세요.

C:\Users\USER\gcptf\01_GCP>terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  + create

Terraform will perform the following actions:

  # google_compute_instance.vm_instance will be created
  + resource "google_compute_instance" "vm_instance" {
      + can_ip_forward       = false
      + cpu_platform         = (known after apply)
      + current_status       = (known after apply)
      + deletion_protection  = false
      + guest_accelerator    = (known after apply)
      + id                   = (known after apply)
      + instance_id          = (known after apply)
      + label_fingerprint    = (known after apply)
      + machine_type         = "f1-micro"
      + metadata_fingerprint = (known after apply)
      + min_cpu_platform     = (known after apply)
      + name                 = "mkahn-instance"
      + project              = (known after apply)
      + self_link            = (known after apply)
      + tags_fingerprint     = (known after apply)
      + zone                 = "asia-northeast3-a"

      + boot_disk {
          + auto_delete                = true
          + device_name                = (known after apply)
          + disk_encryption_key_sha256 = (known after apply)
          + kms_key_self_link          = (known after apply)
          + mode                       = "READ_WRITE"
          + source                     = (known after apply)

          + initialize_params {
              + image  = "centos-cloud/centos-7"
              + labels = (known after apply)
              + size   = (known after apply)
              + type   = (known after apply)
            }
        }

      + confidential_instance_config {
          + enable_confidential_compute = (known after apply)
        }

      + network_interface {
          + ipv6_access_type   = (known after apply)
          + name               = (known after apply)
          + network            = "default"
          + network_ip         = (known after apply)
          + stack_type         = (known after apply)
          + subnetwork         = (known after apply)
          + subnetwork_project = (known after apply)

          + access_config {
              + nat_ip       = (known after apply)
              + network_tier = (known after apply)
            }
        }

      + reservation_affinity {
          + type = (known after apply)

          + specific_reservation {
              + key    = (known after apply)
              + values = (known after apply)
            }
        }

      + scheduling {
          + automatic_restart   = (known after apply)
          + min_node_cpus       = (known after apply)
          + on_host_maintenance = (known after apply)
          + preemptible         = (known after apply)

          + node_affinities {
              + key      = (known after apply)
              + operator = (known after apply)
              + values   = (known after apply)
            }
        }
    }

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

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if
you run "terraform apply" now.

그리고 apply 까지 진행한다면 정상적으로 instance가 올라가는 모습을 볼 수 있습니다.

댓글