如何使用 Terraform for_each 动态创建 ec2 实例

How to dynamically create ec2 instances using a Terraform for_each

我正在尝试使用 for_each 动态创建 ec2 实例。但我收到此错误:

│ Error: Missing required argument
│
│   with aws_instance.ec2-instance,
│   on main.tf line 76, in resource "aws_instance" "ec2-instance":
│   76: resource "aws_instance" "ec2-instance" {
│
│ "instance_type": one of `instance_type,launch_template` must be specified

这是 Terraform:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

variable "instance_name" {
  description = "Value of the Name tag for the EC2 instance"
  type        = string
  default     = "ChangedName"
}

variable "aws_region" {
  description = "AWS Region"
  type        = string
  default     = "eu-west-2"
}

variable "instance_size_small" {
  description = "Instance size small"
  type        = string
  default     = "t3.micro"
}

variable "redundant_count" {
  description         = "Default redundancy - base number of instances to create for redundant services"
  type                = number
  default             = 1
}

variable "ami" {
  description = "Ubuntu 20.04 AMI"
  type        = string
  default     = "ami-0015a39e4b7c0966f"
}

provider "aws" {
  profile = "sandbox"
  region  = var.aws_region
}

variable "environment_name" {
  description         = "Environment Name"
  type                = string
  default             = "dev"
}

variable "client_name" {
  description         = "Client Name"
  type                = string
  default             = "sandbox"
}

variable "instances" {
  description = "Map of modules names to configuration."
  type        = map
  default     = {
    testing-sandbox-dev = {
      instance_count          = 2,
      instance_type           = "t3.micro",
      environment             = "dev"
    },
    testing-sandbox-test = {
      instance_count          = 1,
      instance_type           = "t3.micro",
      environment             = "test"
    }
  }
}

resource "aws_instance" "ec2-instance" {
  ami                = var.ami

  for_each           = var.instances

  tags = {
    Name = "testing-${var.instances.index}.${var.environment_name}.${var.client_name}"
    client = var.client_name
    environment = var.environment_name
  }
}

instance_type 是正在迭代的地图中定义的键之一。那么为什么 Terraform 不接受它呢?

您尚未在 resource "aws_instance" "ec2-instance" 块内定义 instance_type 参数,这是 Terraform 报告错误的地方。

您需要用一个表达式写出您想要设置的每个参数,告诉 Terraform 您希望如何设置它。如果你想设置从你的 for_each 元素派生的值,那么你可以这样写:

resource "aws_instance" "ec2-instance" {
  for_each = var.instances

  ami           = var.ami
  instance_type = each.value.instance_type

  tags = {
    Name = "testing-${var.instances.index}.${var.environment_name}.${var.client_name}"
    client = var.client_name
    environment = var.environment_name
  }
}

你似乎还有另一个问题,关于如何从这个映射的每个元素创建 each.value.instance_count 实例,但我认为最好在你成功填充后作为一个单独的问题 instance_type 每个元素一个实例。