0
0
Terraformcloud~15 mins

Writing configuration for imported resources in Terraform - Deep Dive

Choose your learning style9 modes available
Overview - Writing configuration for imported resources
What is it?
Writing configuration for imported resources means creating Terraform code that matches resources already created outside Terraform. This lets Terraform manage those resources without recreating or deleting them. You import the resource's state first, then write configuration that describes it exactly. This keeps Terraform and the real infrastructure in sync.
Why it matters
Without writing matching configuration after importing, Terraform won't know how to manage the resource properly. This can cause accidental changes or destruction of important infrastructure. Writing correct configuration ensures Terraform safely controls existing resources, preventing downtime or data loss. It helps teams adopt Terraform gradually without rebuilding everything.
Where it fits
Before this, you should understand basic Terraform concepts like resources, state, and configuration syntax. After learning this, you can explore advanced state management, modules, and automation for infrastructure lifecycle.
Mental Model
Core Idea
Writing configuration for imported resources means telling Terraform exactly how the existing resource looks so it can manage it safely.
Think of it like...
It's like moving into a furnished house: you first get the keys (import state), then write down an inventory list of all furniture and appliances (configuration) so you know what you have and can take care of it properly.
┌───────────────┐       ┌───────────────┐
│ Existing      │       │ Terraform     │
│ Resource      │──────▶│ State import  │
└───────────────┘       └───────────────┘
         │                       │
         │                       ▼
         │               ┌───────────────┐
         │               │ Write config  │
         │               │ matching      │
         │               │ imported state│
         │               └───────────────┘
         │                       │
         └──────────────────────▶│
                                 ▼
                        ┌───────────────┐
                        │ Terraform     │
                        │ manages       │
                        │ resource      │
                        └───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Terraform State Basics
🤔
Concept: Terraform keeps track of resources it manages using a state file.
Terraform state is a file that records what resources exist and their details. It helps Terraform know what it created and what to change. Without state, Terraform cannot manage resources effectively.
Result
You understand that Terraform state is the source of truth for managed infrastructure.
Knowing that state tracks resources is key to understanding why importing and configuration must align.
2
FoundationWhat Is Resource Importing
🤔
Concept: Importing brings existing resources into Terraform's state without changing them.
When you import a resource, Terraform records it in the state file but does not create or modify it. This lets Terraform start managing resources created outside Terraform.
Result
Terraform state now knows about the resource, but configuration is still missing.
Importing alone is not enough; Terraform needs configuration to manage the resource safely.
3
IntermediateWriting Matching Configuration
🤔Before reading on: do you think you can write any configuration after import, or must it exactly match the imported resource? Commit to your answer.
Concept: Configuration must exactly describe the imported resource to avoid changes.
After import, write Terraform code that matches the resource's current settings exactly. This includes all required attributes and any optional ones that affect the resource's state. If configuration differs, Terraform will try to change the resource on next apply.
Result
Terraform plan shows no changes, meaning configuration matches reality.
Understanding that configuration is the blueprint Terraform uses prevents accidental resource changes.
4
IntermediateUsing Terraform Import Command
🤔Before reading on: do you think 'terraform import' creates configuration automatically? Commit to your answer.
Concept: The import command only updates state; it does not generate configuration code.
You run 'terraform import . ' to add the resource to state. This command does not create any .tf files or configuration. You must write configuration manually to match the imported resource.
Result
Resource is tracked in state but configuration files remain empty or incomplete.
Knowing import only affects state clarifies why manual configuration writing is necessary.
5
IntermediateHandling Complex Resources and Attributes
🤔Before reading on: do you think all resource attributes are required in configuration after import? Commit to your answer.
Concept: Some attributes are required, others optional or computed; understanding which to include is key.
Resources have required attributes you must specify in configuration. Some attributes are computed by the provider and should not be set manually. Use 'terraform state show' to inspect imported resource attributes and write configuration accordingly.
Result
Configuration includes all required attributes and omits computed ones, matching the resource state.
Knowing which attributes to include avoids errors and unnecessary changes.
6
AdvancedDealing with Drift After Import
🤔Before reading on: do you think Terraform will detect changes made outside after import automatically? Commit to your answer.
Concept: Terraform detects drift by comparing configuration and state to real resources during plan.
If the real resource changes outside Terraform after import, Terraform plan will show differences. You must update configuration or accept changes to keep state and config aligned. Drift detection helps maintain infrastructure consistency.
Result
Terraform plan alerts you to differences, preventing unexpected changes.
Understanding drift detection helps maintain safe infrastructure management.
7
ExpertAutomating Configuration Generation for Imports
🤔Before reading on: do you think there are tools or methods to automate writing configuration after import? Commit to your answer.
Concept: Some tools and scripts can generate configuration from imported state to speed up the process.
Tools like 'terraformer' or custom scripts can read Terraform state or cloud APIs to generate .tf files matching existing resources. This reduces manual errors and speeds up importing large infrastructures. However, generated code often needs review and cleanup.
Result
You can quickly produce initial configuration for many imported resources, improving efficiency.
Knowing automation options helps scale Terraform adoption in large environments.
Under the Hood
Terraform maintains a state file that records resource IDs and attributes. When you import a resource, Terraform adds its details to this state without changing the resource. However, Terraform requires configuration files to know how to manage the resource. During 'terraform plan' and 'apply', Terraform compares configuration, state, and real infrastructure to decide actions. If configuration and state mismatch, Terraform plans changes. Writing matching configuration aligns Terraform's desired state with reality, preventing unwanted changes.
Why designed this way?
Terraform separates state and configuration to allow flexible management. Importing only updates state to avoid accidental resource creation or deletion. Manual configuration writing ensures users consciously define desired resource settings. This design prevents Terraform from guessing or overwriting unknown resource details, reducing risk. Alternatives like automatic configuration generation were avoided to keep control explicit and safe.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Existing      │       │ Terraform     │       │ Configuration │
│ Resource      │──────▶│ State file    │──────▶│ .tf files     │
└───────────────┘       └───────────────┘       └───────────────┘
         │                       │                       │
         │                       │                       ▼
         │                       │               ┌───────────────┐
         │                       │               │ Terraform     │
         │                       │               │ Plan & Apply  │
         │                       │               └───────────────┘
         │                       │                       │
         └──────────────────────▶│                       ▼
                                 │               ┌───────────────┐
                                 └──────────────▶│ Real Infra    │
                                                 └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'terraform import' create configuration files automatically? Commit to yes or no.
