Search code examples
terraformazure-rm

How to automatically import resource to Terraform state?


I want to develop a single Terraform module to deploy my resources, with the resources being stored in separate YAML files. For example:

# resource_group_a.yml
name: "ResourceGroupA"
location: "westus"

# resource_group_b.yml
name: "ResourceGroupB"
location: "norwayeast"

And the following Terraform module:

# deploy/main.tf

variable source_file {
  type = string # Path to a YAML file
}

locals {
  rg = yamldecode(file(var.source_file))
}

resource "azurerm_resource_group" "rg" {
  name     = local.rg.name
  location = local.rg.location
}

I can deploy the resource groups with:

terraform apply -var="source_file=resource_group_a.yml"
terraform apply -var="source_file=resource_group_b.yml"

But then I run into 2 problems, due to the state that Terraform keeps about my infrastructure:

  • If I deploy Resource Group A, it deletes Resource Group B and vice-versa.
  • If I manually remove the .tfstate file prior to running apply, and the resource group already exists, I get an error:
A resource with the ID "/..." already exists - to be managed via Terraform
this resource needs to be imported into the State.

  with azurerm_resource_group.rg,
  on main.tf line 8 in resource "azurerm_resource_group" "rg"

I can import the resource into my state with

terraform import azurerm_resource_group.reg "/..."

But it's a long file and there may be multiple resources that I need to import.


So my questions are:

  • How to keep the state separate between the two resource groups?
  • How to automatically import existing resources when I run terraform apply?

Solution

  • How to keep the state separate between the two resource groups?

    I recommend using Terraform Workspaces for this, which will give you separate state files, each with an associated workspace name.

    How to automatically import existing resources when I run terraform apply?

    That's not currently possible. There are some third-party tools out there like Terraformer for accomplishing automated imports, but in my experience they don't work very well, or they never support all the resource types you need. Even then they wouldn't import resources automatically every time you run terraform apply.