如何使用terraform加载平衡谷歌计算实例?

时间:2018-01-14 20:29:13

标签: google-cloud-platform terraform

在我的terraform配置文件中,我定义了我的资源:

resource "google_compute_instance" "test" {
    ...
    count = 2
}

我现在想要的是创建负载均衡器,它将在我的谷歌计算实例的两个实例之间取得平衡。不幸的是,我无法在文档中找到与此任务相关的任何内容。似乎google_compute_target_poolgoogle_compute_lb_ip_ranges与我的问题无关。

2 个答案:

答案 0 :(得分:1)

您必须使用此地形document上指示的“转发规则”。要使用负载平衡和协议转发,必须创建将流量定向到特定目标实例的转发规则。您可以在Cloud Platform上使用转发规则here

答案 1 :(得分:0)

在通常情况下,您可以使用以下内容:

resource "google_compute_instance" "test" {
    name         = "nlb-node${count.index}"
    zone         = "europe-west3-b"
    machine_type = "f1-micro"
    count        = 2

    boot_disk {
        auto_delete = true
        initialize_params {
            image       = "ubuntu-os-cloud/ubuntu-1604-lts"
            size        = 10
            type        = "pd-ssd"
        }
    }

    network_interface {
        subnetwork = "default"

        access_config {
            nat_ip = ""
        }
    }

    service_account {
        scopes = ["userinfo-email", "compute-ro", "storage-ro"]
    }
}

resource "google_compute_http_health_check" "nlb-hc" {
    name               = "nlb-health-checks"
    request_path       = "/"
    port               = 80
    check_interval_sec = 10
    timeout_sec        = 3
}

resource "google_compute_target_pool" "nlb-target-pool" {
    name             = "nlb-target-pool"
    session_affinity = "NONE"
    region           = "europe-west3"

    instances = [
        "${google_compute_instance.test.*.self_link}"
    ]

    health_checks = [
        "${google_compute_http_health_check.nlb-hc.name}"
    ]
}

resource "google_compute_forwarding_rule" "network-load-balancer" {
    name                  = "nlb-test"
    region                = "europe-west3"
    target                = "${google_compute_target_pool.nlb-target-pool.self_link}"
    port_range            = "80"
    ip_protocol           = "TCP"
    load_balancing_scheme = "EXTERNAL"
}

您可以通过${google_compute_forwarding_rule.network-load-balancer.ip_address}

获取负载均衡器的外部IP。
// output.tf
output "network_load_balancer_ip" {
    value = "${google_compute_forwarding_rule.network-load-balancer.ip_address}"
}