Search code examples
amazon-web-servicesterraformterraform-provider-aws

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


Here's the doc for AWS LB.

Here's the code sample I came up with, let's imagine I've got this 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"
  }
}

then I could enable Shield for it this way:

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

  tags = {
    Environment = "Dev"
  }
}

The issue is apparently there's an existing load balancer on AWS in my infra but my tf state was completely removed so I need to use a data source aws or something to retrieve (export) its arn instead of recreating it.


Solution

  • If you lost your state file, you can re-create it by importing your existing resources into TF. This would be much better then just using a data source for every single resource you lost from under TF control.

    But anyway, to use date source you can:

    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"
      }
    }