You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Terraform数据源获取已存在AWS负载均衡器的ARN

解决方案

你可以通过两种方式获取已有LB的ARN,无需重建现有负载均衡器:

方式1:使用Terraform AWS LB数据源读取资源信息

该方式适用于仅需要获取LB参数、不需要通过Terraform管理该LB生命周期的场景,直接在配置中添加数据源块即可:

data "aws_lb" "existing_lb" {
  # 替换为你现有负载均衡器的实际名称
  name = "test-lb-tf"
  # 也可通过标签匹配过滤目标LB,示例如下:
  # tags = {
  #   Environment = "Dev"
  # }
}

获取到LB信息后,直接引用数据源的arn属性配置Shield防护即可:

resource "aws_shield_protection" "example" {
  name         = "example"
  resource_arn = data.aws_lb.existing_lb.arn
  tags = {
    Environment = "Dev"
  }
}

方式2:将现有LB导入到Terraform状态文件

该方式适用于后续需要继续通过Terraform管理该LB配置的场景:

  1. 先在Terraform配置文件中编写和现有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"
  }
}
  1. 执行导入命令,将现有LB资源关联到上述资源块,不会触发资源重建:
    terraform import aws_lb.test <替换为现有LB的实际ARN或名称>
  2. 导入完成后即可正常通过aws_lb.test.id(即LB的ARN)关联Shield防护资源:
resource "aws_shield_protection" "example" {
  name         = "example"
  resource_arn = aws_lb.test.id
  tags = {
    Environment = "Dev"
  }
}

内容的提问来源于stack exchange,提问作者Alex Ivanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 17:06:04