我是 Terraform 的新手,正在练习创建我的第一个 terraform。我遇到了一个我不确定的错误,并在网上查看相同的错误,不清楚我应该做什么。感觉这里存在一个基本的“类型”问题。有人可以强调需要做什么以及为什么。
错误:
terraform validate
╷
│ Error: Missing resource instance key
│
│ on variables.tf line 32, in output "public_ip":
│ 32: value = aws_instance.my_rhel9_vm.public_ip
│
│ Because aws_instance.my_rhel9_vm has "count" set, its attributes must be accessed on specific instances.
│
│ For example, to correlate with indices of a referring resource, use:
│ aws_instance.my_rhel9_vm[count.index]
╵
╷
│ Error: Missing resource instance key
│
│ on variables.tf line 37, in output "instance_id":
│ 37: value = aws_instance.my_rhel9_vm.id
│
│ Because aws_instance.my_rhel9_vm has "count" set, its attributes must be accessed on specific instances.
│
│ For example, to correlate with indices of a referring resource, use:
│ aws_instance.my_rhel9_vm[count.index]
╵
main.tf
provider "aws" {
access_key = var.aws_access_key_id
secret_key = var.aws_secret_access_key
region = "us-east-1"
}
resource "aws_instance" "my_rhel9_vm" {
ami = var.ami //RHEL 9 AMI
instance_type = var.type
count = var.number_of_instances
key_name = var.ami_key_pair_name
tags = {
Name = "${var.name_tag}"
}
}
variables.tf
variable "ami" {
type = string
description = "RHEL 9 AMI ID in US-East-1"
default = "ami-05a5f6298acdb05b6"
}
variable "type" {
type = string
description = "Instance Type"
default = "t2.micro"
}
variable "name_tag" {
type = string
description = "Name of the EC2 instance"
default = "My EC2 RHEL 9 instance"
}
variable "number_of_instances" {
type = number
description = "Number of instances to be created"
default = 1
}
variable "ami_key_pair_name" {
type = string
description = "SSH Key Pair"
default = "tomcat"
}
output "public_ip" {
value = aws_instance.my_rhel9_vm.public_ip
description = "Public IP Address of EC2 instance"
}
output "instance_id" {
value = aws_instance.my_rhel9_vm.id
description = "Instance ID"
}
variable "aws_access_key_id" {}
variable "aws_secret_access_key" {}
#locals {
# ami = "ami-05a5f6298acdb05b6"
# type = "t2.micro"
# name_tag = "My EC2 RHEL 9 instance"
#}
错误消息告诉你,由于
aws_instance.my_rhel9_vm
有一个count
属性,所以可以有多个实例,所以你需要指定你引用的是哪个实例。基本上,Terraform 期望aws_instance.my_rhel9_vm
是一个资源数组,您可以使用aws_instance.my_rhel9_vm[0]
、aws_instance.my_rhel9_vm[1]
等索引来引用其中的每个资源。您可以更改
aws_instance.my_rhel9_vm
为aws_instance.my_rhel9_vm[0]
invariables.tf
以获得有效的配置来自Terraform 文档: