How to set up GKE via terraform

前置條件

  • terraform
  • GCP

撰寫 terraform

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# main.tf

terraform {
required_providers {
google = {
source = "hashicorp/google"
}
}
}

provider "google" {
credentials = file("sean-side-tf-admin-sa.json")
project = "sean-side"
region = "asia-east1"
zone = "asia-east1-c"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# gke.tf

resource "google_service_account" "sean-side-gke-default-sa" {
account_id = "sean-side-gke-default-sa"
display_name = "GKE default service account"
}

resource "google_container_cluster" "sean-side-prod-cluster" {
name = "sean-side-prod-cluster"
location = "asia-east1-c"
remove_default_node_pool = true
initial_node_count = 1

timeouts {
create = "30m"
update = "40m"
}
}

resource "google_container_node_pool" "sean-side-prod-nodes" {
name = "sean-side-prod-nodes"
location = "asia-east1-c"
cluster = google_container_cluster.sean-side-prod-cluster.name
node_count = 2

autoscaling {
max_node_count = 3
min_node_count = 1
}

node_config {
preemptible = true
machine_type = "e2-medium"

service_account = google_service_account.sean-side-gke-default-sa.email
oauth_scopes = [
"https://www.googleapis.com/auth/cloud-platform"
]
labels = {
env = "prod"
proj = "side"
}
}
}