具有一个所需实例且没有负载均衡器的 AWS Auto-Scaling 组

AWS Auto-Scaling group with one desired instance and no load balancer

运行 一个用 CloudFormation 设计的系统,最近经历了一系列不幸的硬件故障。为了使这个使用不频繁的系统具有成本效益,它仅由单个实例支持并且不使用负载均衡器。我想给它添加一个自动缩放组,以确保至少不需要手动干预来应对未来类似的故障。但是,由于该系统是可公开访问的,因此实例需要关联一个弹性 IP,这正是我苦苦挣扎的地方。我的想法是 IP 将在启动后简单地重新关联到一个新实例。这里不需要关心用户会话等。

据我所知,不可能将单个弹性 IP 配置为在自动缩放组中重复使用(据我所知,我知道这是一个小众用例)。因此,我最终尝试在 CloudFormation::Init 期间重新关联 IP。有没有更优雅的解决方案?

正如您所指出的,您可以将用户数据脚本用于启动配置,以便在 Auto Scaling 启动新实例时,该脚本重新附加弹性 IP 地址或更新 Route 53 DNS 名称。

要附加弹性 IP 地址,脚本需要获取自己的实例 ID,然后 运行 附加命令:

#!/bin/bash
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id/)

aws ec2 associate-address --allocation-id xxx --instance-id $INSTANCE_ID

或者,您可以将 DNS 名称与实例相关联,并在实例启动时更新 DNS 名称以指向该实例。

来自Amazon Route 53: How to automatically update IP addresses without using Elastic IPs - DEV Community

#!/bin/bash
# Extract information about the Instance
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id/)
AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone/)
MY_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4/)

# Extract tags associated with instance
ZONE_TAG=$(aws ec2 describe-tags --region ${AZ::-1} --filters "Name=resource-id,Values=${INSTANCE_ID}" --query 'Tags[?Key==`AUTO_DNS_ZONE`].Value' --output text)
NAME_TAG=$(aws ec2 describe-tags --region ${AZ::-1} --filters "Name=resource-id,Values=${INSTANCE_ID}" --query 'Tags[?Key==`AUTO_DNS_NAME`].Value' --output text)

# Update Route 53 Record Set based on the Name tag to the current Public IP address of the Instance
aws route53 change-resource-record-sets --hosted-zone-id $ZONE_TAG --change-batch '{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"'$NAME_TAG'","Type":"A","TTL":300,"ResourceRecords":[{"Value":"'$MY_IP'"}]}}]}'

没有 "elegant" 方法可以自动为 Auto Scaling 组执行此类操作。