【问题标题】:Get the public IPv4 address of a newly created amazon ec2 instance with boto3使用 boto3 获取新创建的 amazon ec2 实例的公共 IPv4 地址
【发布时间】:2022-02-23 00:59:29
【问题描述】:

我正在使用 boto3 创建一个 ec2 实例,我想打印该新实例的 IP 地址。

ec2 = boto3.resource('ec2')

# create the instance 
new_instance = ec2.create_instances(
    ImageId='###', 
    MinCount = 1, 
    MaxCount = 1, 
    InstanceType = 't2.nano',
    KeyName = "key",
    SecurityGroupIds = ["###"]
)

... wait until running ...
ip = new_instance[0].ipv4 # something like this

有没有办法在它运行后做这样的事情?

【问题讨论】:

标签: python amazon-web-services amazon-ec2 boto3


【解决方案1】:

ec2.create_instances 返回ec2.Instance objects 的列表。 ec2.Instance 对象有一个名为private_ip_address 的属性。您可以使用它来获取私有 IP 地址。

附注(基于您的代码示例中的 cmets)您还可以使用 wait_until_running 服务员让您的代码暂停,直到实例运行。

# create the instance 
new_instance = ec2.create_instances(...)

# use a waiter on the instance to wait until running
new_instance[0].wait_until_running()

ip = new_instance[0].private_ip_address
public_ip = new_instance[0].public_ip_address

【讨论】:

  • 有没有办法在创建时获取公网ip地址?我想在创建后通过 ssh 连接到服务器。
  • 查看链接文档。有一个“public_ip_address”应该给你
  • 您必须致电new_instance[0].reload()public_ip_address 将是None
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 2016-12-05
  • 2017-06-25
  • 2022-01-02
  • 1970-01-01
  • 2016-04-16
  • 2012-03-03
相关资源
最近更新 更多