Search code examples
terraformterraform-template-file

Inappropriate value for attribute vars element string required


Error while applying the terraformI am working on terraform with cloud-init deployment. i want to fetch the ip addresses from locals.tf file in data template_file vars block. when i do terraform apply it will show me "Inappropriate value for attribute vars element string required". locals.tf

locals {
  workers = {
    "worker-1" = { host_name = "wrkr-1", vm_ip = "90" }
    "worker-2" = { host_name = "wrkr-2", vm_ip = "91" }
    "worker-3" = { host_name = "wrkr-3", vm_ip = "92" }
    "worker-4" = { host_name = "wrkr-4", vm_ip = "93" }
    "worker-5" = { host_name = "wrkr-5", vm_ip = "94" }
    "worker-6" = { host_name = "wrkr-6", vm_ip = "95" }    
  }
  controllers = {
    "controllers-1" = { host_name = "ctrl-1", vm_ip = "87" }
    "controllers-2" = { host_name = "ctrl-2", vm_ip = "88" }
    "controllers-3" = { host_name = "ctrl-3", vm_ip = "89" }
  }
}

config.tf

data template_file "lb_userdata" {
  template = file("${path.module}/cloud-init/lb-cloud-config.yaml")
  vars = {
    network_cidr = var.network_cidr
    controller_ip = local.controllers
    ip_address  = var.loadbalancer_ip
  }
}

Any help appreciated

Thanks


Solution

  • Thanks I have found a trick how we can achieve this. data file is as below

    data template_file "lb_userdata" {
      template = file("${path.module}/cloud-init/lb-cloud-config.yaml")
      vars = {
        network_cidr = var.network_cidr
        controller_ip = join(",",([for k in local.controllers: k.vm_ip ]))
        ip_address  = var.loadbalancer_ip
      }
    }
    

    I used join function and use for loop to get the value as a string.

    here is my lb_cloud_config.yaml file

    %{~ for f in split(",",controller_ip) ~}
    server ${network_cidr}.${f}:30793
    %{~ endfor ~}