您已经在 Google Cloud 中部署了资源,现在需要使用 Terraform 来管理基础架构即代码 (IaC)。Google 提供了一个工具,可用于为项目、文件夹或组织中的资源生成 Terraform 代码。
准备工作
安装 Config Connector 的命令行界面 (CLI)。
gcloud components install config-connector
借助 Config Connector,您可以使用 Google Cloud 的 Terraform 批量导出工具。
将整个项目配置导出到 Terraform HCL 代码
gcloud beta resource-config bulk-export --resource-format=terraform
命令可导出项目、文件夹或组织中当前配置的资源,并以 HCL 代码格式将其输出到屏幕上。
gcloud beta resource-config bulk-export \ --project=PROJECT_ID \ --resource-format=terraform
将输出写入目录结构
将项目的整个配置输出到路径:
gcloud beta resource-config bulk-export \ --path=OUTPUT_DIRECTORY_NAME \ --project=PROJECT_ID \ --resource-format=terraform
--path
标志指定输出 HCL 代码的位置。如果路径 OUTPUT_DIRECTORY_NAME
不存在,则提示会询问您是否要创建该路径。
运行该命令后,每个资源的 HCL 代码会输出到以下目录结构中一个单独的 .tf
文件:
OUTPUT_DIRECTORY_NAME/projects/PROJECT_ID/RESOURCE_TYPE
将输出写入单个文件
如果您不想输出到屏幕或创建单独的 .tf
文件,可以将所有输出写入单个文件,如以下示例所示:
gcloud beta resource-config bulk-export --resource-format=terraform >> gcp_resources.tf
过滤输出
通过指定资源类型来过滤批量导出命令的输出。
列出要过滤的受支持的资源类型
如需查看支持的资源类型列表,请运行 gcloud beta
resource-config list-resource-types
命令:
gcloud beta resource-config list-resource-types
(可选)将输出写入文件:
gcloud beta resource-config list-resource-types >> strings.txt
在输出中,Compute Engine 虚拟机的资源类型如下所示:
KRM KIND: ComputeInstance
您可以忽略 KRM KIND:
前缀。
导出单个资源类型
使用上一条命令中显示的 ComputeInstance
字符串,以 HCL 代码格式仅导出项目的 Compute Engine 虚拟机实例:
gcloud beta resource-config bulk-export \ --resource-types=ComputeInstance \ --project=PROJECT_ID \ --resource-format=terraform
--resource-types
标志指定要输出的资源类型。
导出多个资源类型
以 HCL 代码格式导出虚拟机实例和防火墙规则:
gcloud beta resource-config bulk-export \ --resource-types=ComputeFirewall,ComputeInstance \ --project=PROJECT_ID \ --resource-format=terraform
使用文件指定要导出的资源类型
创建名为
tf-output
的目录。cd && mkdir tf-output && cd tf-output
创建一个名为
types.txt
的文件,并添加资源类型列表。例如:ComputeBackendBucket ComputeBackendService ComputeForwardingRule
运行带有
--resource-types-file
标志的gcloud beta resource-config bulk-export
命令:gcloud beta resource-config bulk-export \ --resource-types-file=types.txt \ --path=tf-output \ --project=PROJECT_ID \ --resource-format=terraform
如果项目不包含任何特定资源类型,则命令会成功,但不会为该资源类型输出任何内容。