Terraform GCP 以错误的顺序执行资源
Terraform GCP executes resources in wrong order
我有这个 main.tf 文件:
provider "google" {
project = var.projNumber
region = var.regName
zone = var.zoneName
}
resource "google_storage_bucket" "bucket_for_python_application" {
name = "python_bucket_exam"
location = var.regName
force_destroy = true
}
resource "google_storage_bucket_object" "file-hello-py" {
name = "src/hello.py"
source = "app-files/src/hello.py"
bucket = "python_bucket_exam"
}
resource "google_storage_bucket_object" "file-main-py" {
name = "main.py"
source = "app-files/main.py"
bucket = "python_bucket_exam"
}
第一次执行时它运行良好,但在 terraform destroy
和 terraform plan
-> terraform apply
之后,我注意到 terraform 尝试在实际创建存储桶之前创建对象:
当然,它不能在不存在的东西中创建对象。这是为什么?
您必须在对象和存储桶之间创建依赖关系(请参见下面的代码)。否则,Terraform 将不知道它必须先创建存储桶,然后再创建对象。这与 Terraform 如何存储资源有关 in a directed graph.
resource "google_storage_bucket_object" "file-hello-py" {
name = "src/hello.py"
source = "app-files/src/hello.py"
bucket = google_storage_bucket.bucket_for_python_application.name
}
resource "google_storage_bucket_object" "file-main-py" {
name = "main.py"
source = "app-files/main.py"
bucket = google_storage_bucket.bucket_for_python_application.name
}
通过这样做,您声明了一个隐式顺序:存储桶,然后是对象。这相当于在你的 google_storage_bucket_object
中使用 depends_on
,但在那种特殊情况下,我建议在你的对象中使用对你的存储桶的引用,而不是使用显式的 depends_on
.
我有这个 main.tf 文件:
provider "google" {
project = var.projNumber
region = var.regName
zone = var.zoneName
}
resource "google_storage_bucket" "bucket_for_python_application" {
name = "python_bucket_exam"
location = var.regName
force_destroy = true
}
resource "google_storage_bucket_object" "file-hello-py" {
name = "src/hello.py"
source = "app-files/src/hello.py"
bucket = "python_bucket_exam"
}
resource "google_storage_bucket_object" "file-main-py" {
name = "main.py"
source = "app-files/main.py"
bucket = "python_bucket_exam"
}
第一次执行时它运行良好,但在 terraform destroy
和 terraform plan
-> terraform apply
之后,我注意到 terraform 尝试在实际创建存储桶之前创建对象:
当然,它不能在不存在的东西中创建对象。这是为什么?
您必须在对象和存储桶之间创建依赖关系(请参见下面的代码)。否则,Terraform 将不知道它必须先创建存储桶,然后再创建对象。这与 Terraform 如何存储资源有关 in a directed graph.
resource "google_storage_bucket_object" "file-hello-py" {
name = "src/hello.py"
source = "app-files/src/hello.py"
bucket = google_storage_bucket.bucket_for_python_application.name
}
resource "google_storage_bucket_object" "file-main-py" {
name = "main.py"
source = "app-files/main.py"
bucket = google_storage_bucket.bucket_for_python_application.name
}
通过这样做,您声明了一个隐式顺序:存储桶,然后是对象。这相当于在你的 google_storage_bucket_object
中使用 depends_on
,但在那种特殊情况下,我建议在你的对象中使用对你的存储桶的引用,而不是使用显式的 depends_on
.