0
0
Terraformcloud~30 mins

Why importing existing resources matters in Terraform - See It in Action

Choose your learning style9 modes available
Why Importing Existing Resources Matters
📖 Scenario: You are managing cloud infrastructure using Terraform. Some resources like virtual machines or storage buckets were created manually or by other tools. To manage them properly with Terraform, you need to import these existing resources into your Terraform state.This helps keep your infrastructure organized and prevents accidental resource duplication or deletion.
🎯 Goal: Learn how to define a Terraform resource and import an existing cloud resource into Terraform state to manage it safely.
📋 What You'll Learn
Create a Terraform resource block for an existing cloud resource
Add a variable to hold the resource identifier
Use the Terraform import command to link the existing resource
Verify the resource is managed by Terraform without recreating it
💡 Why This Matters
🌍 Real World
Many cloud resources are created outside Terraform. Importing them lets you manage all infrastructure consistently in one place.
💼 Career
Cloud engineers and DevOps professionals often import existing resources to maintain infrastructure as code and avoid manual errors.
Progress0 / 4 steps
1
Define a Terraform resource block for an existing AWS S3 bucket
Create a Terraform resource block named aws_s3_bucket with the resource name existing_bucket. Set the bucket attribute to my-existing-bucket exactly.
Terraform
Need a hint?

Use the resource keyword, specify the resource type aws_s3_bucket, and name it existing_bucket. Set the bucket attribute to the exact bucket name.

2
Add a variable to hold the S3 bucket name
Add a Terraform variable named bucket_name with a default value of my-existing-bucket.
Terraform
Need a hint?

Define a variable block with the name bucket_name and set its default to the bucket name. Use var.bucket_name in the resource block.

3
Import the existing S3 bucket into Terraform state
Use the Terraform import command to import the existing S3 bucket named my-existing-bucket into the resource aws_s3_bucket.existing_bucket. Write the exact command as: terraform import aws_s3_bucket.existing_bucket my-existing-bucket.
Terraform
Need a hint?

Use the terraform import command with the resource address and the existing bucket name.

4
Verify the imported resource is managed by Terraform
Add the lifecycle block inside the aws_s3_bucket.existing_bucket resource with prevent_destroy = true to avoid accidental deletion.
Terraform
Need a hint?

Inside the resource block, add a lifecycle block with prevent_destroy = true to protect the resource.