Using resources created outside of the current Terraform state

Leonardo Loch
3 min readAug 6, 2023

--

I can imagine that many people have already faced the situation where you are working on Terraform and then raised the need to get some attribute from a resource that was not created in the current state or created manually in the cloud. At least for me, that’s super normal. In this article, I’ll show you how we can retrieve a resource created in the cloud that is not in the current state.

We have three different ways to accomplish this.

  • Data Source: allow Terraform to use information defined outside of Terraform, defined by another separate Terraform configuration, or modified by functions.
  • Terraform Remote State data source: Uses the latest state snapshot from a specified state backend to retrieve the root module output values from some other Terraform configuration.
  • Import State: Terraform can import existing infrastructure. This allows you to take resources you have created by some other means and bring them under Terraform management.

Let’s dive deep into those three approaches.

Data Source

Terraform has two different resource structures, which are resource and data source. Resource structures create a resource in the provider and data source you can retrieve the remote resource to the Data Source, let’s see for example aws_intance:

In this example, the aws_intance was not created in the current Terraform State, and we want to reserve a public IP for one specific ec2, but it’s hard to put the instance id as a hardcode, so Terraform can retrieve from the cloud the aws_instace with data source and then we can get from it.

Terraform Remote State Data Source

This approach will demand a little more organization because the target resource already was created in another state and then, you had to use Terraform output and add your resource attribute to be exported. Let’s see it.

Ok, we just created the resource in the state localized foo/boo, and we want to use it in another state.

Now you can get output from another state.

Import State

This approach is just indicated in the case where you have not created the resource in another state, because you could have the same definition of resource in many places, and definitely is not a good thing. You can use it when the resource was created manually in the provider.

Continuing work on AWS instance, let’s imagine that was created on AWS and you want to import to state and then get the attribute id. First, create the resource manifest.

And then run the Terraform Import command, for example:

terraform import aws_instance.web i-12345678

At the end of Terraform resources documentation, almost always there is a way to import state. It’s easy to know how you can accomplish it.

Having seen these three ways to handle Terraform resource that was created outside of the current state, tell me: Which of them do you use the most?

--

--