如何使用数据源通过 Terraform 找出 AWS 负载均衡器的 ARN?

How can I use a data source to find out the ARN of AWS load balancer using terraform?

这是 AWS LB 的 the doc

这是我想出的代码示例,假设我有这个 LB:

resource "aws_lb" "test" {
  name               = "test-lb-tf"
  internal           = false
  load_balancer_type = "network"
  subnets            = aws_subnet.public.*.id

  enable_deletion_protection = true

  tags = {
    Environment = "Dev"
  }
}

然后我可以通过这种方式为其启用 Shield:

resource "aws_shield_protection" "example" {
  name         = "example"
  resource_arn = aws_lb.test.id

  tags = {
    Environment = "Dev"
  }
}

问题显然是我的基础设施中 AWS 上有一个现有的负载均衡器,但我的 tf 状态已完全删除,所以我需要使用数据源 aws 或其他东西来检索(导出)它的 arn,而不是重新创建它。

如果您丢失了您的状态文件,您可以通过importing您现有的资源到 TF 中重新创建它。这比在 TF 控制下丢失的每个资源都使用数据源要好得多。

但无论如何,要使用 date source,您可以:

data "aws_lb" "test" {
  name = "test-lb-tf"
}

resource "aws_shield_protection" "example" {
  name         = "example"
  resource_arn = data.aws_lb.test.id

  tags = {
    Environment = "Dev"
  }
}