Search code examples
amazon-web-servicesterraformterraform-provider-awsaws-application-load-balancer

How to create a custom domain for an application load balancer using Terraform in AWS


I've been trying to figure out how to create application load balancer with a custom name using Terraform. So far I have this:

resource "aws_alb" "application_load_balancer" {
  name               = "${var.brand}-be-${var.environment_name}-load-balancer"
  tags               = local.tags
  load_balancer_type = "application"
  subnets            = data.aws_subnets.public_subnets.ids

  # security group
  security_groups    = [aws_security_group.sg_load_balancer.id]
}

# Hosted Zone for new-dev.foocorp.com
resource "aws_route53_zone" "zone_dev" {
  name    = "new-dev.foocorp.com"
  comment = "Hosted Zone for new-dev.foocorp.com"
  records = [ aws_alb.application_load_balancer.dns_name ]

  tags = merge(local.tags, {
    Name = "new-dev.foocorp.com"
  })
}

However, I'm getting:

╷
│ Error: Unsupported argument
│ 
│   on main.tf line 323, in resource "aws_route53_zone" "zone_dev":
│  323:   records = [ aws_alb.application_load_balancer.dns_name ]
│ 
│ An argument named "records" is not expected here.
╵

From what I understand, it's not possible to tell the ALB to use a specific domain name and I have to wait for it to be created in order to then get a reference to it's domain and use that when creating a new Route 53 entry? Is this correct? Is there a better way to do this?

Instead of http://foo-bar-load-balancer-1234567890.us-east-1.elb.amazonaws.com/, I would like to have http://new-dev.foocorp.com/.

In addition, the DNS records in AWS have not been Terraformed yet and the zones are in the root account and I'm trying to do this in a sub-account where the dev environment will be. Will I need some IAM policies for this?


Solution

  • To define records you have to use aws_route53_record, not aws_route53_zone. Example is in TF docs, but it should be:

    resource "aws_route53_record" "new-dev" {
      zone_id = aws_route53_zone.zone_dev.zone_id
      name    = "new-dev.foocorp.com"
      type    = "A"
      ttl     = 300
      records = [aws_alb.application_load_balancer.dns_name]
    }