Home > Net >  How to create a dynamic map in Terraform?
How to create a dynamic map in Terraform?

Time:07-15

I have created 2 modules. One for SQS and another for SSM. My SQS creates 4 queues and i am trying to create corresponding entries in the parameter store for their url and arn. I am importing the SSM module inside my SQS module such that it creates the parameters right after SQS creation is done.

This is what my SQS module looks like :-

resource "aws_sqs_queue" "FirstStandardSQSQueue" {
    name = "sqs-${var.stage}-one"
    message_retention_seconds = var.SQSMsgRetention
    redrive_policy = jsonencode({
        deadLetterTargetArn = aws_sqs_queue.FirstDeadLetterQueue.arn
        maxReceiveCount = 2
    })
}

resource "aws_sqs_queue" "FirstDeadLetterQueue" {
    name = "sqs-dead-letter-${var.stage}-one"
    receive_wait_time_seconds = var.SQSRecvMsgWaitTime
}

resource "aws_sqs_queue" "SecondStandardSQSQueue" {
    name = "sqs-${var.stage}-two"
    message_retention_seconds = var.SQSMsgRetention
    redrive_policy = jsonencode({
        deadLetterTargetArn = aws_sqs_queue.SecondDeadLetterQueue.arn
        maxReceiveCount = 3
    })
}

resource "aws_sqs_queue" "SecondDeadLetterQueue" {
    name = "sqs-dead-letter-${var.stage}-two"
    receive_wait_time_seconds = var.SQSRecvMsgWaitTime
}

module "ssm" {
    source = "../ssm/"
   // How do i create a dynamic map???
    for_each = var.Queues 
    name = "/new/${var.stage}/${each.key}"
    type = "SecureString"
    value = "${each.value}"
}

My SSM module looks like this :-

resource "aws_ssm_parameter" "main" {
  name        = var.name
  type        = var.type
  value       = var.value
}

I am trying to create either a map or somehow dynamically be able to pass values in my ssm module using for_each? I tried setting up something like this :-

variable "Queues" {
  type = map
  default = {
    "FirstStandardSQSQueueUrl" = aws_sqs_queue.FirstStandardSQSQueue.url
    "FirstStandardSQSQueueArn" = aws_sqs_queue.FirstStandardSQSQueue.arn
    "SecondStandardSQSQueueUrl" = aws_sqs_queue.SecondStandardSQSQueue.url
    "SecondStandardSQSQueueArn" = aws_sqs_queue.SecondStandardSQSQueue.arn
  }
}

But this is invalid because i keep running into

Error: Variables not allowed  line 40: Variables may not be used here.

Can someone suggest a better/right way to do it? Thank you.

CodePudding user response:

As the error msg writes, you can't have dynamic variables. locals should be used instead.

locals {
  Queues = {
    "FirstStandardSQSQueueUrl" = aws_sqs_queue.FirstStandardSQSQueue.url
    "FirstStandardSQSQueueArn" = aws_sqs_queue.FirstStandardSQSQueue.arn
    "SecondStandardSQSQueueUrl" = aws_sqs_queue.SecondStandardSQSQueue.url
    "SecondStandardSQSQueueArn" = aws_sqs_queue.SecondStandardSQSQueue.arn
  }
}

Then you refer to the value as local.Queues in other parts of your code.

  • Related