Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude a given string from the given list in terraform

Tags:

terraform

I would like to exclude a given string from the list of string in terraform

example: I have following data source as a variable

region_list = data.oci_identity_region_subscriptions.region_subscriptions.region_subscriptions.*.region_name

Now, I would like to exclude a region from it. Region "us-ashburn-1"

exclude ("us-ashburn-1") form region_list. Any thoughts on how to do that?

like image 702
Amman Avatar asked Dec 10 '25 18:12

Amman


2 Answers

Easiest way to get rid of a set of values in another set is to use setsubtract():

locals {
  regions = ["us-west-2", "us-west-1", "us-east-2", "us-ashburn-1"]
}

output "excluded" {
  value = setsubtract(local.regions, ["us-ashburn-1"])
}

outputs:

excluded = [
  "us-east-2",
  "us-west-1",
  "us-west-2",
]

if you want to keep the order or duplicates in a list, then using a for expression as already mentioned in another answer is preferred.

like image 161
mariux Avatar answered Dec 13 '25 18:12

mariux


You can do this by using for loop and if condition in terraform.

Example terraform configuration,

variable "regions" {
  type    = list
  default = ["us-west-2", "us-west-1", "us-east-2", "us-east-1"]
}

output "excluded" {
  value = [for region in var.regions : region if region != "us-east-1"]
}

The above config will output all the region except us-east-1.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

excluded = [
  "us-west-2",
  "us-west-1",
  "us-east-2",
]
like image 23
aashitvyas Avatar answered Dec 13 '25 19:12

aashitvyas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!