我有一个 tfvars.json 文件,我想用它来传递我的服务器配置。
{
"test": "test",
"machines": {
"master01": {
"node_type": "master",
"image": "ubuntu-20.04",
"server_type": "cx21",
"location": "nbg1"
},
"master02": {
"node_type": "master",
"image": "ubuntu-20.04",
"server_type": "cx21",
"location": "nbg1"
}
}
}
现在在我的 main.tf 中我想创建实例
############## Provider ################
terraform {
required_providers {
hcloud = {
source = "hetznercloud/hcloud"
version = "1.26.2"
}
}
}
############## Variables ###############
# machines variable
variable "machines" {}
# Token variable
variable "hcloud_token" {
default = "<Secret Key>"
}
# Define Hetzner provider
provider "hcloud" {
token = "${var.hcloud_token}"
}
# Obtain ssh key data
data "hcloud_ssh_key" "ssh_key" {
fingerprint = "<Secret Fingerprint>"
}
# Create Master Server
resource "hcloud_server" "master" {
for_each = {
for name, machine in var.machines :
name => machine
if machine.node_type == "master"
}
name = each.key
image = each.image
server_type = each.server_type
location = each.location
ssh_keys = ["${data.hcloud_ssh_key.ssh_key.id}"]
}
当我跑步时
$ terraform init
$ terraform apply -var-file tfvars.json -state terraform.tfstate -auto-approve
我收到以下错误
╷
│ Error: Invalid "each" attribute
│
│ on main.tf line 40, in resource "hcloud_server" "master":
│ 40: image = each.image
│
│ The "each" object does not have an attribute named "image". The supported
│ attributes are each.key and each.value, the current key and value pair of the
│ "for_each" attribute set.
╵
╷
│ Error: Invalid "each" attribute
│
│ on main.tf line 41, in resource "hcloud_server" "master":
│ 41: server_type = each.server_type
│
│ The "each" object does not have an attribute named "server_type". The
│ supported attributes are each.key and each.value, the current key and value
│ pair of the "for_each" attribute set.
╵
╷
│ Error: Invalid "each" attribute
│
│ on main.tf line 42, in resource "hcloud_server" "master":
│ 42: location = each.location
│
│ The "each" object does not have an attribute named "location". The supported
│ attributes are each.key and each.value, the current key and value pair of the
│ "for_each" attribute set.
我想通过顶部的 tfvars.json 传递我的服务器的配置,但是这个错误阻止我执行。我可能缺少如何将 json 传递给 terraform 中的变量的概念,因此对文档的任何引用也受到高度赞赏。