> Blog >
How to Migrate Existing Infrastructure to Terraform Without Breaking Production
Learn how to migrate existing infrastructure to Terraform without downtime: import methods, state setup, refactoring, and governance that prevents drift.

How to Migrate Existing Infrastructure to Terraform Without Breaking Production

4 mins
July 3, 2026
Author
Aditya Santhanam
TL;DR
  • Terraform import is only a metadata operation: it maps live resources into state without touching production. The real work is writing or generating matching HCL until "terraform plan" reports "No changes."
  • Match the method to the scale: CLI import for a handful of resources, import blocks plus generate-config on Terraform 1.5+ or OpenTofu for standard migrations, and bulk tools like Terraformer for sprawling estates. Bulk tools ingest fast but produce messy code.
  • Do two things before importing anything: stand up an encrypted, locked remote state backend such as S3 with DynamoDB, and decide Terraform versus OpenTofu, which is a licensing and governance call, not a technical one.
  • Generated code is a starting point, not your source of truth. Refactor it into reusable modules, standardize naming and tags, then enforce governance with plan-on-every-PR and routine drift detection.
  • Look at your current cloud infrastructure. But do you know who changed the security group setting yesterday? Keeping track of it manually and relying on it can take a lot of time. Moving to Terraform - an Infrastructure as Code (IaC) tool is the standard path to achieving drift visibility, ironclad change control, and repeatable deployments. 

    But the biggest concern about migrating existing infrastructure to Terraform is the risk of disrupting production. By carefully importing existing resources into Terraform, validating configurations, and migrating in phases, organizations can adopt Infrastructure as Code while keeping production systems running. 

    In this blog, we will illustrate how to migrate existing infrastructure to Terraform safely.

    Table of Contents

      What migrating to Terraform actually means (and what Terraform import does)

      Organizations often migrate existing infrastructure to Terraform through cloud consoles or using other Infrastructure as Code (IaC) tools. Migration is all about bringing the existing resources under Terraform management without disrupting production environments.

      Terraform migration is a process of creating a Terraform configuration for existing or new cloud infrastructure under the management of Terraform’s Infrastructure as Code (IaC). An important difference to note is that the import of resources to Terraform state is just the first step in the migration process. The team still has to configure their Terraform code to reflect the imported infrastructure correctly.

      Import command

      Terraform import function scans your cloud resources and collects information regarding those into the Terraform state file on the local or remote system. In simple terms, it’s just a metadata operation that does not affect your live resources in any manner.

      When you import the resource:

      • It gets saved to the state file by Terraform.
      • The existing cloud resource remains the same.
      • There is no rebooting, redeploying, or reconfiguration of any infrastructure.
      • All subsequent Terraform plans will make comparisons between your configuration and the imported resource.
      • It is especially useful to use terraform import in production where any downtime is not allowed.

      Brownfield vs. Greenfield Terraform Migration

      So after deciding to Terraform, your approach will fall under one of two categories depending on what you are starting with.

      Greenfield [ Rebuild Clean]

      A Greenfield approach is used when building something brand new or when you recreate the environment from scratch. It’s clean, free of historical technical debt, and allows you to test your code safely in isolation. This approach offers consistent architecture, standardized resource naming, cleaner module design, and fewer legacy configuration issues.

      Brownfield [ Import Existing Infrastructure]

      A Brownfield approach is used when you have a massive footprint of existing cloud infrastructure (i.e production) that must continue operating throughout the migration. The steps are

      • Writing configurations for Terraform
      • Importing existing infrastructure to Terraform state
      • Validating the configuration with respect to the real infrastructure
      • Managing future changes using Terraform.

      This methodology reduces risks since existing services will be left intact while Terraform starts managing them.

      Why teams move from manual and scripted infra to Terraform

      Most companies start their journey with the development of infrastructure using cloud consoles or the command-line interface. As time goes by, the infrastructure gets more complex, and the administrators use shell scripts, PowerShell, or cloud provider-based solutions to automate the process.

      Such an approach is valid at first, yet there are some problems like:

      • Configuration differences across environments
      • Lack of visibility into what happened with the infrastructure
      • Onboarding of new staff is difficult
      • The necessity of manual intervention in case of any failures
      • Scripts becoming unmaintainable due to changing requirements

      In the end, infrastructure becomes very knowledge-dependent. The main reasons organizations adopt infrastructure as code with Terraform

      • Reproducibility: By using manual setups, it is difficult to duplicate an environment. Terraform solves this problem. This allows developers to provision the same environment without having to manually recreate the resources or run a set of customized scripts. This will make the process consistent and thus reduce the chances of errors in deployment.
      • Drift visibility: One of the greatest difficulties with manual infrastructure is that of drift. The modifications performed through the console interface or even through ad-hoc scripts usually go unrecorded, thus creating a discrepancy between the actual infrastructure and what is documented within the organization. Terraform detects drift by performing comparisons between the current infrastructure and its desired state every time a plan is performed.
      • Rigorous Change Control and Auditing: Infrastructure changes become easier to review when they are stored as code. Version control can be used to manage Terraform configurations, and this enables the team to:
        • Review changes before implementation
        • Understand who made changes and when
        • Reverse the configuration if required
        • Include the infrastructure changes in the CI/CD pipeline.
        • This ensures that mistakes are not made.
      • Cost Management: Terraform makes infrastructure easier to understand and manage. Standardized configurations assist in:
        • Consistently removing unneeded resources
        • Preventing duplicate deployments
        • Implementing resource tagging strategies
        • Standardizing environment size
        • Infrastructure assessment before deployment
        • Increased visibility of deployed resources usually facilitates cloud cost optimization initiatives.
      • Disaster Recovery: Recovering manually built infrastructure can be slow and error-prone, especially when documentation is incomplete. Infrastructure is already defined using Terraform in the form of code. With the use of Terraform, teams can recreate their environments faster through the configuration that is saved, making them less reliant on rebuilding their environment manually. Terraform cannot be considered a replacement for backups and disaster recovery processes; however, it offers an effective way to recreate the infrastructure. 

      Choosing your migration approach

      It is not true that every migration in the Terraform environment goes the same way. Companies that have developed cloud environments can use a brownfield migration process, which implies importing data in batches and verifying each step of the process. It is often useful for new apps to have a greenfield migration.

      The main migration strategies differ in how they discover existing resources and how much manual work they require.

      Approach Best For Tradeoffs
      CLI import Small environments or individual resources Slow, manual, and prone to human typos
      Import Blocks + generate_config Standard migrations Excellent accuracy, but requires native Terraform 1.5+.
      Bulk Tools Massive, sprawling estates Rapid ingestion, but generates messy, complex code.
      Rebuild (Greenfield) Total infrastructure resets Clean code, but requires high effort and data migration
      Hybrid Enterprise environments Balances speed and cleanliness, but requires strict coordination.

      For mid-to-large scale estates, use a hybrid, tool-assisted approach.

      • Use native import blocks with generated configuration as your foundation to guarantee accurate state mapping.
      • Supplement this with bulk tooling to ingest wide, repetitive resource footprints quickly.
      • Immediately refactor the output into clean, reusable modules.

      Before you start: Terraform or OpenTofu, and State Setup

      An infrastructure migration that succeeds requires much more preparation than just moving the first resource. Two decisions made at the beginning of your migration process will influence everything else you do in the future: the decision about the Infrastructure as Code system to use and the setting up of your secure remote state.

      Terraform or OpenTofu?

      Both Terraform and OpenTofu use a similar kind of workflow and configuration language. The decision is less about technical capability and more about governance, licensing, and long-term strategy.

      Considerations Terraform OpenTofu
      License Operates under the restrictive BSL. Fully open-source under an OSI-approved MPL-2.0 license.
      Governance Maintained by HashiCorp Community-driven project with open governance
      Industry support Broad enterprise adoption and mature commercial ecosystem Backed by a growing ecosystem including IBM
      Roadmap Focuses mainly on large-scale enterprise platform integrations. Actively prioritizes standalone engineering utilities and security ergonomics

      Configure Remote State before Importing Resources

      Importing resources into the local state file is one of the most typical migration errors. The risk involved in the local state is that it is hard to manage, secure, and recover. 

      It is important to create a remote state file backend before importing any resources. A correct setup of the backend will give you:

      • State management in a centralized place
      • Data encryption for your state files
      • Locking your state to avoid concurrent modifications
      • Recovery of your state
      • Access control using identity and access management

      An Amazon S3 bucket along with DynamoDB for locking is used in most cases in AWS environments. There are also comparable backends available in other cloud platforms.

      The step-by-step Import process

      Bringing manual or scripted cloud resources under the control of Infrastructure as Code (IaC) doesn’t have to be a high-stakes guessing game. By correct planning and following a structured, step-by-step framework, one can map live infrastructure into Terraform with zero impact on production.

      Step1: Inventory and discover existing resources 

      Before writing a single line of HashiCorp Configuration Language (HCL), one must know what is running in your cloud environment. Missing dependencies or unmanaged resources can lead to incomplete configurations and unexpected drift later.

      Utilize cloud native technology and metadata to identify:

      • Virtual machines, containers, databases, networks, and storage
      • Tagging and naming of resources
      • Dependency of resources
      • Identity and access configurations
      • Modules or shared components

      Checklist

      Before proceeding, confirm that 

      • A complete resource inventory
      • Consistent resource tagging
      • Dependency mapping
      • Appropriate permission to read infrastructure
      • A configured remote state backend
      • Version-controlled Terraform project structure.

      Step 2: Write or Generate Terraform Configuration

      Terraform needs configuration that describes every imported resource. One can write HCL manually or use import blocks together with generated configuration to reduce manual effort. If you are using Terraform 1.5+ or OpenTofu, you can utilize plannable imports using import blocks. This allows Terraform to automatically generate the required configuration files.

      For example, declaring an import block creates an imports.tf file and defines the resources:

      import {

      To = aws_instance.web_server

      Id = “ i-0123456789abcdef0”

      }

      Next, run the generation command in your terminal

      Bash

      Terraform plan -generate-config-out = generated_resources.tf

      Terraform will automatically inspect the live i-0123456789abcdef0 instance and write the fully populated HCL code directly into generated_resources.tf.

      Step 3: Import the Resources into State File

      Now that the code is generated, we need to link the real-world cloud resources to your Terraform state ledger. For larger migrations, import blocks provide a more scalable, plannable workflow. Import existing resources into Terraform because imports become part of the Terraform configuration rather than one-time CLI commands. 

      Step 4: Verify with Terraform plan

      Now, after importing resources, validate that Terraform’s configuration matches the live infrastructure.

      </> Bash

      terraform plan - refresh-only

      If the generated code matches your cloud infrastructure perfectly, the terminal will return the ultimate success metric.

      Step 5: Handle for_each and count addressing safely.

      Resources created with for_each or count require careful addressing during import.

      For example:

      Aws_instance.web[“production”]

      This address for the import source should be identical to the address that is set up for the resource in the Terraform configuration. An addressing mistake will connect the state to a wrong resource, making further planning hard to understand. In case of importing sets of resources, check keys and indexes beforehand.

      Step 6: Validation before Ongoing management

      Once all the resources have been imported into Terraform and “No changes” is reported from terraform plan -refresh-only, that indicates Terraform can manage the infrastructure. From this point, changes should be made through Infrastructure as Code rather than cloud consoles, which helps to manage the drift.

      Importing at scale

      Importing a small scale of resources into Terraform is straightforward, but enterprise migrations often involve thousands of resources across multiple accounts, subscriptions, projects, and regions. Use bulk discovery tools like Terraformer, former2, or Azure’s aztfexport to ingest sprawling environments quickly. Generated code contains duplicated resources, inconsistent naming, hardcoded values, and little modularization. 

      Large organizations typically adopt a migration-factory approach. With AI assistance, code generation and reconciliation can further accelerate refactoring by identifying duplicate patterns, suggesting reusable modules.

      Choosing an experienced partner like Entrans can provide automated frameworks and deep architectural expertise. Contact us to learn more about Migration Scale Assessment.

      Refactor: From Generated Code to Maintainable IaC

      Automatically generated Terraform configuration is great to use as a migration point; however, it will be unwise to use it as your definitive source code. Code generation solutions for HCL care about generating the most accurate representation of the infrastructure you have in place; they don't care about creating clear and easily managed code.

      Modularize the Architecture

      Break down the single-file configuration into isolated, reusable modules. Categorize and group related infrastructure components such as networking, databases, or compute clusters. This decouples the environment and ensures that an update to an application server won’t accidentally risk modifying core network routing tables.

      Standardize Naming and Tagging

      Names used by generated code might have varying naming conventions. When carrying out refactorings, ensure that you have consistent resource names, labels, and tags. Good tagging allows for better governance, cost management, discoverability of resources, and compliance reports.

      Apply DRY Principles

      Do not repeat the same configuration on several resources. Instead, use variables, locals, and a modular approach to replace duplicated values. In the case where it is necessary, apply for_each or count when dealing with similar resources using a single configuration.

      State management and security

      Terraform state file is a literal blueprint of cloud architecture because it stores sensitive credentials, API keys, and database passwords in plain text format. Store state in a remote backend rather than on local machines to enable collaboration, centralized management, and recovery. Enable state locking to prevent concurrent updates that could corrupt the state and ensure encryption at rest and in transit to protect sensitive data.

      Prevent data loss using versioning, automatic backups, and disaster recovery strategies on the remote backend. Test state recovery regularly so that the infrastructure management process can continue even if there is any accidental deletion or corruption of data.

      In case you have a security-minded organization, then state management is both a governance issue as well as an operational issue. With partners such as Entrans, you can get the proper backend architecture designed, access controls set up, and security and cloud services managed.

      Governance after import: keeping the estate clean

      Importing existing infrastructure into Terraform is only the beginning. To get long-term success, we should follow governance that keeps the environment consistent and prevents configuration drift. Enforce a strict automated workflow: trigger a terraform plan on every GitPull Request (PR) for peer review, and execute terraform apply by merging with the main branch. 

      Perform drift detection on a routine basis by using the terraform plan command to discover any drift in your infrastructure that occurs outside of Terraform, thereby keeping your infrastructure aligned with the authorized configuration.

      How much it costs and how long it takes

      The Terraform migration depends on the number of resources and complexity of the environment. The primary driver of your timeline isn’t running the terraform import command - that takes seconds. Factors such as multiple cloud accounts, interdependent services, legacy infrastructure, custom networking, and compliance requirements can all be considered in influencing the timelines of migration.

      Estate Size Resource Count Timeline Primary Cost Drivers
      Small Up to ~ 100 resources 1 - 3 weeks Inventory, import, validation, and basic module creation
      Medium 100 - 500 resources 1 - 3 months Database clusters, cross-region routing
      Large enterprise 500+ resources 3 to 6+ months Legacy technical debt, strict compliance, multi-account structures.

      Common mistakes and best practices

      Terraform migration is often considered successful only when the team follows a disciplined process. 

      • Applying before the Plan is Clean: Running terraform apply while your plan still shows impending changes or replacements is one of the ways to trigger an accidental production outage.
      • Thinking code as Production-Ready: While tools that can generate Terraform configurations offer an excellent way to start, the code generated is not usually maintainable. Using HCL code that has been generated without refactoring leads to duplication of code and inconsistency in names.
      • Dumping Generated Code As-Is: Treating the raw output of automated discovery tools as production-ready results in monolithic, brittle configuration files that are difficult to update.
      • Incorrect for_each or count Addressing: Any resources that are configured through the for_each or count methods should have their import done through the correct resource address, as any mistake on either keys or index numbers may confuse the association in the Terraform plan.

      Best practices

      • Use declarative import blocks alongside - generate-config-out to let Terraform write your baseline code wherever possible for a more repeatable migration process.
      • Run terraform plan -refresh-only after importing resources and continue refining the configuration until Terraform reports “No changes”.
      • Ensure all HCL configuration module frameworks and policy definitions are maintained and audited correctly.
      • Break down raw configurations into logical infrastructure modules.
      • Integrate compliance tools like Open Policy Agent (OPA) into CI/CD runners that block security policy violations before they can deploy.

      Build versus partner, and how to choose one.

      To carry on with the Terraform migration, the organization must decide whether to do it with internal teams or bring in an experienced partner. The right choice depends on complexity and skills available.

      Building In-House Makes Sense

      Consider internal team

      • If the infrastructure is relatively small or of moderate size.
      • If your engineers are expertised in Terraform and Infrastructure as Code.
      • Migration timelines are flexible.
      • Business can allocate engineers without affecting day-to-day operations.

      Choosing a partner

      A migration partner will be helpful

      • when the environment is large, business-critical, or highly regulated.
      • The migration deadline is tight.
      • Security, compliance, or governance requirements.
      • Limited internal Terraform expertise.

      Choosing an experienced partner like Entrans will bring in proven migration frameworks, automation, and governance practices to reduce risk and accelerate delivery.

      Want to know more about it? Schedule a call to meet our team today.

      Share :
      Link copied to clipboard !!
      Migrate to Terraform Without Breaking Production
      Entrans imports, validates, and refactors your existing infrastructure into clean, production-grade Terraform.
      20+ Years of Industry Experience
      500+ Successful Projects
      50+ Global Clients including Fortune 500s
      100% On-Time Delivery
      Thank you! Your submission has been received!
      Oops! Something went wrong while submitting the form.

      FAQ

      1. What is the safest way to bring our existing AWS infrastructure under Terraform without any downtime?

      The safest way is using import blocks to map AWS resources into a locked, encrypted remote state file. Start applying the changes only after the terraform plan reports “No changes”, ensuring existing resources remain untouched.

      3. How do I import hundreds of existing cloud resources into Terraform efficiently?

      For Efficient bulk importing, use an automated migration-factory approach combining utilities like Terraformer or former2. Then refactor the generated configuration into reusable modules before managing future changes.

      3. Should I use terraform import, import blocks, or a tool like Terraformer for an existing estate?

      For production environments, use import blocks with the generated configuration for accuracy. Bulk tools like Terraformer are best for large estates but require cleanup and standardization afterward.

      4. Do I generate Terraform configuration from resources that already exist?

      Yes. Generated configuration provides a solid starting point that reflects your existing infrastructure. Review and refactor it into reusable modules before treating it as production-ready code. 

      5. Why does terraform plan want to destroy my resource after I imported it, and how do I stop it?

      This happens because your generated HCL code contains a mismatch or missing argument compared to the real-world cloud configuration, causing Terraform to plan a destructive replacement. 

      6. How do I import resources that use for_each or count without breaking the state?

      Import each resource using its exact Terraform address, including the correct key or index. Verify the mapping carefully to avoid associating state with the wrong resource.

      Hire Terraform Migration Engineers
      Entrans engineers import existing resources, refactor generated code into modules, and set up secure remote state.
      Free project consultation + 100 Dev Hours
      Trusted by Enterprises & Startups
      Top 1% Industry Experts
      Flexible Contracts & Transparent Pricing
      50+ Successful Enterprise Deployments
      Aditya Santhanam
      Author
      Aditya Santhanam is the Co-founder and CTO of Entrans, leveraging over 13 years of experience in the technology sector. With a deep passion for AI, Data Engineering, Blockchain, and IT Services, he has been instrumental in spearheading innovative digital solutions for the evolving landscape at Entrans. Currently, his focus is on Thunai, an advanced AI agent designed to transform how businesses utilize their data across critical functions such as sales, client onboarding, and customer support

      Related Blogs

      How to Migrate Existing Infrastructure to Terraform Without Breaking Production

      Learn how to migrate existing infrastructure to Terraform without downtime: import methods, state setup, refactoring, and governance that prevents drift.
      Read More

      How to Migrate from Docker Swarm to Kubernetes: A Practical, Low-Downtime Playbook

      A practical, low-downtime Docker Swarm to Kubernetes migration playbook: concept mapping, R-strategies, a step-by-step process, and blue-green cutover.
      Read More

      Avaya to Five9 Contact Center Migration: A Step-by-Step Guide

      A step-by-step Avaya to Five9 migration guide: when to move, key benefits, a 9-step plan, common pitfalls, and how to hit zero downtime.
      Read More