DEV Community

Cover image for Terraform Import Command: Example, Tips and Best Practices
env0 Team for env0

Posted on • Originally published at env0.com

Terraform Import Command: Example, Tips and Best Practices

In this post, we’ll dive into the terraform import command, explaining what it does and how to use it. 

By the end of this blog, you will know how and when to use the terraform import, how to review the imported resource in your .state file, how terraform import differs from terraform state mv, and more.

Disclaimer

All use cases of 'terraform import' discussed here work similarly in OpenTofu, the open-source Terraform alternative. However, to keep thing simple and familiar, we will refer to 'terraform validate' throughout this discussion from now on.

What is Terraform Import

The terraform import command helps you import the resources you’ve created from the console on cloud platforms like AWS, Azure, or GCP, and bring them under your Terraform code. 

Using terraform import command, you can control and track these cloud resources via Terraform without recreating them.

When Should You Use Terraform Import?

When managing existing infrastructure with Terraform CLI, the import command becomes invaluable for seamlessly integrating pre-existing resources into your Terraform state without disruption. 

Here are some scenarios for using the terraform import:

1. Moving to TF from PowerShell, Pulumi, or Shell Scripts 

If an existing infrastructure is managed manually using Powershell, Pulumi, or shell scripts, you can use the terraform import command to bring those resources into your Terraform state. This lets you transition to Terraform without duplicating resources.

2. Syncing State File with Existing Resources 

If you've created resources outside of Terraform, like a Google Cloud Storage (GCS) bucket through the GCP console, you might want to make sure that your Terraform state file matches your actual resources. 

Here, the terraform import command helps you bring these resources into Terraform, preventing differences between your infrastructure in the cloud and your Terraform files.

3. Centralized IaC Management

By importing existing resources from cloud platforms like AWS, Azure, or GCP, you can create, update, and delete resources, track changes, and ensure consistency across your infrastructure from one place.

Terraform Import Syntax and Basics 

The syntax for terraform import is:

terraform import [options] <ADDRESS> <ID>
Enter fullscreen mode Exit fullscreen mode
  • terraform import: The command executed to import a resource into the Terraform.
  • [options]: Represents the optional flags that modify the behavior of the import command (e.g., -lock=false, -var 'foo=bar').
  • ADDRESS: The path to the resource in your Terraform configuration. For example, if you have a GCS bucket resource defined as "google_storage_bucket" "import-env0", its address would be google_storage_bucket.import-env0.
  • ID: A unique identifier of the cloud provider resource, which would be the bucket name for a GCS bucket, such as bucket-not-made-using-terraform-env0.

If you need to create a  Google Cloud Storage (GCS) bucket to test a proof of concept, using the GUI or console might be quicker than writing Terraform code and naming it bucket-not-made-using-terraform-env0

Now, we would like to use this bucket in our Terraform configuration.

To do that, we will write the following code to create a bucket in our main.tf :

resource "google_storage_bucket" "import-env0" {
  name          = "bucket-not-made-using-terraform-env0"
  location      = "US"
  force_destroy = true
}
Enter fullscreen mode Exit fullscreen mode

When we run terraform apply, we get this error:

This error shows that the bucket creation request was successful, but there is a conflict between our Terraform state and the console since it already exists. 

To resolve the issue, you need to bring the existing bucket under our Terraform management.

For that, we will use the following terraform import command:

terraform import google_storage_bucket.import-env0 bucket-not-made-using-terraform-env0
Enter fullscreen mode Exit fullscreen mode

Once you run terraform import, the state file will be updated to include the newly imported resource. 

Flags Used with the Terraform Import 

The terraform import command includes several optional flags that modify its behavior. Here are some commonly used flags: 

-allow-missing-config

This flag allows you to import resources even if they still haven’t been defined in your Terraform code. This is especially useful for initial imports, when the configuration hasn’t been created yet.

For example:

terraform import -allow-missing-config google_storage_bucket.import-env0 bucket-not-made-using-terraform-env0
Enter fullscreen mode Exit fullscreen mode

-input=false

This flag disables interactive prompts during the import process, which is handy for scripting and automation since you won't be asked for input.

For example:

terraform import -input=false google_storage_bucket.import-env0 bucket-not-made-using-terraform-env0
Enter fullscreen mode Exit fullscreen mode

-var 'foo=bar'

This flag sets a variable for the import command, which is useful when your Terraform code uses input variables that need to be specified during the import process.

For example:

terraform import -var 'project_id=content-gen-418510' google_storage_bucket.import-env0 bucket-not-made-using-terraform-env0
Enter fullscreen mode Exit fullscreen mode

The Challenges of Running Terraform Import

The import command is useful for bringing existing infrastructure resources under Terraform configuration, saving time and increasing efficiency. 

However, in some scenarios, it can be challenging to determine the best times to use the import command.

1. Manage Configuration after Import

When you import a resource, Terraform only updates the state file. You still need to write the Terraform configuration code to manage that resource yourself. 

For example, you must write the Terraform configuration after importing a Google Cloud Storage (GCS) bucket. This can be time-consuming and might lead to mistakes if not done properly.

2. Handling Infrastructure Drift

