|
| 1 | +# See https://cloud.google.com/compute/docs/load-balancing/network/example |
| 2 | + |
| 3 | +provider "google" { |
| 4 | + region = "${var.region}" |
| 5 | + project = "${var.project_name}" |
| 6 | + account_file = "${file(var.account_file_path)}" |
| 7 | +} |
| 8 | + |
| 9 | +resource "google_compute_http_health_check" "default" { |
| 10 | + name = "tf-www-basic-check" |
| 11 | + request_path = "/" |
| 12 | + check_interval_sec = 1 |
| 13 | + healthy_threshold = 1 |
| 14 | + unhealthy_threshold = 10 |
| 15 | + timeout_sec = 1 |
| 16 | +} |
| 17 | + |
| 18 | +resource "google_compute_target_pool" "default" { |
| 19 | + name = "tf-www-target-pool" |
| 20 | + instances = ["${google_compute_instance.www.*.self_link}"] |
| 21 | + health_checks = ["${google_compute_http_health_check.default.name}"] |
| 22 | +} |
| 23 | + |
| 24 | +resource "google_compute_forwarding_rule" "default" { |
| 25 | + name = "tf-www-forwarding-rule" |
| 26 | + target = "${google_compute_target_pool.default.self_link}" |
| 27 | + port_range = "80" |
| 28 | +} |
| 29 | + |
| 30 | +resource "google_compute_instance" "www" { |
| 31 | + count = 3 |
| 32 | + |
| 33 | + name = "tf-www-${count.index}" |
| 34 | + machine_type = "n1-standard-1" |
| 35 | + zone = "${var.region_zone}" |
| 36 | + tags = ["www-node"] |
| 37 | + |
| 38 | + disk { |
| 39 | + image = "ubuntu-os-cloud/ubuntu-1204-precise-v20150625" |
| 40 | + } |
| 41 | + |
| 42 | + network_interface { |
| 43 | + network = "default" |
| 44 | + access_config { |
| 45 | + # Ephemeral |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + metadata { |
| 50 | + sshKeys = "ubuntu:${file("~/.ssh/gcloud_id_rsa.pub")}" |
| 51 | + startup-script = <<SCRIPT |
| 52 | +apt-get -y update |
| 53 | +apt-get -y install nginx |
| 54 | +HOSTNAME=$(hostname | tr -d "\n") |
| 55 | +IP=$(curl -s -H "Metadata-Flavor:Google" http://metadata/computeMetadata/v1/instance/network-interfaces/0/ip) |
| 56 | +echo "Welcome to ${count.index} - $HOSTNAME ($IP)" > /usr/share/nginx/www/index.html |
| 57 | +service nginx start |
| 58 | +SCRIPT |
| 59 | + } |
| 60 | + |
| 61 | + service_account { |
| 62 | + scopes = ["https://www.googleapis.com/auth/compute.readonly"] |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +resource "google_compute_firewall" "default" { |
| 67 | + name = "tf-www-firewall" |
| 68 | + network = "default" |
| 69 | + |
| 70 | + allow { |
| 71 | + protocol = "tcp" |
| 72 | + ports = ["80"] |
| 73 | + } |
| 74 | + |
| 75 | + source_ranges = ["0.0.0.0/0"] |
| 76 | + target_tags = ["www-node"] |
| 77 | +} |
0 commit comments