如何为 ASG 实例设置基于序数的 DNS 名称

How can I set ordinal based DNS names for ASG instances

问题

在我的开发环境中,我想为 ECS 集群主机创建易于记忆的有序 dns 名称。当我们部署时,我们从 1 台主机扩展到 2 台主机,然后 drain/scale 缩回。

目前我们像这样使用用户数据所以设置dns名称

INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
INSTANCE_IP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)
RECORD_CONFIG="/tmp/ecs-a-record.json"

cat >>$RECORD_CONFIG << ROUTE53
{
  "Comment": "Create a friendly DNS name for the DOD ECS host",
  "Changes": [{
  "Action": "UPSERT",
    "ResourceRecordSet": {
      "Name": "dev-ecs.ourenv.dev",
      "Type": "A",
      "TTL": 300,
      "ResourceRecords": [{ "Value": "$INSTANCE_IP"}]
    }
  }]
}
ROUTE53

aws route53 change-resource-record-sets --hosted-zone-id ... --change-batch file://$RECORD_CONFIG

我认为我的选择是

有人知道更优雅的解决方案吗?

因此,下面是我们如何管理开发测试环境的便利 fqdns 记录。当我们扩展集群以确保第 2/3 台主机不会尝试使用第 1 台主机的名称时,这一点变得很重要

checkHostExists() {
  host=
  nc -z $host 22 >> /dev/null 2>&1 ; echo $?
}

findDevTestDNSName() {
  base_name=
  domain=
  count=1
  name=$(printf "%s%02d.%s" $base_name $count $domain)

  while [[ "$(checkHostExists $name)" -eq "0"  ]]
  do
    count=$((count+1))
    name=$(printf "%s%02d.%s" $base_name $count $domain)
  done
  echo $name
}


##
# Main Userdata context
#
# Please Note: This is a Terraform template
#  ${foo} refers to a foo variable passed to the template
#  $${bar} refers to an actual env variable
# when terraform resolves the template then tf vars are replaced with
# concrete values in the usedata
##

# lookup the instance ID
INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
INSTANCE_IP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)

if [[ "${cluster_name}" =~ "devtest" ]]; then
  # create a friendly hostname for the ECS host if this is a development test env

  # install nmap/nc for host probing
  yum install -y nmap

  ECS_HOST_FQDNS=$(findDevTestDNSName ${cluster_name}-ecs ${dns_domain})
  HOST_NAME=$(echo $ECS_HOST_FQDNS|sed 's/\..*//')
  echo Setting DevTest ECS Hostname: $${ECS_HOST_FQDNS}

    RECORD_CONFIG="/tmp/ecs-a-record.json"
    cat >>$RECORD_CONFIG << ROUTE53
    {
      "Comment": "Create a friendly DNS name for the ${cluster_name} ECS host",
      "Changes": [{
      "Action": "UPSERT",
        "ResourceRecordSet": {
          "Name": "$${ECS_HOST_FQDNS}",
          "Type": "A",
          "TTL": 300,
          "ResourceRecords": [{ "Value": "$INSTANCE_IP"}]
        }
      }]
    }
    ROUTE53

    aws route53 change-resource-record-sets --hosted-zone-id ${dns_zone_id} --change-batch file://$RECORD_CONFIG

fi