从 ASG 获取私有 IP

Get Private IP from ASG

我需要从 Terraform 配置的 EC2 实例的 Auto Scaling Group 输出私有 IP。如何从 ASG 获取私有 IP?

# Launch config for ASG
resource "aws_launch_configuration" "asg_conf" {
  name            = "ASG-Conf-${var.env}"
  image_id        = data.aws_ami.ubuntu.id                # Get image from data
  instance_type   = var.instance_type                     # use t2.micro ad default
  security_groups = [var.sg_app.id, var.sg_alb.id]        # SG for APP
  key_name        = var.ssh_key                           # SSH key for connection to EC2
  user_data       = file("./modules/ec2/shell/apache.sh") # install apache

  lifecycle {
    create_before_destroy = true
  }
}

# Auto Scaling Group
resource "aws_autoscaling_group" "asg" {
  count                = length(var.private_subnet_id) # count numbers of private subnets
  name                 = "ASG-${var.env}-${count.index + 1}"
  vpc_zone_identifier  = [var.private_subnet_id[count.index]]
  launch_configuration = aws_launch_configuration.asg_conf.name
  target_group_arns    = [var.alb_target.arn]

  min_size         = 1 # Min size of creating EC2
  max_size         = 1 # Max size of creating EC2

  health_check_grace_period = 120
  health_check_type         = "ELB" 
  force_delete              = true  

  lifecycle {
    create_before_destroy = true
  }

  tag {
    key                 = "Name"
    value               = "Webserver-ec2-${count.index + 1}"
    propagate_at_launch = true
  }
}

output {
  # How can i get this???
  value = aws_autoscaling_group.asg.private_ip
}

我的基础设施通过 ASG 在 2 个私有 AZ 中创建 1 个 EC2 实例,我需要来自这个 ASG 的输出 IP

您需要 custom data source 来获取 IP。但这真的没有多大意义,因为 ASG 中的实例可以随时被 AWS 更改,从而使您的 IP 过时。