Skip to main content

Import Resources From Within Terraform Modules

·367 words·2 mins
Mattias Fjellström
Author
Mattias Fjellström
Author · Microsoft MVP · AWS Community Builder · IBM Champion

An upcoming feature in Terraform 1.16.0 is support for import blocks within modules.

This will allow you to prepare your modules for handling imports of existing resources in a way that previously must be managed through root modules.

With this new feature you can do something like the following. Start by adding a new variable block to your module:

variable "import_id" {
  description = "Existing resource ID to import"
  type        = set(string)
  default     = []
}

I create this variable as a set(string) with a default value of []. I do this because if you used a string instead you would always have to provide a value - null would not be acceptable because when you use it in the import block it would generate an error.

Let’s say I have a module for an azurerm_resource_group, something like this:

resource "azurerm_resource_group" "default" {
  name     = var.name
  location = var.location
  tags     = var.tags
}

To this module I would add the following import block:

import {
  for_each = var.import_id

  to = azurerm_resource_group.default
  id = each.value
}

If I leave the import_id variable as an empty set there will be no import, but if I set it to a value like ["<my resource group id>"] a resource will be imported.


You could implement this in all of your modules to always have support for importing resources within the module going forward.

I suspect this feature is here primarily to support Terraform Stacks. I am too lazy to actually test if I could use a module with an import block in Terraform 1.15.x with stacks already, I suspect that it might work because in stacks a component (= a module) is treated as a root module. And as we know import blocks are supported in root modules.

However, if you’ve implemented import blocks in modules before Terraform 1.16.0 they would in that case only be applicable for Terraform stacks and not for anything else. So this new feature will make it possible to reuse the same modules across stacks and workspaces.

But you can’t use ephemeral outputs in modules that you plan to use for stacks though … So there is still not 100% module compatibility between stacks and workspaces.

Related