Home > OS >  Terraform change Hostname on subnet
Terraform change Hostname on subnet

Time:11-18

I am launching two ec2 instances with an autoscale group in terraform. The hostnames of the two ec2 need to be different based on the subnet (vpc_zone_identifier) its launched into (one should be xxxx-proxy01 and the other should be xxxx-proxy02). Is there a way i can do this?

### EC2, ASG, LAUNCH CONFIG
resource "aws_launch_configuration" "as_conf" {
  name          = "${local.name}-launchconfig"
  image_id      = "ami-xxxxxx"
  instance_type = "t4g.xxxxx"
  iam_instance_profile = aws_iam_instance_profile.xxxxx_profile.id
  key_name      = aws_key_pair.proxy.key_name
  user_data = templatefile("${path.module}/templates/user_data_proxy.tftpl", 
  {
    hostname              = format("%s-proxyd", local.name_prefix, 1)
    region                = var.region
    enable_x11_forwarding = "false"
  }
  )

}

resource "aws_autoscaling_group" "auto_scaler" {
  name                      = "${local.name}-group"
  max_size                  = 2
  min_size                  = 2
  health_check_grace_period = 30
  health_check_type         = "EC2"
  desired_capacity          = 2
  force_delete              = true
  launch_configuration      = aws_launch_configuration.as_conf.name
  vpc_zone_identifier       = [module.vpc.subnet_ids["app"][0], module.vpc.subnet_ids["app"][1]]
``

CodePudding user response:

You can do that. You have to amend your userdata to fetch the subnet-id, availability-zone-id or what you want from ec2 metadata.

  • Related