Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

terraform - list creation from attribute in list of maps

I have the following list of maps:

variable "virtual_machines" {
  default = {
    "master1" = {
       name         = "z-ca-bdc-master1"
       worker_node  = false
       ipv4_address = "192.168.113.79"
       ipv4_netmask = "22"
       ipv4_gateway = "192.168.112.1"
       dns_server   = "192.168.112.2"
       ram          = 8192
       logical_cpu  = 4
       disk0_size   = 40
       disk1_size   = 0
    },
    "master2" =  {
       name         = "z-ca-bdc-master2"
       worker_node  = false
       ipv4_address = "192.168.113.80"
       ipv4_netmask = "22"
       ipv4_gateway = "192.168.112.1"
       dns_server   = "192.168.112.2"
       ram          = 8192
       logical_cpu  = 4
       disk0_size   = 40
       disk1_size   = 0
    },

What I would like to do is create a list of virtual machine names that I can assign to a variable, containing z-ca-bdc-master1, z-ca-bdc-master2 etc . . . how can I achieve this ?

My end goal is to be able to use this with template_file:

data "template_file" "k8s" {
  template = file("./templates/kubespray_inventory.tpl")

  vars = {
    k8s_master_host = values(var.virtual_machines)[*].name
    k8s_node_host   = values(var.virtual_machines)[*].name
  }
}
question from:https://stackoverflow.com/questions/65935775/list-creation-from-attribute-in-list-of-maps

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get the "list of virtual machine names" from your var.virtual_machines you can do:

locals {
   vm_names = values(var.virtual_machines)[*].name
}

Then you can use it when you need it as local.vm_names.

Update:

locals {
   vm_names = [for k,v in var.virtual_machines: v.name if v.worker_node]
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...