Introduction
You can automatically generate Terraform configuration for existing infrastructure using plannable imports. This feature, introduced as an experiment in Terraform 1.5, requires careful manual review before you apply any changes.
Scenario
You want to automatically generate Terraform configuration for an existing resource by using the terraform plan command with the -generate-config-out flag.
$ terraform plan -generate-config-out=generated_resources.tf
This command works in conjunction with an import block in your configuration, such as the following example.
import {
to = aws_instance.ec2
id = "i-REDACTED"
}Recommendation
Always review the automatically generated configuration for accuracy and address any warnings produced in the console from this experimental Terraform feature.
-
Prune Default Values: The generated configuration may include attributes with default values that Terraform would normally supply. You should remove these optional attributes to avoid reliance on otherwise-default values.
For example, review the following output and remove attributes like
ebs_optimized = falseif that is the default behavior.resource "aws_instance" "ec2" { ami = "ami-REDACTED" associate_public_ip_address = true availability_zone = "us-east-1c" disable_api_stop = false disable_api_termination = false ebs_optimized = false get_password_data = false hibernation = false host_id = null ## generated configuration continues but is omitted for brevity } -
Review the Subsequent Plan: After refining the generated configuration, run
terraform planagain. Pay close attention to the execution plan to ensure the difference (or lack of difference) between your current state and desired state is correct before you runterraform apply.
Additional Information
Please refer to the official documentation on Generating Configuration with Plannable Imports.