如何从列表迭代到输出值?

时间:2019-08-05 17:54:07

标签: terraform

我要从terraform 12获取,请调用值列表

data "oci_core_instances" "test_instances" {
    #Required
    compartment_id = "${var.compartment_ocid}"

    availability_domain = "${data.oci_identity_availability_domains.ads.availability_domains[0].name}"
}

// numInstances = 3 for my case 
locals {
  numInstances = length(data.oci_core_instances.test_instances.instances)
}

我想像(伪代码)那样进行迭代:

# Output the result single element
output "format_instances_name_state" {
         value = "${
           for (i=0 ; i< 3; i++)
           format("%s=>%s",data.oci_core_instances.test_instances.instances[i].display_name,data.oci_core_instances.test_instances.instances[i].state)
           } " 
}

我该如何在Terraform中执行此操作?

我已经尝试过了:

# Output the result single element
output "format_instances_name_state" {
         value = "${
           for i in local.numInstances :
           format("%s=>%s",data.oci_core_instances.test_instances.instances[i].display_name,data.oci_core_instances.test_instances.instances[i].state)
           } " 
}

但我遇到此错误:

Error: Extra characters after interpolation expression

  on main.tf line 64, in output "format_instances_state_element_single":
  63:
  64:            for i in local.numInstances :

Expected a closing brace to end the interpolation expression, but found extra
characters.

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您似乎真正想要的是从显示名称到状态的映射,在这种情况下,以下表达式将产生该映射:

output "instance_states" {
  value = {
    for inst in data.oci_core_instances.test_instances.instances : inst.display_name => inst.state
  }
}

如果由于某些原因确实需要里面带有=>的字符串列表,可以修改上面的字符串以得到它,就像这样:

output "format_instances_state_element_single" {
  value = [
    for inst in data.oci_core_instances.test_instances.instances : "${inst.display_name}=>${inst.state}"
  ]
}

在第二种情况下,for表达式用[ ]括号而不是括号{ }标记,这意味着它将产生列表结果而不是地图结果。