【发布时间】:2023-03-06 11:43:01
【问题描述】:
我们有一个在 GCP 中创建 redis 实例的模块。我从定义变量的示例文件夹中调用它。这工作正常。 这个 redis 实例将输出一个 IP 元组,我想用它来通过子模块创建 consul 服务。子模块需要IP作为字符串,所以我需要以某种方式迭代模块/ terraform状态的输出或数据资源,这些资源使用每个子模块获取信息,但我有点迷路了!
main.tf
output.tf
variables.tf
submodule.tf
└── example
├── main.tf
└── output.tf
example/main.tf
module "create_redis_instance_example" {
source = "../."
stage = "eng"
redis_instances = {
test1 = {
memory_size_gb = 1
tier = "BASIC"
redis_config = {
maxmemory-policy = "allkeys-lru"
}
}
}
register_consul = true
consul_servicenames = [
"test1",
]
}
example/output.tf
output "redis_instances" {
value = module.create_redis_instance_example.redis_instances
}
main.tf
resource "google_redis_instance" "cache" {
provider = google-beta
for_each = var.redis_instances
name = "${var.stage}-${each.key}"
display_name = "${var.stage}-${each.key}"
memory_size_gb = each.value["memory_size_gb"]
auth_enabled = true
authorized_network = test
connect_mode = "PRIVATE_SERVICE_ACCESS"
redis_configs = each.value["redis_config"]
tier = each.value["tier"]
}
输出.tf
output "redis_instances" {
value = toset([
for i in google_redis_instance.cache : i.host
])
}
变量.tf
variable "stage" {
description = "Stage of the redis instance"
type = string
}
variable "redis_instances" {
description = "A list of bucket-suffixes with optional information"
type = map(object({
memory_size_gb = number
tier = string
redis_config = map(any)
}))
}
etc. etc.
子模块.tf
module "terraform_consul_dns" {
for_each = var.redis_instances
depends_on = [google_redis_instance.cache]
#ipaddress = "${google_redis_instance.cache[host]}"
#ipaddress = "${google_redis_instance.cache[each.value].host}"
#ipaddress = "${var.google_redis_instances[each.value.host]}"
ipaddress = "1.1.1.1"
nodename = "test1-${var.stage}-${each.key}"
services_with_ports = [
{
servicename = "test1-${var.stage}-${each.key}"
port = "1234"
},
]
}
所以当我们指定IP时:
ipaddress = "1.1.1.1"
这可以正常工作,但如前所述,我们希望使用输出、terraform 状态或数据源动态创建它。如您在上面看到的,尝试了一些东西,但没有任何效果:-(任何提示,非常欢迎!
【问题讨论】:
标签: google-cloud-platform terraform