0

Would it be possible to attempt to find two resources and error if none of them are found?

Example:

data "aws_resourcegroupstaggingapi_resources" "elb_classic" {
  resource_type_filters = ["elasticloadbalancing:loadbalancer"]
  depends_on = [  ]

  tag_filter {
    key    = "kubernetes.io/service-name"
    values = ["service-name"]
  }
}

data "aws_resourcegroupstaggingapi_resources" "elb_v2" {
  resource_type_filters = ["elasticloadbalancing:loadbalancer"]
  depends_on = [  ]

  tag_filter {
    key    = "service.k8s.aws/stack"
    values = ["service-name"]
  }
}

data "aws_lb" "lb" {
  arn = try(data.aws_resourcegroupstaggingapi_resources.elb_classic.resource_tag_mapping_list[0].resource_arn, try(data.aws_resourcegroupstaggingapi_resources.elb_v2.resource_tag_mapping_list[0].resource_arn, "LB not found"))
}

Is there perhaps a better way of configuring this?

  • Well, you could use local variables and then maybe the ternary operator, but the result would be the same if the data sources do not return anything. – Marko E Jul 27 '23 at 10:46
  • 1
    Although no examples of this are in the documentation, the `try` documentation does mention the argument is variadic, and therefore you do not need to nest the invocations here. – Matthew Schuchard Jul 27 '23 at 12:10

1 Answers1

1

try evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors.

so you can do:

data "aws_lb" "lb" {
  arn = try(data.aws_resourcegroupstaggingapi_resources.elb_classic.resource_tag_mapping_list[0].resource_arn, data.aws_resourcegroupstaggingapi_resources.elb_v2.resource_tag_mapping_list[0].resource_arn, "LB not found")
}

try returns the first expression that does not throw an error, which in this case is the string you've defined, which in this case will imply an error given that "LB not found" is certainly not a valid ARN.

│ Error: "arn" (LB not found) is an invalid ARN: arn: invalid prefix

Paolo
  • 21,270
  • 6
  • 38
  • 69