弹性IP有其
局限性
。
如果你已经达到了一个地区的弹性IP地址的最大数量,而你想要的是一个持续的方式来连接到EC2实例,我建议使用route53记录,而不是使用IP地址。
我创建了一个route53记录,指向我的EC2实例的IP地址。当EC2停止时,该记录不会被改变。
而保持记录指向EC2地址的方法是通过
运行一个脚本,在EC2启动时改变route53记录
。
这里是我的EC2的
用户数据
。
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
# get the public ip address
# Ref: https://stackoverflow.com/questions/38679346/get-public-ip-address-on-current-ec2-instance
export public_ip=$(curl http://169.254.169.254/latest/meta-data/public-ipv4)
cat <<EOF > input.json
"Comment": "optional comment about the changes in this change batch request",
"Changes": [
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "my-domain.my-company.com",
"Type": "A",
"TTL": 300,
"ResourceRecords": [
"Value": "${public_ip}"
# change route53 record
/usr/bin/aws route53 change-resource-record-sets \
--hosted-zone-id <hosted_zone_of_my-company.com> \
--change-batch file://input.json >
这里我使用my-domain.my-company.com
作为我的EC2的route53记录。
通过使用这种方法,你可以得到一个指向你的EC2实例的route53记录。而且,当你停止和启动EC2时,该记录不会改变。所以你可以一直使用route53记录来连接到你的EC2。
记得给EC2实例分配一个有route53权限的IAM角色,这样你就可以无误地运行用户数据。
并且记住,我提供的用户数据是为亚马逊Linux 2使用的,这些命令可能对其他Linux发行版不起作用。