Terraform 使用地形变量创建多个元素的正确方法是什么?

Terraform 使用地形变量创建多个元素的正确方法是什么?,terraform,amazon-sqs,terraform-provider-aws,Terraform,Amazon Sqs,Terraform Provider Aws,我正在使用Terraform创建AWS SQS队列。对于每个服务,我需要创建两个队列,一个正常队列和一个错误队列。每个队列的设置基本相同,但我需要首先创建错误队列,以便将其ARN传递给正常队列,作为其重新驱动策略的一部分。与创建10个模块不同,必须有一种更好的方法来循环,只替换名称。所以编程逻辑。。。对于队列前缀中的每个队列,创建错误模块,然后创建常规模块。我确信我只是没有正确地寻找或提出正确的问题 sandbox/main.tf provider "aws" { re

我正在使用Terraform创建AWS SQS队列。对于每个服务,我需要创建两个队列,一个正常队列和一个错误队列。每个队列的设置基本相同,但我需要首先创建错误队列,以便将其ARN传递给正常队列,作为其重新驱动策略的一部分。与创建10个模块不同,必须有一种更好的方法来循环,只替换名称。所以编程逻辑。。。对于队列前缀中的每个队列,创建错误模块,然后创建常规模块。我确信我只是没有正确地寻找或提出正确的问题

sandbox/main.tf

provider "aws" {
  region = "us-west-2"
}

module "hfd_sqs_error_sandbox" {
    source = "../"
    for_each = var.queue_prefixes
    name= each.key+"_Error"
}

module "hfd_sqs_sandbox" {
    source = "../"

    name=hfd_sqs_error_sandbox.name

    redrive_policy = jsonencode({
    deadLetterTargetArn = hfd_sqs_error_sandbox_this_sqs_queue_arn,
    maxReceiveCount     = 3
  })
}
变量.tf

variable "queue_prefixes" {
  description = "Create these queues with the enviroment prefixed"
  type = list(string)
  default = [
    "Clops",
    "Document",
    "Ledger",
    "Log",
    "Underwriting",
    "Wallet",
  ]
}

您可能需要考虑添加一个包装模块,该模块创建正常队列和死信队列。这将使创建资源变得更加容易

考虑以下示例(使用空资源以便于测试):

根模块创建所有队列:

# ./main.tf

locals {
  queue_prefixes = [
      "Queue_Prefix_1",
      "Queue_Prefix_2",
  ]
}

module queue_set {
  source = "./modules/queue_set"

  for_each = toset(local.queue_prefixes)

  name = each.key
}
包装器模块创建一组2个队列:正常+dlq:

# ./modules/queue_set/main.tf

variable "name" {
  type = string
}

module dlq {
  source = "../queue"

  name = "${var.name}_Error"
}

module queue {
  source = "../queue"

  name = var.name
  redrive_policy = module.dlq.id
}
单个队列适合创建两种类型队列的资源:

# ./modules/queue/main.tf

variable "name" {
  type = string
}

variable "redrive_policy" {
  type = string
  default =  ""
}

resource "null_resource" "queue" {
  provisioner "local-exec" {
    command = "echo \"Created queue ${var.name}, redrive policy: ${var.redrive_policy}\""
  }

  # this is irrelevant to the question, it's just to make null resource change every time
  triggers = {
    always_run = timestamp()
  }
}

output "id" {
  value = null_resource.queue.id
}
现在,如果我们运行此堆栈,我们可以看到按正确顺序创建的资源: