First time at Zeet?

23 Apr
2024
-
20
min read

How Does Terraform Import Work and Why It Matters for Your DevOps

Understanding Terraform import is essential for effective DevOps practices. Learn how it works and why it's crucial for your projects.

Jack Dwyer

Product
How To
Content
heading2
heading3
heading4
heading5
heading6
heading7

Share this article

What Is Terraform Import Used For?

person understanding terraform import

What is Terraform? Terraform is one of the world’s most popular Infrastructure as Code (IaC) tools. It uses a declarative language and stores the current state of all deployed and managed infrastructure into a file, which can be stored locally or remotely. This file describes current infrastructure configurations and is used to plan and deploy changes via files and modules that define the new state.

How does Terraform import help integrate untracked resources into Terraform management?

Occasionally, there is a need to manage resources via Terraform that were created externally. In such cases, we can use the Terraform Import command to onboard these preexisting resources.

What problems does Terraform import resolve?

1. Import old resource

Organizations can import resources created with alternative tools or methods

2. Import resources created outside Terraform

When Terraform is deployed, it may not have been universally adopted. As such, there may have been infrastructure additions/amendments made outside of Terraform.

3. Loss of Terraform state file

The state file can be deleted or become irreversibly corrupt.

4. Re-factoring / Amending Terraform code structure

As an environment scales, there may be a need to re-factor or re-structure Terraform modules and other constructs.

Why Use the Terraform Import Command?

uses of terraform import

Terraform Import offers several critical benefits that make the tool invaluable.

  • It helps prevent resource duplication, making it easier to manage your infrastructure. This is especially useful if you are working with legacy issues in your infrastructure that you wish to manage using Terraform.
  • Terraform Import ensures all your resources are managed consistently, regardless of their origin, and helps prevent manual configuration drift. It also maintains a single source of truth for all your infrastructure resources. 
  • Terraform Import allows you to adopt Terraform incrementally for existing resources without having to start from scratch. This means you can gradually manage your infrastructure with Terraform without causing any disruptions.
  • Importing resources using Terraform Import allows you to collaborate with your team using a shared version-controlled Terraform state. This enhances team collaboration and ensures every team member is working with the same infrastructure definitions, promoting a higher level of consistency and accuracy among your team.

By using Terraform Import, you can effectively manage your infrastructure, prevent resource duplication, and ensure your team has a shared understanding of your infrastructure. Terraform Import is a valuable tool for ensuring configuration consistency, facilitating incremental adoption, and enhancing collaboration.

Zeet: Get Seamless Cloud Deployments

Zeet helps you to get more from your cloud, Kubernetes, and Terraform investments and helps your engineering team become strong individual contributors through our CI/CD & deployment platform. 

Contact Zeet to learn more about how Zeet can help you get seamless cloud deployments every time, and help your team to become a top-performing engineering team.

Zeet Terraform and Helm Product Overview

Related Reading

How to Use Terraform Import to Manage Existing Resources

programming commands for terraform import

Importing Resources

Prepare the EC2 instance

Create an EC2 instance in your AWS account. An example of the details of the EC2 instance is as follows:

Name: MyVM

Instance ID: i-0b9be609418aa0609

Type: t2.micro
VPC ID: vpc-1827ff72

Create main.tf and set provider configuration

In your desired path, create `main.tf` and configure the AWS provider. The file should look something like this:

hcl // Provider configuration Terraform {  required_providers {    aws = {      source  = "hashicorp/aws"      version = "~> 3.0"    }  } } provider "aws" {  region = "eu-central-1" }

Run `Terraform init` to initialize the Terraform modules.

Write config for the resource to be imported

Add the following configuration for the EC2 instance to the `main.tf` file

hcl resource "aws_instance" "myvm" {  ami           = "unknown"  instance_type = "unknown" }

Run the import command

Run the import command to map the aws_instance.myvm configuration to the EC2 instance using the ID:

bash Terraform import aws_instance.myvm

Observe state files and plan output

After importing, observe the state file and run `Terraform plan` to see if there are any changes needed.

Improve config to avoid replacement

Adjust the configuration to avoid the replacement of the EC2 instance by updating the `ami` attribute to the correct value.

Improve config to avoid changes

Further align the resource block to avoid changes highlighted in the plan output.

Importing Modules

Terraform Import AWS VPC module example

To import a resource in a module's configuration, run the command as follows:

bash Terraform import module.vpc.aws_vpc.this

Importing IAM roles using for_each

Define a Terraform configuration for roles and then import them using the following commands:

bash Terraform import "aws_iam_role.import_roles[\"import_role1\"]" import_role1Terraform import "aws_iam_role.import_roles[\"import_role2\"]" import_role2

Terraform 1.5 import - How to use the import block

To use the import block in Terraform 1.5, define the import block in your code to allow import operations. For example, you can import S3 buckets using the import block as follows:

