在cloud-init脚本中运行`apt-get update`时出现networking错误

昨天,我在AWS中build立了自己的第一个Autoscaling组。 我写了一个cloud-init / userdata脚本来安装我的应用程序,我testing了它40次,没有任何错误。 就在我回家之前,它突然停止了工作,新的事例从未变得健康,并在宽限期到期后最终终止。

今天早上我进来发现问题依然存在。 我SSH到一个实例,并看看在cloud-init-output.log文件,并发现以下内容:

Err:1 http://ap-southeast-2.ec2.archive.ubuntu.com/ubuntu xenial InRelease Could not connect to ap-southeast-2.ec2.archive.ubuntu.com:80 (54.253.131.141), connection timed out [IP: 54.253.131.141 80] Err:2 http://ap-southeast-2.ec2.archive.ubuntu.com/ubuntu xenial-updates InRelease Unable to connect to ap-southeast-2.ec2.archive.ubuntu.com:http: [IP: 54.253.131.141 80] Err:3 http://ap-southeast-2.ec2.archive.ubuntu.com/ubuntu xenial-backports InRelease Unable to connect to ap-southeast-2.ec2.archive.ubuntu.com:http: [IP: 54.253.131.141 80] Err:4 http://security.ubuntu.com/ubuntu xenial-security InRelease Cannot initiate the connection to security.ubuntu.com:80 (2001:67c:1360:8001::21). - connect (101: Network is unreachable) [IP: 2001:67c:1360:8001::21 80] Reading package lists... W: Failed to fetch http://ap-southeast-2.ec2.archive.ubuntu.com/ubuntu/dists/xenial/InRelease Could not connect to ap-southeast-2.ec2.archive.ubuntu.com:80 (54.253.131.141), connection timed out [IP: 54.253.131.141 80] W: Failed to fetch http://ap-southeast-2.ec2.archive.ubuntu.com/ubuntu/dists/xenial-updates/InRelease Unable to connect to ap-southeast-2.ec2.archive.ubuntu.com:http: [IP: 54.253.131.141 80] W: Failed to fetch http://ap-southeast-2.ec2.archive.ubuntu.com/ubuntu/dists/xenial-backports/InRelease Unable to connect to ap-southeast-2.ec2.archive.ubuntu.com:http: [IP: 54.253.131.141 80] W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/xenial-security/InRelease Cannot initiate the connection to security.ubuntu.com:80 (2001:67c:1360:8001::21). - connect (101: Network is unreachable) [IP: 2001:67c:1360:8001::21 80] W: Some index files failed to download. They have been ignored, or old ones used instead. 

这是由脚本顶部的sudo apt-get update命令造成的。 在这之后,我的sudo apt-get -y install命令中的多个软件包无法安装,这会阻止我的应用程序工作。

奇怪的是,如果我通过SSH运行sudo apt-get update ,它没有任何错误,只有在cloud-init脚本中不起作用。 我的直觉是,也许实例还没有连接到networking的脚本执行时? 如果是这样的话,我该如何解决这个问题呢?

编辑:我不能再重现这个问题。 我已经将其添加到脚本的顶部以尝试防止问题重新发生:

 until ping -c1 ap-southeast-2.ec2.archive.ubuntu.com &>/dev/null; do echo "waiting for networking to initialise"; done 

但是cloud-init-output.log中没有“等待networking初始化”的消息,所以看起来这个代码没有做任何事情,问题可能是暂时的。 如果有人知道是什么原因导致这个问题,以及更可靠的减轻方法是什么,请让我知道。

我想清楚是什么问题,我觉得有点傻。 事实certificate,一个实例需要一个公共IP才能访问VPC之外的服务器。 我想我假设会有某种NAT允许服务器在没有公共IP的情况下拨出,但现在我看到,如果我想要,我必须使用NAT网关自行设置它。

这个问题很难解决的原因是,为了SSH和查看日志我分配一个弹性IP的实例,然后导致脚本成功。