Terraform Import

While the terraform import CLI command exists since early days of Terraform the ability to execute imports through configuration using the import blocks functionality got introduced with Terraform v.1.5.0 (April 2024).

This page provides a guide on how to navigate through an import of already existing infrastructure into a Terraform maintained workflow.

The import bock allows a declarative ability to integrate already existing infrastructure deployments into a Terraform maintained deployment workflow. The corresponding and already existing CLI does not generate configuration code whereas the configuration-driven approach through the import block along the plan-stage offers functionality to create .tf configurations of already existing infrastructure.

Note: The feature is yet (while typing this document) marked as experimental, specifically the -generate-config-out feature returns a warning during execution. Therefore -generate-config-out is yet to be used carefully though it can be tremendously helpful when used.

Steps to Import an existing infrastructure

This guide does not contain setting up Terraform. Therefore provider configuration as well as state file handling is assumed to exist already.

Import of an S3 bucket:

import {

to = aws_s3_bucket.<name>

id = “<name>”

}

Execution of terraform plan: terraform plan -generate-config-out=imported_config_s3.tf. The import block in the .tf-declaration above creates a configuration file named imported_config_s3.tf with a configuration matching the S3 bucket along a header/comment section noting the configuration file got created through Terraform’s configuration-driven import functionality

Content of imported_config_s3.tf:

# __generated__ by Terraform

# Please review these resources and move them into your main configuration files.

# __generated__ by Terraform from “<name>”

resource “aws_s3_bucket” “<name>” {

bucket = “<name>”

bucket_prefix = null

force_destroy = null

object_lock_enabled = false

tags = {}

tags_all = {}

}

Conclusion

Though the feature is flagged as experimental and therefore may indicate changes and further to evolve in future releases the already existing functionality of the configuration-driven import block is already a very powerful option to handle requirements where infrastructure which exists outside a Terraform workflow would need to be made aware to a workflow.

The step above becomes very handy through migrations, duplication of legacy deployments and many other opportunities where an already existing deployment would need to be made aware to Terraform’s workflows.

Leave a comment