如何协调 Terraform 状态与现有存储桶?

zna*_*nat 1 google-cloud-storage terraform terraform-provider-gcp

使用 Terraform 11.14 我的 terraform 文件包含以下资源:

resource "google_storage_bucket" "assets-bucket" {
  name          = "${local.assets_bucket_name}"
  storage_class = "MULTI_REGIONAL"
  force_destroy = true
}
Run Code Online (Sandbox Code Playgroud)

并且这个存储桶已经被创建(它存在于基于先前的基础设施上apply)但是状态(远程上gcs)不一致并且似乎不包括这个存储桶。结果,terraform apply失败并出现以下错误:

google_storage_bucket.assets-bucket: googleapi: Error 409: You already own this bucket. Please select another name., conflict
Run Code Online (Sandbox Code Playgroud)

我该如何协调国家?(terraform refresh没有帮助)

编辑

根据 @ydaetskcoR 的回应,我做了:

terraform import module.bf-nathan.google_storage_bucket.assets-bucket my-bucket
Run Code Online (Sandbox Code Playgroud)

输出:

module.bf-nathan.google_storage_bucket.assets-bucket: Importing from ID "my-bucket"...
module.bf-nathan.google_storage_bucket.assets-bucket: Import complete! Imported google_storage_bucket (ID: next-assets-bf-nathan-botfront-cloud)
module.bf-nathan.google_storage_bucket.assets-bucket: Refreshing state... (ID: next-assets-bf-nathan-botfront-cloud)

Error: module.bf-nathan.provider.kubernetes: 1:11: unknown variable accessed: var.cluster_ip in:

https://${var.cluster_ip}
Run Code Online (Sandbox Code Playgroud)

刷新步骤不起作用。我从存在文件的项目根目录运行该命令terraform.tfvars。我尝试添加-var-file=terraform.tfvars但没有运气。任何想法?

yda*_*coR 7

您需要将其导入现有的状态文件中。您可以使用支持该terraform import命令的任何资源来执行此操作。

值得庆幸的是,该google_storage_bucket资源确实支持它

可以使用名称或项目/名称导入存储桶。如果项目未传递给导入命令,则会从提供程序块或环境变量中推断出该项目。如果无法推断,将从计算 API 中查询(如果未启用 API,则会失败)。

例如

$ terraform import google_storage_bucket.image-store image-store-bucket
$ terraform import google_storage_bucket.image-store tf-test-project/image-store-bucket
Run Code Online (Sandbox Code Playgroud)