Infrastructure drift occurs when your actual infrastructure differs from what’s defined in your Terraform configuration. 

For example, suppose the S3 bucket was modified through the AWS console to enable versioning (actual state), but this change wasn’t captured in your Terraform configuration (desired state).

In this case, it creates an infrastructure drift between these two states - the desired state and the actual state.

3. Exact Resource IDs Required

For the terraform import command to be run successfully, it requires the correct resource IDs. The import will fail without them, so it's essential to carefully check and provide the proper identifiers.

Reviewing the Imported Resource

After using the terraform import command, you can verify that the resource has been correctly imported in the state file. 

This can be done by identifying the changes in the state file and analyzing the terraform plan output to understand how Terraform will update the imported resource before applying those changes.

1. Identifying Changes and Additions in the State File

Once the resource is imported, you should check the Terraform state file to see the details of the imported cloud resource. This can be done by verifying that all the properties and attributes of the resource have been correctly captured in the state file. 

For instance, if you have imported a Google storage bucket using the command:

terraform import google_storage_bucket.import-env0 bucket-not-made-using-terraform-env0
Enter fullscreen mode Exit fullscreen mode

After the import, you can verify the state by running terraform state show google_storage_bucket.import-env0 command. 

Now, you will be able to see the detailed configuration of the imported resource:

2. Analyzing the Plan Output to Understand Updates

After verifying the state file, the next step is to run the terraform plan command to see how Terraform intends to manage the imported resource moving forward. 

For instance, the output for terraform plan will indicate whether Terraform needs to make any changes to the imported google_storage_bucket resource to match the configuration defined in the GCP cloud provider. 

Here is how an output can look after you run the terraform plan command:

Here, you can see that the value for the force_destroy attribute will be updated, meaning there was a drift between the actual (GCP cloud provider) state and the desired (terraform configuration) state. 

Hence, analyzing is one way to prevent configuration drift and ensure consistency in your infrastructure.

Terraform Import and env0

When you run the terraform import command locally, others might struggle to know when the import was run or who performed the action. It makes it difficult to track changes within your team and avoid conflicts. 

With env0’s ad-hoc tasks feature, every Terraform command is tracked, allowing your team to see who ran the terraform import command and when it was executed, simply by making it a part of your team’s Custom Flows.

To show how this works, we will use env0’s run tasks (ad-hoc tasks) feature to import an existing Storage Bucket from GCP into our env0 integrated Terraform configuration, streamlining the process of bringing resources created via GUI under the Terraform state.

First, add your Terraform configuration files to GitHub:

resource "google_storage_bucket" "import-env0" {
  name          = "bucket-not-made-using-terraform-env0"
  location      = "US"
  force_destroy = true
}
Enter fullscreen mode Exit fullscreen mode

Next, integrate this GitHub repository with env0. When env0 runs the Terraform configuration, it will produce an error stating that the bucket already exists in GCP, since the resource was already created through GUI:

To resolve this error, you can use env0's ad-hoc feature, which will allow you to import the existing GCP bucket into the Terraform state managed by env0.

Start by choosing Run a Task:

Run the terraform import command in env0’s ad-hoc task:

In the env0 console, you will see the task running and the output:

And that’s it! You have now successfully imported the GCP bucket from the cloud into Terraform’s state, allowing you to manage it via env0. 

The result is a better way to ensure consistency and reduce the risk of manual errors, with a flow that will automatically run with every execution of the Terraform configuration. 

Moreover, you will also improve traceability and auditability, as the platform will log every import action (together with any other actions and changes).

Wrapping up

By now, you know why the terraform import command is essential for managing existing resources created using the console on cloud platforms like AWS, Azure, or GCP. 

We have looked at how the terraform import command  centralizes infrastructure management, making tracking and updating resources easier. While it requires precise handling such as manually writing configurations and using exact resource IDs, it ensures an accurate state file. 

Integrating the terraform import command with env0 simplifies the process of keeping your Terraform configuration consistent. 

The command runs automatically whenever you change your Terraform code, reducing errors and enabling teams to track changes, keeping your Terraform state current and reliable. 

Frequently Asked Questions

Q: How do I import into a Terraform module?

To put import commands into a Terraform module, specify the module path in the import command.

For example:

terraform import module.module_name.resource_type.resource_name resource_id
Enter fullscreen mode Exit fullscreen mode




Q: How to import existing resources in the Terraform state file?

Use the terraform import command followed by the resource address and the resource ID.

For example:

terraform import resource_type.resource_name resource_id
Enter fullscreen mode Exit fullscreen mode




Q: What do you need to do before running terraform import?

Before you run the terraform import command, ensure you have:

  • The resource block is defined in your Terraform configuration file
  • Identified the exact resource ID
  • Initialized the working directory with terraform init command

Q: Does Terraform import generate code?

No, terraform import command does not generate code in itself; it only updates the state file to include the existing resource. 

You’ll need to manually write the corresponding resource configuration in your Terraform files.

Q: What is the difference between Terraform Import vs. Terraform State mv?

The commands are sometimes confused, but they perform two different functions. Let's quickly compare the two:

Terraform Import vs. Terraform State mv

Top comments (0)