Hendro
Hendro

Reputation: 11

How to iterate a list up to certain element/index in terraform?

This is simple in other language by using for or do while statement. Being a novice, I still can't figure out to do it in Terraform.

The real case that I need to do is to build a connection string to mongoDB replica-set service. The replication_factor is 3, 5 or 7 which means I need to create a list of 2, 4, or 6 hostnames/addresses.

I come up with the following code sofar:

locals {
  uri_list = [
    "@${alicloud_mongodb_instance.tyk_mongodb-test.id}1.mongodb.${var.region}.rds.aliyuncs.com:${var.db_port}",
    "@${alicloud_mongodb_instance.tyk_mongodb-test.id}2.mongodb.${var.region}.rds.aliyuncs.com:${var.db_port}",
    "@${alicloud_mongodb_instance.tyk_mongodb-test.id}3.mongodb.${var.region}.rds.aliyuncs.com:${var.db_port}",
    "@${alicloud_mongodb_instance.tyk_mongodb-test.id}4.mongodb.${var.region}.rds.aliyuncs.com:${var.db_port}",
    "@${alicloud_mongodb_instance.tyk_mongodb-test.id}5.mongodb.${var.region}.rds.aliyuncs.com:${var.db_port}",
    "@${alicloud_mongodb_instance.tyk_mongodb-test.id}6.mongodb.${var.region}.rds.aliyuncs.com:${var.db_port}"
  ]

  uri_list_out = [
    for uriname in local.uri_list :
      lower(uriname)
      if substr(uriname,length("${alicloud_mongodb_instance.tyk_mongodb-test.id}") + 1, 1) < var.mongos_config["${var.environment}"]["replication_factor"]
  ]
}

What I expect from

output "uri_list_out" {
  value = local.uri_list_out
}

is the first two elements of uri_list but instead I got only [1,2] for replication_factor = 3. Seems like if instruction in for also modify the output ???

I appreciate any hints to solve this problem.

Hendro

Upvotes: 0

Views: 973

Answers (1)

Iso
Iso

Reputation: 3238

I believe what you really need is the slice(list, startindex, endindex) function:

uri_list_out = [
  for uri in slice(local.uri_list, 0, var.mongos_config[var.environment]["replication_factor"] - 1) :
  replace(uri, "/^@/", "") # Remove the leading '@'
]


The docs for the slice function

> slice(["a", "b", "c", "d"], 1, 3)
[
  "b",
  "c",
]

Upvotes: 2

Related Questions