Terraform can import existing infrastructure. This allows you to take resources you've created by some other means and bring them under Terraform management. Google provides a tool that you can use to import your Google Cloud resources into Terraform state so that you can manage your deployment in Terraform.
You can import the state for a project, folder, or organization.
Before you begin
Install the command-line interface (CLI) for Config Connector.
gcloud components install config-connector
Config Connector lets you use Google Cloud's Terraform import tool.
Generate Terraform code for your resources
Run the gcloud beta resource-config
bulk-export
command to output the project's entire configuration to the path,
entire-tf-output
:
gcloud beta resource-config bulk-export \ --path=entire-tf-output \ --project=PROJECT_ID \ --resource-format=terraform
Create Terraform modules from the generated code
Run the gcloud beta resource-config terraform
generate-import
command, pointing to the content in the output directory:
gcloud beta resource-config terraform generate-import entire-tf-output
This command generates Terraform modules and an import script:
The
gcloud-export-modules.tf
file. This file points to all of the modules from the sub-resources. The content of this file looks like this:provider "google" { project = "PROJECT_ID" } module "entire-tf-output-projects-PROJECT_ID-ComputeFirewall" { source = "./entire-tf-output/projects/PROJECT_ID/ComputeFirewall" } module "entire-tf-output-projects-PROJECT_ID-ComputeBackendService-global" { source = "./entire-tf-output/projects/PROJECT_ID/ComputeBackendService/global" } ...and so on
An executable shell script called something like
terraform_import_20220331-19-12-33.sh
. The shell script contains a list ofterraform import
commands:#!/bin/sh # Terraform Import Script generated by gcloud cli terraform import module.entire-tf-output-projects-PROJECT_ID-ComputeFirewall.google_compute_firewall.allow_ssh projects/PROJECT_ID/global/firewalls/allow-ssh ...and so on
The
terraform import
commands are for importing the modules created by thegenerate-import
command into the Terraform state.
Import the modules into the Terraform state
Initialize it:
terraform init
Run the script:
./terraform_import_20220331-19-12-33.sh
Output:
module.examples-projects-PROJECT_ID-ComputeInstance-us-central1-a.google_compute_instance.instance_1: Importing from ID "projects/PROJECT_ID/zones/us-central1-a/instances/instance-1"... module.examples-projects-PROJECT_ID-ComputeInstance-us-central1-a.google_compute_instance.instance_1: Import prepared! Prepared google_compute_instance for import module.examples-projects-PROJECT_ID-ComputeInstance-us-central1-a.google_compute_instance.instance_1: Refreshing state... [id=projects/PROJECT_ID/zones/us-central1-a/instances/instance-1] Import successful! The resources that were imported are shown above. These resources are now in your Terraform state and will henceforth be managed by Terraform.