In this guide, you’ll learn how to import your pre-existing AWS resources into Terraform. This process is essential when some resources—such as an EC2 instance—have been created using other tools or methods and you want to manage them with Terraform. For more context on alternative provisioning tools, refer to the Ansible Advanced Course.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Prerequisites
Before you begin, ensure you have the following:- A unique identifier for the resource you wish to import (for example, the EC2 instance ID).
- The resource’s current configuration information from AWS.
Remember that the Terraform Import command updates only the state file. You must manually update your configuration files to reflect the imported resources.
Step 1: Define an Empty Resource Block
Start by creating an empty resource block in your Terraform configuration file. In this example, we define a resource named “webserver-2”. You can choose any unique name that suits your configuration and state.Step 2: Import the Resource
With your resource block in place, execute the Terraform Import command from your terminal. The syntax is as follows: terraform import [resource address] [unique resource attribute] For an EC2 instance, the resource address is “aws_instance.webserver-2” and the unique resource attribute is the instance ID. Run the command as shown below:Step 3: Update the Resource Block with Configuration
After a successful import, inspect either the AWS management console or the Terraform state file to capture key resource attributes needed for the configuration. An example snippet from the state file might look like this:Step 4: Verify the Configuration
To validate that Terraform correctly recognizes the imported resource, run the Terraform plan. This operation compares your configuration with the current state and should report no changes if everything is in sync.Now that your EC2 instance is under Terraform management, proceed with the usual Terraform workflow for future modifications. Always update your configuration file and run
terraform plan followed by terraform apply to implement changes.