Common Belief:Running 'terraform import' automatically generates the Terraform configuration code for the resource.
Tap to reveal reality
Reality:'terraform import' only updates the state file; it does not create or modify configuration files. You must write configuration manually.
Why it matters:Believing import creates configuration leads to missing or incorrect code, causing Terraform to try to recreate or change resources unexpectedly.
Quick: After import, can you write any configuration you want, or must it match the resource exactly? Commit to your answer.
Common Belief:You can write any configuration after import; Terraform will adjust the resource accordingly.
Tap to reveal reality
Reality:Configuration must exactly match the imported resource's current settings to avoid Terraform planning destructive changes.
Why it matters:Incorrect configuration causes Terraform to modify or destroy existing resources, risking downtime or data loss.
Quick: Are all resource attributes required in configuration after import? Commit to yes or no.
Common Belief:All attributes shown in the resource must be included in configuration after import.
Tap to reveal reality
Reality:Only required and user-settable attributes must be in configuration; computed attributes are omitted.
Why it matters:Including computed attributes causes errors or unnecessary changes during Terraform runs.
Quick: Does Terraform automatically detect changes made outside Terraform after import? Commit to yes or no.
Common Belief:Terraform will always detect and fix any changes made outside Terraform automatically.
Tap to reveal reality
Reality:Terraform detects drift during plan but does not fix it automatically; you must update configuration or accept changes.
Why it matters:Assuming automatic fixes can cause unnoticed drift and unexpected infrastructure states.
Expert Zone
1
Some providers have attributes that appear optional but must be included in configuration after import to avoid drift.
2
State import can fail silently if resource IDs are incorrect, leading to mismatched state and configuration.
3
Terraform's plan output can be used as a guide to adjust configuration precisely after import.
When NOT to use
Writing configuration for imported resources is not suitable when resources are highly dynamic or managed by other tools continuously. In such cases, consider using dedicated configuration management or orchestration tools instead of Terraform. Also, avoid importing resources that Terraform providers do not fully support, as this can cause inconsistent state.
Production Patterns
Teams often import existing cloud infrastructure during migration to Terraform, then write configuration incrementally. They use 'terraform state show' and 'terraform plan' to verify configuration accuracy. Automation tools generate initial configuration for large imports, followed by manual refinement. Continuous drift detection and state reconciliation are part of production workflows.
Connections
Infrastructure as Code (IaC)
Builds-on
Understanding how to write configuration for imported resources deepens mastery of IaC by enabling management of existing infrastructure, not just new deployments.
Version Control Systems
Supports
Storing Terraform configuration for imported resources in version control ensures safe collaboration and tracks changes to infrastructure definitions over time.
Inventory Management in Supply Chain
Analogous process
Just like writing configuration for imported resources is about documenting existing infrastructure, inventory management documents existing stock to control and plan supply effectively.
Common Pitfalls
#1Writing configuration that differs from the imported resource's actual settings.
Wrong approach:resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" tags = { Name = "WrongName" } }
Correct approach:resource "aws_instance" "example" { ami = "ami-87654321" instance_type = "t2.micro" tags = { Name = "CorrectName" } }
Root cause:Misunderstanding that configuration must exactly match the imported resource to avoid Terraform planning changes.
#2Assuming 'terraform import' creates configuration files automatically.
Wrong approach:terraform import aws_instance.example i-1234567890abcdef0 # Then running 'terraform apply' without writing any .tf files
Correct approach:terraform import aws_instance.example i-1234567890abcdef0 # Then writing matching configuration in .tf files before running 'terraform apply'
Root cause:Confusing state import with configuration generation.
#3Including computed attributes in configuration after import.
Wrong approach:resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" private_ip = "10.0.0.5" # Computed attribute }
Correct approach:resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" # private_ip omitted because it is computed }
Root cause:Not distinguishing between user-settable and computed attributes.
Key Takeaways
Terraform import adds existing resources to state but does not create configuration files.
Writing configuration that exactly matches the imported resource is essential to prevent unwanted changes.
Only required and user-settable attributes should be included in configuration; computed attributes must be omitted.
Terraform detects drift between configuration, state, and real infrastructure during plan, helping maintain consistency.
Automation tools can help generate initial configuration for imports but manual review is necessary for accuracy.