创建并运行以下示例代码后,我试图获取我的ec2实例的公共IP地址:
instance = ec2_resource.create_instances(ImageId='ami-a0cfeed8',
MinCount=1, MaxCount=1, InstanceType='t2.micro', SecurityGroups= .
['some_security_group'], KeyName='some_key')
instance[0].wait_until_running()
print(instance[0].public_ip_address)
但是,即使在aws控制台中可以看到公共ip,上述代码打印的值仍为None
。如果我在实例的所有状态检查完成后尝试打印该值,则可以正常打印。
答案 0 :(得分:0)
要使用@Michael-sqlbot的答案并将其全部集中在一个地方,这是此代码的工作方式:
import boto3
# create the session and resource objects
boto3_session = boto3.Session(profile_name=some_profile_you_configured)
ec2_resource = boto3_session('ec2')
# create the instance
instance = ec2_resource.create_instances(ImageId='ami-a0cfeed8',
MinCount=1, MaxCount=1, InstanceType='t2.micro', SecurityGroups= .
['some_security_group'], KeyName='some_key')
# use the boto3 waiter
instance[0].wait_until_running()
# reload the instance object
instance[0].reload()
public_ip = instance[0].public_ip_address
print(public_ip)