amazon-web-servicesamazon-ec2scale

How Do I Set Unique, Descriptive Hostnames for AWS Auto Scaled Instances?


My ASG assigns scaled nodes the aws:autoscaling:groupName to each Instance Name. This yields multiple instances with the same Instance Name.

For example:

Instance Name Instance ID
dev-test-my-ASG i-05w50iy3g34co7uea
dev-test-my-ASG i-0mri5p3or7k6dxxv5
dev-test-my-ASG i-0ak1ws9m049nt00b5
dev-test-my-ASG i-0408tzorvsg5l74zq
dev-test-my-ASG i-0qw480y71ddns2vsv
dev-test-my-ASG i-0y4c2t7zv5jytt7c7

To avoid naming collisions, these scaled instances default to IP name for Hostname type.

For example:

Hostname Instance ID
ip-192-168-10-123.ec2.internal i-05w50iy3g34co7uea
ip-192-168-10-3.ec2.internal i-05w50iy3g34co7uea
ip-192-168-10-2.ec2.internal i-0mri5p3or7k6dxxv5
ip-192-168-10-23.ec2.internal i-0ak1ws9m049nt00b5
ip-192-168-10-231.ec2.internal i-0408tzorvsg5l74zq
ip-192-168-10-213.ec2.internal i-0qw480y71ddns2vsv
ip-192-168-10-26.ec2.internal i-0y4c2t7zv5jytt7c7

How can I configure my launch template to provide unique hostnames for the auto-scaled EC2 instances, so that they include the ASG name in the hostname without defaulting to the IP address.

For example:

I expect a method to create unique, descriptive names for the scaled nodes.


Solution

  • To change the hostname in the OS, you can follow this documentation

    test if this works with your other software.

    If you are looking to do this for an Auto Scaling Group, I would use something like the USERDATA section of the EC2 template and have something like the following:

    #!/bin/bash
    echo "preserve_hostname: true">>/etc/cloud/cloud.cfg
    MY_HOSTNAME=dev-test-my-ASG-$RANDOM    
    hostnamectl set-hostname $MY_HOSTNAME
    echo "HOSTNAME=$MY_HOSTNAME">>/etc/sysconfig/network
    echo "127.0.0.1   $MY_HOSTNAME $MY_HOSTNAME.localdomain localhost4 localhost4.localdomain4">/etc/hosts
    echo "::1         localhost6 localhost6.localdomain6">>/etc/hosts
    

    May have to issue a reboot command at the end of this, but see if it works without it.