Go package and CLI for generating Terraform config from a Terraform state file.
Terraform supports importing resources into it's managed state but it does not create the config files required to manage that state. The terraconf CLI tool generates the matching Terraform config for a Terraform state file.
-
You can either build the CLI from source or download it from a GitHub release.
-
To build from source
git clone [email protected]:jzbruno/terraconf.git cd terraconf/ go get go install
-
To download from GitHub
curl -sL https://github.com/jzbruno/terraconf/releases/download/v0.5.0/terraconf -o terraconf
-
After terraconf is installed run the command with the following syntax. The Terraform config will be output to standard out which can be redirected to a file.
terraconf /path/to/state/file > main.tf
Note that at this time purely computed attributes are included in the output. These need to be removed or Terraform plan and apply will complain about un-supported attributes. In a future release it may be possible to have computed attributes removed automatically by referencing the reosurce schema.
The following is more thorough example of using terraconf to bring existing resources under Terraform control. This example will use the AWS provider but terraconf should work with any provider.
-
Create an instance that will be used during the example. If you already have existing resources you can skip this step.
instanceID="$(aws --profile jzbruno-terraform --region us-east-1 ec2 run-instances --instance-type t3.nano --image-id ami-0ff8a91507f77f867 --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=test-terraconf-instance}]' | jq -r '.Instances[0].InstanceId')"
-
Import the existing resources into Terraform state. WARNING: Importing state without config using the -allow-missing-config flag is dangerous because it is easy to accidently delete resources.
echo 'provider "aws" { region = "us-east-1" profile = "jzbruno-terraform" }' > main.tf terraform init terraform import -allow-missing-config aws_instance.test_terraconf_instance $instanceID
-
Geenrate the Terraform config from the Terraform state file.
terraconf terraform.tfstate > main.tf
-
Update the Terraform config to remove computed attributes. In a future release it may be possible to have computed attributes removed automatically by referencing the reosurce schema.
terraform plan
For any errors like the following remove that attribute from main.tf
Error: aws_instance.test_terraconf_instance: "arn": this field cannot be set Error: aws_instance.test_terraconf_instance: : invalid or unknown key: id
Some further modifications may be required to avoid diff issues depending on the resource type.