Skip to content

Instantly share code, notes, and snippets.

@J00MZ
Last active July 7, 2022 09:34
Show Gist options
  • Save J00MZ/baa20a34c817f0784f985eb9f10326c0 to your computer and use it in GitHub Desktop.
Save J00MZ/baa20a34c817f0784f985eb9f10326c0 to your computer and use it in GitHub Desktop.
Quickly create terraform files from resources - reverse Terraform

Create .tf files from remote resources

Disclaimer

Generating configuration from remote state is still not officially supported by Terraform.

However, when I stupidly enough deleted a complex DataDog resource that I had created manually, I managed to fully restore it and create a full terraform file for it using a few simple commands

This worked for me with the datadog_synthetics_test resource, so this will be the example resource below.
If this works for you with any other Terraform resources, I would love to know 🤗 .

Terraform and provider versions:

❯ tf -version
Terraform v1.1.2
on darwin_arm64
+ provider registry.terraform.io/datadog/datadog v3.12.0

Steps

1. Create an empty resource block for the remote resource

resource "datadog_synthetics_test" "my_test" {

}

2. Import the resource into local terraform state - docs.

terraform import datadog_synthetics_test.my_test <RESOURCE_ID>

3. Export the resource from state into a new .tf file

terraform state show -no-color datadog_synthetics_test.my_test > my_test.tf

4. Remove ID's of the resource and monitor - or just comment them out

resource "datadog_synthetics_test" "my_test" {
  # id = "***-***-***"
  # monitor_id      = ******
  .
  .
  .
}

5. Apply your changes!

terraform apply my_test.tf

Voilà!
Resource creates successfully

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment