首页 > 解决方案 > 如何使用 boto3 从连接到 ECS 任务的网络接口获取公共 IP

问题描述

我需要一些帮助。

我正在尝试使用 boto3 从网络接口获取公共 IP,由于某种原因,我收到以下错误:

ec2 = boto3.resource('ec2')
nia = ec2.NetworkInterfaceAssociation('eni-r2d2')
nia.id  # I can obtain the id without any issue
# 'eni-r2d2'
nia.public_ip
# /usr/local/lib/python3.6/site-packages/boto3/resources/factory.py in property_loader(self)
#     343                             self.__class__.__name__))
#     344
# --> 345             return self.meta.data.get(name)
#     346
#     347         property_loader.__name__ = str(snake_cased)
# 
# AttributeError: 'NoneType' object has no attribute 'get'

注意:网络接口属于ECS任务,启动类型为FARGATE,网络模式为awsvpc。有人能帮助我吗?

谢谢!

标签: pythonboto3aws-ecsaws-fargate

解决方案


我可以解决它!这是代码:

import boto3

session = boto3.Session(
  aws_access_key_id='...',
  aws_secret_access_key='...',
  region_name='...',
)
ec2 = session.client('ec2')
response = ec2.describe_network_interfaces(
    NetworkInterfaceIds=['eni-r2d2'],
)
interface = response['NetworkInterfaces'][0]
interface['Association']['PublicIp']
# '1.2.3.4'

推荐阅读