【问题标题】:Can you get the public IP address of an EC2 instance能否获取 EC2 实例的公网 IP 地址
【发布时间】:2021-04-06 01:41:06
【问题描述】:

嗨,我是 python 代码的新手,想知道有没有办法创建一个实例,然后将 IP 地址打印回控制台,目前我可以创建一个实例并打印回实例 ID

#!/usr/bin/env python3
import boto3
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
    ImageId='ami-0713f98de93617bb4',
    MinCount=1,
    MaxCount=1,
    KeyName='JamieTest',
    SecurityGroupIds=['sg-0273f9f172ba795ab'],
    InstanceType='t2.nano')
print ('Your instance has been created, the instance ID is :' + instance[0].id)

【问题讨论】:

  • 它应该在instance[0].public_ip_addressboto3.amazonaws.com/v1/documentation/api/latest/reference/…
  • 所以如果我这样做,打印('您的实例已创建,实例 ID 为:' + instance[0].id),+ instance[0].public_ip_address)它不会工作,因为创建 ip 需要几秒钟的时间有没有办法告诉它等到实例运行后再打印它?
  • 可以在打印id之前检查实例状态是否正在运行。 if instance[0].state['Name'] == 'running': print('your instance ip address' + instance[0].public_ip_address)

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


【解决方案1】:

create_instances() 返回ec2.Instance 对象的列表,每个对象可能有一个public_ip_address 属性(如果实例具有公共IP 地址)。

这样

print ('Your instance public IP address is : ' + instance[0].public_ip_address)

【讨论】:

【解决方案2】:

你可以使用describe_instances()方法:

import time

session = boto3.Session(profile_name='default')
ec2_client = session.client('ec2')
instance_id = instance[0].id #your instance id here

cycle = True
    while cycle:
        time.sleep(0.1)  #any value of your choice              
        allinstances = ec2_client.describe_instances().get('Reservations')
        for i, group in enumerate(allinstances):
             for j, instance in enumerate(group.get('Instances')):
                  if instance.get("InstanceId") == instance_id:
                      externalip = instance.get('PublicIpAddress')
                      if externalip is not None: cycle = False
print('External IP:', externalip)

【讨论】:

    猜你喜欢
    • 2014-09-16
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多