Предоставить экземпляр виртуальной машины GCP со статическим IP-адресом через Terraform - PullRequest
0 голосов
/ 21 марта 2019

Я отредактировал файл main.tf и variable.tf, как предложено @ Claire Bellivier , но все еще получаю ту же ошибку, пожалуйста, посмотрите. Main.tf:

# Path to the authentification to GCP json file
provider "google" {
 credentials = "${file("${var.path_gcp_auth_json_file}")}"
 version     = "~> 2.2"

}

resource =  "google_compute_address" "test-static-ip-address" {
 count  = "${var.gcp_ip_count}"
 name   = "${var.gcp_project_id}-gke-ip-${count.index}"
 region = "${var.region}"
 }

resource "google_compute_instance" "tests" {
 name         = "project-tests"
 project      = "xyz"
 machine_type = "f1-micro"
 zone         = "us-west1-a"

 tags = ["gcp"]

 boot_disk {
 initialize_params {
  image = "ubuntu-os-cloud/ubuntu-1804-lts"
   }
 }

network_interface {
 network = "default"

  access_config {
   nat_ip = "${google_compute_address.test-static-ip-address.address}"

   }
 }

  metadata {
   sshKeys = "local:${file(var.ssh_public_key_filepath)}"
  }

}

resource "google_compute_firewall" "firewalls" {
 name    = "firewalls"
 project = "video-library-228319"
 network = "default"

 allow {
  protocol = "tcp"
  ports = ["80", "443"]
 }

  source_ranges = ["0.0.0.0/0"]
}

Variable.tf

# Path to the authentification to GCP json file
variable "path_gcp_auth_json_file" {
  description = "Path to the authentication JSON file"
 default = "account.json"
}


variable "ssh_public_key_filepath" {
 description = "Filepath to local ssh public key"
 type = "string"

 default = "local.pub"
}

variable "gcp_ip_count" {
 default = "1"
}

variable "gcp_project_id" {
  default = "xyz"
}

variable "region" {
 default ="us-west1-a"
}

Ошибка: неизвестный ключ корневого уровня: test-static-ip-address Ошибка: конфигурация ресурса google_compute_instance.tests: неизвестный ресурс google_compute_address.test-static-ip-address ', указанный в переменной google_compute_address.test-static-ip-address.address

Пожалуйста, помогите

Ответы [ 2 ]

0 голосов
/ 24 марта 2019

Не могли бы вы скопировать, вставить этот и удалить второй блок?

resource "google_compute_address" "test-static-ip-address" {
  count  = "${var.gcp_ip_count}"
  name   = "${var.gcp_project_id}-gke-ip-${count.index}"
  region = "${var.region}"
}

Как уже упоминалось, = слишком много, поэтому он не может работать.

Шаблон всегда для файла main.tf:

resource "<kind of GCP Resource>" "<the name of your resources> {
  <list of arguments you need>
  # ...
}

Небольшая хитрость, если вам нужна помощь с синтаксисом Terraform, вы можете выполнить некоторые тесты с этими командами: terraform formatчтобы получить правильный отступ, и terraform validate, чтобы убедиться, что в вашем коде все правильно.

0 голосов
/ 21 марта 2019

Прежде всего, вы можете попробовать настроить провайдера Google Cloud следующим образом:

# Configure the Google Cloud provider
provider "google" {
  credentials = "${file("${var.path_gcp_auth_json_file}")}"
  version     = "~> 2.2"
}

С файлом variables.tf

# Path to the authentification to GCP json file 
variable "path_gcp_auth_json_file" {
  description = "Path to the authentication JSON file"
  default = "YOUR_PATH_TO_YOUR_JSON_KEY"
}

, если вы хотите быть быстрым ине добавляйте значения default в файл terraform.tfvars.

Во-вторых, вы пропустили { в конце ресурса tests:

resource "google_compute_instance" "tests" {
  name         = "project-tests"
  project      = "video-library-228319"
  machine_type = "f1-micro"
  zone         = "us-west1-a"

  tags = ["gcp"]

  boot_disk {
    initialize_params {
      image = "ubuntu-os-cloud/ubuntu-1804-lts"
    }
  }

  network_interface {
    network = "default"

    access_config {
      nat_ip = "${google_compute_address.test-static-ip-address.address}"
    }
  }
}

И затем, для генерации IP-адресов вам необходимо правильно объявить вычислительный ресурс Terraform:

# Generate IPs
resource "google_compute_address" "test-static-ip-address" {
  count  = "${var.gcp_ip_count}"
  name   = "${var.gcp_project_id}-gke-ip-${count.index}"
  region = "${var.region}"
}

Каждый "${var.[...] должен ссылаться на variables.tf, упомянутый ранее.Значение count зависит от того, сколько IP-адресов вам нужно.Надеюсь, это поможет.

...