Recently, I faced an interesting challenge while working with Terraform and Azure. I had already deployed a bunch of resources container apps, storage accounts, and more manually. Later, my team wanted to replicate this setup automatically in another Azure account using Terraform pipelines.
At first, it sounded straightforward just write Terraform code for everything, run the pipeline, and it’s done. But reality hit me hard:
How do you make Terraform aware of resources that already exist?
The Problem
Terraform relies on its state file to track infrastructure. If a resource exists in Azure but isn’t in Terraform’s state, running terraform apply will attempt to recreate it, which either fails or risks breaking things.
A few complications in my setup:
- We were using a remote backend for the state (so the state wasn’t local).
- Manual
terraform importwas not practical for dozens of resources. - We wanted the pipeline to be fully automated, without manual interventions.
At this point, I was stuck until the idea hit me.
The “Aha” Moment
I thought:
Terraform can create resources via pipeline automatically…
Why can’t I import existing resources via pipeline too?
And that’s when I realized I could automate the import process itself.
The Solution
Here’s what I did:
1. Create a Separate Import Pipeline
- I wrote a dedicated pipeline that loops over existing Azure resources.
- For each resource, it runs
terraform importusing Terraform CLI. - The state gets automatically recorded in the remote backend.
2. Sync the State
- After the import pipeline runs, the Terraform state now accurately reflects all existing resources.
- No more mismatch between Azure and Terraform.
3. Run the Regular Terraform Pipeline
- Now, the normal pipeline (
terraform apply) works seamlessly. - Terraform can manage both existing and new resources.
- The setup is now fully repeatable in other Azure accounts.
Why This Matters
This approach solved multiple challenges:
- Automates importing resources no manual effort.
- Works with remote backends.
- Ensures Terraform pipelines can manage existing and new infra seamlessly.
- Makes infrastructure replication across accounts practical and safe.
Key Takeaways
- Terraform Import is pipeline-friendly: You don’t need to run it manually for each resource.
- Remote backend doesn’t block imports: You just need a process to sync state first.
- Planning is critical: When onboarding existing infrastructure into IaC, always think about state synchronization.
This experience taught me that Terraform is incredibly flexible if you combine automation with a little bit of creativity. Sometimes, the solution is not in writing more code, but in automating the right process.
💡 Pro Tip: Always test imports on non-production environments first to avoid accidental overrides.
Top comments (0)