Search code examples
amazon-web-servicesterraformamazon-sqs

Importing terraform resources into a local block


I have a project that has many SQS queues in AWS that we need to manage. I need to import those queues into my terraform code, but since they're already being used, I can't destroy and recreate them.

Since we have many queues, we use a locals block instead of its resource block to define some of its arguments, such as name, delay_seconds and others. (this is because we don't want to add over 10 resource blocks to import the queues into them and have 100+ lines of code)

Below, example code that we use to create them:

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

locals {
  sqs_queues = {
    test-01 = {
      name          = "test-import-terraform-01"
      delay_seconds = 30
    }
    test-02 = {
      name          = "test-import-terraform-02"
      delay_seconds = 30
    }
  }
}

resource "aws_sqs_queue" "queue" {
  for_each      = local.sqs_queues
  name          = each.value.name
  delay_seconds = each.value.delay_seconds
}

This in turn will create the following queues: test-import-terraform-01 and test-import-terraform-02 as usual. Querying my statefile, i can see then defined as such:

aws_sqs_queue.queue["test-01"]
aws_sqs_queue.queue["test-02"]

Based on that, i would like to import two existing queues to my code: test-import-terraform-03 and test-import-terraform-04. I thought about adding these two maps to my locals block:

test-03 = {
  name          = "test-import-terraform-03"
  delay_seconds = 30
}
test-04 = {
  name          = "test-import-terraform-04"
  delay_seconds = 30
}

But when I try to import them, I get the following error for either queues:

$ terraform import aws_sqs_queue.queue["test-03"] https://sqs.us-east-2.amazonaws.com/12345678910/test-import-terraform-03
zsh: no matches found: aws_sqs_queue.queue[test-03]

Is doing something like that possible?


Solution

  • Your problem is not to do with Terraform, but with shell expansion (note the error message comes from zsh).

    Try quoting your shell arguments properly:

    terraform import 'aws_sqs_queue.queue["test-03"]' 'https://sqs.us-east-2.amazonaws.com/12345678910/test-import-terraform-03'