hcl import {  id = "import-bucket-tf15"  to = aws_s3_bucket.this } import {  id = "import-bucket-tf15-2"  to = aws_s3_bucket.this2 }```


After running `Terraform plan`, review the generated configuration and then apply it to add the resources to the state.

4 Common Issues When Using Terraform Import

understanding issues related to terraform import

1. Error-prone Manual Configuration

When using Terraform import, one of the challenges is that it does not automatically generate corresponding configuration files for the imported resources. This means that you must manually create the configuration, which can be both time-consuming and prone to errors. You would have to collect all the necessary attributes from the external resource and write them as a configuration file which may result in mistakes and omissions if not done correctly.

2. Require Exact Resource Ids

Terraform needs to know the exact resource ID of the resource you're trying to import. This can be a challenge, especially when dealing with resources that have dependencies or require a tuple of identifiers. 

For example, to import an AWS autoscaling policy, you would need the autoscaling group and scaling policy names. If you are importing resources with dependencies, you have to know the actual names of these resources from the AWS console and execute the import command multiple times.

3. Handling Drifts

After importing resources using Terraform import, you should run the 'Terraform Plan' command to ensure that there are no drifts between the configuration and the real-world resource. A 'drift' refers to a discrepancy between the desired state in the configuration file and the actual state of the resource. 

If there are any differences, the physical resource may be updated, deleted, or created. Another challenge is the possibility of missing attribute values, which can lead to drift. You should refer to the resource documentation before importing to identify default values and ensure they are included in the configuration file.

4. Destruction of Resources

One of the risks of using Terraform import is the potential to destroy existing resources if mistakes are made in the configuration. For instance, if you provide an incorrect AMI ID, Terraform may destroy the existing EC2 instance and create a new one. 

It's essential to review the 'Terraform Plan' output to ensure that no resources are unintentionally destroyed. Be cautious when using the 'Terraform Apply' command, especially with the '--auto-approve' option, as this could lead to unintended destruction of resources.

Related Reading

10 Best Practices for Using Terraform Import

best practices related to terraform import

1. Planning is crucial

You must include not only the resources you intend to import but also any resources that interact with those, and so on

2. Write your Terraform code

As part of the planning process, write your Terraform code before any changes to help quicken deployment. When importing multiple resources, automate the import commands via a script

3. Schedule all changes

Schedule all changes with your colleagues and ensure other modifications are suspended, especially when using CI/CD pipelines for deployment

4. Consider stopping tasks

If using CI/CD pipelines, consider stopping these tasks and running the import commands (and subsequent plan and apply commands) manually. Doing so will give you more time to review any changes and allow colleagues to critique your plan. Triggering any Terraform processes you’re not aware of can also be prevented this way

5. Carry out import tasks in small batches

Carry out import tasks in small batches rather than in bulk. Use the Terraform plan and apply commands regularly to ensure no unexpected consequences

6. Keep your state file in a shared storage

It’s generally recommended to keep your Terraform state file in a shared storage location rather than on your local machine for a few reasons

Consistency

A shared state file ensures that everyone uses the same state of the infrastructure. If each team member has a copy of the state file, it can be challenging to ensure consistency across different environments and prevent drift.

Backup and Recovery

A shared storage location provides a central point for backing up and recovering your state file. If your local machine crashes or your state file becomes corrupted, storing a backup in a shared location can save you time and effort.

Remote Execution

Storing state files on shared storage makes running Terraform in a remote environment, such as a build server or a continuous integration/continuous deployment (CI/CD) pipeline, easier.

Using a shared storage location for your Terraform state file helps ensure consistency, collaboration, and ease of use, making it a critical best practice when using Terraform for infrastructure management.

7. Back up frequently

Back up the state file frequently, allowing for easy recovery should anything go wrong

8. Use Terraform workspaces

Use Terraform workspaces to limit the “blast radius” of any Terraform state issues and reduce the complexity of recovery

9. Proper documentation

Keeping good documentation about imported Terraform resources is vital in the long run. If new members join the team in the future, they can refer to the documentation and learn about imported resources and the process of managing those resources.

10. Consider why you are importing resources

Carefully consider why you are importing the resources – is it essential? Balance the risk and reward of importing the resource vs. managing them outside Terraform.

Related Reading

Zeet Contact Us

Get Control of Your Releases With Zeet's CI/CD & Deployment Platform for Kubernetes and Terraform

Zeet is a powerful tool that helps you make the most of your cloud, Kubernetes, and Terraform investments. Our platform provides you with seamless cloud deployments that reduce manual errors and ensure you get the most out of your resources.

Maximize Your Team's Efficiency with Zeet's CI/CD Platform

By leveraging Zeet, your engineering team can become top-performing individual contributors. Our CI/CD & deployment platform empowers your team to make the most of cloud deployments and Kubernetes, allowing them to focus on delivering value to your organization.

Optimize Your Cloud Infrastructure

Zeet is the key to unlocking the potential of your cloud investments. Contact us today to learn more about how Zeet can help you optimize your cloud infrastructure and empower your team to achieve success.

Subscribe to Changelog newsletter

Jack from the Zeet team shares DevOps & SRE learnings, top articles, and new Zeet features in a twice-a-month newsletter.

Thank you!

Your submission has been processed
Oops! Something went wrong while submitting the form.