啟動 Cloud Shell,並設定要為已部署資源產生 Terraform 程式碼的預設 Google Cloud 專案。
每個專案只需要執行一次這個指令,而且可以在任何目錄中執行。
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
如果您在 Terraform 設定檔中設定明確值,環境變數就會遭到覆寫。
在 Cloud Shell 中,安裝 Config Connector 的指令列介面 (CLI)。
gcloud components install config-connector
您可以使用 Config Connector 的 Terraform 大量匯出工具。 Google Cloud
如果看到 ERROR: (gcloud.components.install) You cannot perform this action
because the Google Cloud CLI component manager is disabled for this
installation,請改為執行下列指令:
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[[["\u003cp\u003eGoogle provides a tool to generate Terraform code for existing Google Cloud resources in a project, folder, or organization, enabling infrastructure as code (IaC) management.\u003c/p\u003e\n"],["\u003cp\u003eBefore using the tool, you need to set up Cloud Shell, install the Config Connector CLI, enable the Cloud Asset API, and create a service account with the appropriate roles.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003egcloud beta resource-config bulk-export\u003c/code\u003e command exports resources to HCL code, either printed to the screen, written to a directory with separate \u003ccode\u003e.tf\u003c/code\u003e files, or saved in a single file.\u003c/p\u003e\n"],["\u003cp\u003eYou can filter the output of the bulk export by specifying resource types either directly in the command or through a file listing the desired resource types, allowing for selective exports.\u003c/p\u003e\n"],["\u003cp\u003eCertain resources may not be supported, and the tool is considered pre-GA, meaning it is subject to specific terms and might have limited support, and is not supported on Windows OS.\u003c/p\u003e\n"]]],[],null,["# Export your Google Cloud resources to Terraform format\n\n| **Preview**\n|\n|\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n| **Caution:** This feature isn't supported on Windows operating systems.\n\nYou've deployed resources in Google Cloud, and now need to manage your\ninfrastructure as code (IaC) with Terraform. Google provides a tool that you\ncan use to generate Terraform code for resources in a project, folder, or\norganization.\n\nRoles\n-----\n\n\nTo get the permissions that\nyou need to export assets to Terraform,\n\nask your administrator to grant you the\nfollowing IAM roles on the organization, folder, or project:\n\n- [Service Usage Consumer](/iam/docs/roles-permissions/serviceusage#serviceusage.serviceUsageConsumer) (`roles/serviceusage.serviceUsageConsumer`)\n- If writing state to an existing bucket (`--storage-path=BUCKET`):\n - [Storage Object Creator](/iam/docs/roles-permissions/storage#storage.objectCreator) (`roles/storage.objectCreator`)\n - [Storage Object Viewer](/iam/docs/roles-permissions/storage#storage.objectViewer) (`roles/storage.objectViewer`)\n- If writing state to a new bucket: [Storage Object Viewer](/iam/docs/roles-permissions/storage#storage.objectViewer) (`roles/storage.objectViewer`)\n\n\nFor more information about granting roles, see [Manage access to projects, folders, and organizations](/iam/docs/granting-changing-revoking-access).\n\n\nYou might also be able to get\nthe required permissions through [custom\nroles](/iam/docs/creating-custom-roles) or other [predefined\nroles](/iam/docs/roles-overview#predefined).\n\nBefore you begin\n----------------\n\n- Prepare Cloud Shell.\n\n Launch [Cloud Shell](https://shell.cloud.google.com/), and set\n the default Google Cloud project where you want to generate Terraform code for the\n deployed resources.\n\n You only need to run this command once per project, and you can run it in any\n directory. \n\n ```\n export GOOGLE_CLOUD_PROJECT=PROJECT_ID\n ```\n\n Environment variables are overridden if you set explicit values in a\n Terraform configuration file.\n- In Cloud Shell, install the command-line interface (CLI) for Config Connector.\n\n ```\n gcloud components install config-connector\n ```\n\n Config Connector lets you use Google Cloud's Terraform bulk-export tool.\n\n If you see `ERROR: (gcloud.components.install) You cannot perform this action\n because the Google Cloud CLI component manager is disabled for this\n installation`, run the following command instead: \n\n ```\n sudo apt-get install google-cloud-sdk-config-connector\n ```\n- Enable the Cloud Asset API.\n\n ```\n gcloud services enable cloudasset.googleapis.com\n ```\n- Create a service account to use for this export:\n\n ```\n gcloud beta services identity create --service=cloudasset.googleapis.com\n ```\n- Ensure that the [Cloud Asset Service\n Agent](/iam/docs/service-agents)\n (`gcp-sa-cloudasset.iam.gserviceaccount.com`) has the\n `roles/servicenetworking.serviceAgent` role:\n\n ```\n gcloud projects add-iam-policy-binding PROJECT_ID \\\n --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-cloudasset.iam.gserviceaccount.com \\\n --role=roles/servicenetworking.serviceAgent\n ```\n- Ensure that the [Cloud Asset Service\n Agent](/iam/docs/service-agents)\n (`gcp-sa-cloudasset.iam.gserviceaccount.com`) has the\n `roles/storage.objectAdmin` role:\n\n ```\n gcloud projects add-iam-policy-binding PROJECT_ID \\\n --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-cloudasset.iam.gserviceaccount.com \\\n --role=roles/storage.objectAdmin\n ```\n | **Note:** To get your `PROJECT_ID` and `PROJECT_NUMBER`, go to the [Google Cloud console](https://console.cloud.google.com/home/dashboard).\n\nLimitations\n-----------\n\nSome resource types aren't supported for export to Terraform format\neven though they are supported by the Terraform Google provider. For a\nlist of resource types that are supported for export to Terraform format, run\nthe [`gcloud beta resource-config list-resource-types`](/sdk/gcloud/reference/beta/resource-config/list-resource-types) command.\n\nExport the entire project configuration to Terraform HCL code\n-------------------------------------------------------------\n\nThe [`gcloud beta resource-config bulk-export --resource-format=terraform`](/sdk/gcloud/reference/beta/resource-config/bulk-export) command exports\nresources configured in the project, folder, or\norganization and prints them to the screen in [HCL code format](https://www.terraform.io/language/configuration-0-11/syntax). \n\n```\ngcloud beta resource-config bulk-export \\\n --project=PROJECT_ID \\\n --resource-format=terraform\n```\n\n### Write the output to a directory structure\n\n1. If you haven't done so already, create the directory where you want to\n output the project's configuration:\n\n ```\n mkdir OUTPUT_DIRECTORY\n ```\n2. Export the project's entire configuration to the directory:\n\n ```\n gcloud beta resource-config bulk-export \\\n --path=OUTPUT_DIRECTORY \\\n --project=PROJECT_ID \\\n --resource-format=terraform\n ```\n\n The `--path` flag specifies the location to output the HCL code.\n\nAfter running the command, the HCL code for each resource is output to a\nseparate `.tf` file in the following directory structure: \n\n```\nOUTPUT_DIRECTORY/projects/PROJECT_ID/RESOURCE_TYPE\n```\n\n### Write the output to a single file\n\nIf you don't want to print the output to the screen or create separate `.tf`\nfiles, you can write all of the output to a single file, as shown in this\nexample: \n\n```\ngcloud beta resource-config bulk-export \\\n --resource-format=terraform \\\n --project=PROJECT_ID \\\n \u003e\u003e gcp_resources.tf\n```\n\nFilter the output\n-----------------\n\nFilter the output of the bulk export command by specifying resource types.\n\n### List the supported resource types to filter on\n\nFor a list of resource types that are supported for export to Terraform format,\nrun the [`gcloud beta resource-config list-resource-types`](/sdk/gcloud/reference/beta/resource-config/list-resource-types) command: \n\n```\ngcloud beta resource-config list-resource-types\n```\n\nOptionally, write the output to a file: \n\n```\ngcloud beta resource-config list-resource-types \u003e\u003e strings.txt\n```\n\nIn the output, the resource type for Compute Engine VMs is listed as: \n\n```\nKRM KIND: ComputeInstance\n```\n\nYou can ignore the `KRM KIND:` prefix.\n\n### Export a single resource type\n\nUse a string, such as `ComputeInstance`, to export specific resource types for\nyour project in HCL code format: \n\n```\ngcloud beta resource-config bulk-export \\\n --resource-types=RESOURCE_TYPE \\\n --project=PROJECT_ID \\\n --resource-format=terraform\n```\n\nThe `--resource-types` flag specifies the resource type to output.\n\n### Export multiple resource types\n\nExport VM instances and firewall rules in HCL code format: \n\n```\ngcloud beta resource-config bulk-export \\\n --resource-types=ComputeFirewall,ComputeInstance \\\n --project=PROJECT_ID \\\n --resource-format=terraform\n```\n\n### Use a file to specify the resource types to export\n\n1. Create a directory called `tf-output`.\n\n ```\n cd && mkdir tf-output && cd tf-output\n ```\n2. Create a file called `types.txt`, and add a list of resource types. For\n example:\n\n ```\n ComputeBackendBucket\n ComputeBackendService\n ComputeForwardingRule\n ```\n3. Run the `gcloud beta resource-config bulk-export` command with the\n `--resource-types-file` flag:\n\n ```\n gcloud beta resource-config bulk-export \\\n --resource-types-file=types.txt \\\n --path=tf-output \\\n --project=PROJECT_ID \\\n --resource-format=terraform\n ```\n\nIf the project doesn't contain any of a particular resource type, the command\nsucceeds but nothing is output for that resource type.\n\nTroubleshooting\n---------------\n\nIf you see the following error:\n\n\"Permission denied during export. Please ensure the Cloud Asset Inventory API is\nenabled.\"\n\nMake sure that you have followed the instructions in the\n[Before you begin](#before-you-begin) section.\n\nNext steps\n----------\n\n- [Import your Google Cloud resources into Terraform\n state](/docs/terraform/resource-management/import)."]]