Terraform 安裝與運行

Terraform 安裝與運行

Terraform 是由 HashiCorp 開發的一套 Infrastructure as Code 工具。

這裡記錄 Terraform 基本安裝及設定的步驟,示範如何在 GCP 建立一個 instance。

Mac install terraform

依照官方文件,透過以下步驟安裝 terraform

brew tap hashicorp/tap
brew install hashicorp/tap/terraform
brew upgrade hashicorp/tap/terraform
terraform -help
terraform -help plan

建立服務帳戶與金鑰

接著,我們需要在 GCP 建立一個 json 憑證,之後會透過這個憑證來讓 terraform 可以來獲得授權。

(1) 建立服務帳戶

先前往 GCP > API 和服務 > 憑證 > 建立憑證 > 服務帳戶

帳戶名稱:treeaform-compouter-engine-service (可自行填寫)

將專案存取權授予這個服務帳戶: Compute Engine > Compute 管理員

點選建立

(2) 建立金鑰

在服務帳戶列表,點選剛剛新增的帳戶 > 新增金鑰 > JSON > 建立

點選建立後,會下載一個 Json 格式的金鑰檔案,更名為 gcp-terraform-account-for-computer-engine.json

建立 terraform

建立一個 vim terrafform.tf 檔案,內容:

provider "google" {
  credentials = "${file("gcp-terraform-account-for-computer-engine.json")}"
  project = "aerial-matrix-286317"
  region  = "us-central1"
  zone    = "us-central1-c"
}

resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "f1-micro"

  boot_disk {
    initialize_params {
      image = "centos-cloud/centos-7"
    }
  }

  network_interface {
    # A default network is created for all GCP projects
    network = google_compute_network.vpc_network.self_link
    access_config {
    }
  }
}

resource "google_compute_network" "vpc_network" {
  name                    = "terraform-network"
  auto_create_subnetworks = "true"
}

初始化 terraform,可以下載所需要的 plugins

terraform init

輸出結果

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/google...
- Installing hashicorp/google v3.51.0...
- Installed hashicorp/google v3.51.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.


Warning: Interpolation-only expressions are deprecated

  on terrafform.tf line 2, in provider "google":
   2:   credentials = "${file("gcp-terraform-account-for-computer-engine.json")}"

Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the "${ sequence from the start and the }"
sequence from the end of this expression, leaving just the inner expression.

Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.

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 plan 查看目前變更

terraform plan

接著,透過 terraform apply 開始運行部署,在執行時會比較目前設定檔案與實際 infra 的差異,來決定要部署的項目。

因此,如果有變更設定,同樣在執行 terraform apply 就可以更新。

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:

  # 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                 = "terraform-instance"
      + project              = (known after apply)
      + self_link            = (known after apply)
      + tags_fingerprint     = (known after apply)
      + zone                 = (known after apply)

      + 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)
            }
        }

      + network_interface {
          + name               = (known after apply)
          + network            = (known after apply)
          + network_ip         = (known after apply)
          + subnetwork         = (known after apply)
          + subnetwork_project = (known after apply)

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

      + scheduling {
          + automatic_restart   = (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)
            }
        }
    }

  # google_compute_network.vpc_network will be created
  + resource "google_compute_network" "vpc_network" {
      + auto_create_subnetworks         = true
      + delete_default_routes_on_create = false
      + gateway_ipv4                    = (known after apply)
      + id                              = (known after apply)
      + mtu                             = (known after apply)
      + name                            = "terraform-network"
      + project                         = (known after apply)
      + routing_mode                    = (known after apply)
      + self_link                       = (known after apply)
    }

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


Warning: Interpolation-only expressions are deprecated

  on terrafform.tf line 2, in provider "google":
   2:   credentials = "${file("gcp-terraform-account-for-computer-engine.json")}"

Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the "${ sequence from the start and the }"
sequence from the end of this expression, leaving just the inner expression.

Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:

這時出現 Enter a value: ,請輸入 yes

CVT2HUGO: 確認要部署,送出後就會繼續開始建立 infra
google_compute_network.vpc_network: Creating...
google_compute_network.vpc_network: Still creating... [10s elapsed]
google_compute_network.vpc_network: Still creating... [20s elapsed]
google_compute_network.vpc_network: Still creating... [30s elapsed]
google_compute_network.vpc_network: Still creating... [40s elapsed]
google_compute_network.vpc_network: Creation complete after 45s [id=projects/aerial-matrix-286317/global/networks/terraform-network]
google_compute_instance.vm_instance: Creating...
google_compute_instance.vm_instance: Still creating... [10s elapsed]
google_compute_instance.vm_instance: Creation complete after 15s [id=projects/aerial-matrix-286317/zones/us-central1-c/instances/terraform-instance]

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

建立完成後,就可以在看到新建立的 terraform-instance

最後,我們在執行 terraform plan 來驗證目前 infrastructure

terraform plan

參考:

https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started