Hi everyone
Currently I’m using variable list of object to input some variable , then use the variable to create a list of resource (google_compute_instance) , but now I’m facing some issue that some of the instance didn’t need a attribute block named “alias_ip_range” , so I leave “” to the variable value , and try to use conditional dynamic block in the list of resource , if the value of alias_ip isn’t equal to “” then it will have the attribute block in the resource , if it have IP in CIDR format then will create the attribute block inside the resource and the attribute value will be the value of variable alias_ip , but It keep having a issue that in the list of variable , even some objects’s alias_ip is “” , it still create the attribute block inside the resource then cause error , does anyone know how to use conditional dynamic block with list of resource , or it’s unachievable?
Variable I declared :
variable "gce" {
type = list(object({
hostname = string
ip = string
alias_ip = string
subnet = string
zone = string
instance_type = string
image = string
disk_type = string
boot_disk_size = string
second_disk_size = string
labels = map(string)
tag = list(string)
ssh_user = string
status = string
}))
}
And what I input to the variable list :
gce = [
{ ### server_1
hostname = "jason-test-1"
ip = "192.168.1.2"
alias_ip = "192.168.1.10/32"
subnet = module.VPC.subnet_1_id
zone = "asia-east1-a"
instance_type = "e2-small"
image = "projects/centos-cloud/global/images/centos-7-v20210512"
disk_type = "pd-balanced"
boot_disk_size = "20"
second_disk_size = "0"
labels = {
"test" = "jason"
}
tag = ["jason"]
ssh_user = "jason.hsu"
status = "RUNNING"
},
{ ### server_2
hostname = "jason-test-2"
ip = "192.168.1.3"
alias_ip = ""
subnet = module.VPC.subnet_1_id
zone = "asia-east1-c"
instance_type = "e2-small"
image = "projects/centos-cloud/global/images/centos-7-v20210512"
disk_type = "pd-balanced"
boot_disk_size = "20"
second_disk_size = "0"
labels = {
"test" = "jason"
}
tag = ["jason"]
ssh_user = "jason.hsu"
status = "RUNNING"
},
]
And here is my list of resource code :
resource "google_compute_instance" "gce" {
for_each = { for instance in var.gce : instance.hostname => instance }
name = each.value.hostname
machine_type = each.value.instance_type
tags = each.value.tag
zone = each.value.zone
desired_status = var.gce_status
network_interface {
subnetwork = each.value.subnet
access_config {
network_tier = "PREMIUM"
}
dynamic "alias_ip_range" {
for_each = {for instance in var.gce: instance.hostname=>instance if instance.alias_ip != "" }
content {
ip_cidr_range = each.value.alias_ip
}
}
}
service_account {
scopes = var.service_account_scope
}
boot_disk {
source = google_compute_disk.disk0[each.key].name
}
}
Does anyone know what’s wrong with my code ? Or it’s not possible to use conditional dynamic block inside list of resource?
Jason