After looking through lots of documentations I came to the conclusion that it can't be done reliably with the information that is exposed through the APIs. The answer by John covers important details on the factors that determine if an EC2 instance will be assigned a public IP on first boot.
Given that information it's possible to determine if a newly launched EC2 instance will get a public IP, which is essentially controlled by the AssociatePublicIpAddress
parameter. This can be set explicitly while starting an instance (see doc1 - Example 5, doc2) and will have a default value that depends on the subnet the instance is launched in.
If the instance is launched in a subnet that has MapPublicIPOnLaunch
set to true, this defaults to true and if MapPublicIPOnLaunch
is set to false, it defaults to false. However, you can overwrite this default.
The information if a public IP is supposed to be associated is retained on the ENI, if the docs are to be believed (emphasis mine).
When you create a network interface, it inherits the public IPv4 addressing attribute from the subnet. If you later modify the public IPv4 addressing attribute of the subnet, the network interface keeps the setting that was in effect when it was created. If you launch an instance and specify an existing network interface as the primary network interface, the public IPv4 address attribute is determined by this network interface.
Unfortunately it doesn't seem like any API exposes the value of this internal Flag - neither the DescribeInstances nor the DescribeNetworkInterfaces API-call include it in the response.
As a result of that, you can make an educated guess based on the subnet the instance lives in, but however educated, it is still a guess, because this only works, if the default for AssociatePublicIpAddress
hasn't been changed. The only way to determine that reliably is to turn the instance on, to a DescribeInstances
on it and check if it has received a public IP.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…