Search code examples
amazon-web-servicesterraformipvpc

Terraform assigning elastic IPs to auto scaling group instances


I've just been using Terraform for a few days now and looking for guidance. I have two subnets under a vpc (private, public). What I'm trying to do is assign elastic IPs to each instance that the auto scaling group creates, or remove the elastic IP when the instance is destroyed. I've tried to follow this link: Auto assign public IPs to my instance created by an austo-scaling group

So I've created an elastic load balancer listening on port 80 and assigned it to the auto scaling group and public subnet. I've gone through the AWS docs for elastic load balancing here: https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/how-elastic-load-balancing-works.html and various others AWS provides, so I could just be thinking about the problem incorrectly. I'm unsure of how to assign the public subnet's auto scaling group's EC2 instances an elastic IP, so the only thing I can think of is it automatically handled through the elastic load balancer?

The first solution I thought of (not even sure if I can do this without being an EC2 instance), and the second is from the instructions within the first link

  1. Assign an elastic IP to the elastic load balancer instead of the EC2 instances, then point a DNS record to that elastic IP and then let the load balancer handle the rest
  2. Make a DNS record to point to the DNS of the load balancer

If the second option is correct, I will try it again and my .tf must just be incorrect. However if there are any better options, I'd like to hear any suggestions that people have used!

Any guides, docs, or guidance would be great!


Solution

  • The second option is correct. You need to point your DNS record to your load balancer. In terraform that looks something like this (your ELB or ALB resource will vary):

    # Set up the load balancer
    resource "aws_alb" "example" {
      name            = "example"
      internal        = false
      security_groups = ["${aws_security_group.example.id}"]
      subnets         = ["${data.aws_subnet_ids.example.ids}"]
    }
    
    # Get the zone id for the zone you are setting this in
    data "aws_route53_zone" "example" {
      name         = "example.com"
      private_zone = false
    }
    
    # Set the record, replace <your dns name> with the name you want to use
    resource "aws_route53_record" "build" {
      provider = "aws"
      zone_id  = "${data.aws_route53_zone.example.zone_id}"
      name     = "<your dns name>"
      type     = "A"
    
      alias {
        name                   = "${aws_alb.example.dns_name}"
        zone_id                = "${aws_alb.eaxmple.zone_id}"
        evaluate_target_health = false
      }
    }