英文:
Does Terraform support nested try blocks?
问题
有可能尝试查找两个资源,如果没有找到任何一个则报错吗?
示例:
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"))
}
也许有更好的配置方法吗?
英文:
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?
答案1
得分: 1
> try 依次评估其所有参数表达式,并返回第一个不产生任何错误的表达式的结果。
因此,您可以执行:
```terraform
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未找到")
}
try
返回第一个不引发错误的表达式,本例中即您定义的字符串,这将意味着错误,因为"LB未找到"显然不是有效的 ARN。
│ 错误: "arn" (LB未找到) 是无效的 ARN:arn: 无效前缀
<details>
<summary>英文:</summary>
> 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:
```terraform
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论