Skip to main content
Welcome to this step-by-step guide on importing existing AWS resources into OpenTofu. By the end of this tutorial, you’ll know how to discover unmanaged resources, import an EC2 instance, and manage it alongside your Terraform code.

Prerequisites

  • OpenTofu CLI installed
  • AWS CLI configured for LocalStack (or your AWS account)
  • A project directory named project-jade

1. Initialize the Project Directory

Open your terminal and navigate to the project-jade folder:

2. Review the Existing Terraform Configuration

Below is the current HCL setup. It defines an AWS provider, global variables, and a set of EC2 instances:

3. Identify Unmanaged Resources

To list all resources tracked in state versus your code, run:
Compare this output with your HCL.
Question: Which resource appears in the state but not in the configuration?
Answer: An EC2 instance (e.g., jade-agent) that wasn’t defined in code.

4. Provision the SSH Key Pair

OpenTofu did not create the jade key pair—it was generated via AWS CLI:
This command writes the private key to jade.pem.
Keep your private keys out of version control. Add jade.pem to .gitignore.

5. Locate the External EC2 Instance ID

Another EC2 instance named Jade-MW was created manually. Retrieve its Instance ID:
The image shows a split screen with a task description on the left about creating and inspecting an AWS EC2 instance using the AWS CLI, and a code editor on the right displaying Terraform configuration files for setting up an AWS instance.
Sample JSON excerpt:
Instance ID: i-1bd18cac05184c14

6. Import the EC2 Instance into OpenTofu

  1. Create an empty resource block in main.tf:
  2. Import the existing EC2 resource:

7. Complete the Imported Resource Definition

After import, running tofu apply will show missing arguments. Inspect the imported state:
Then update main.tf with the required properties:
You can always re-run tofu show to confirm attribute names and values for any imported resource.

8. Validate the Configuration

Run a plan to ensure no changes are pending:
You should see 0 to add, 0 to change, 0 to destroy.
The image shows a coding environment with a task to update a resource configuration using Terraform. The code editor displays a resource block for an AWS instance, and the terminal shows the execution plan output.

Congratulations! You’ve successfully imported and now manage an existing AWS EC2 instance with OpenTofu.

References

Watch Video

Practice Lab