【问题标题】:How to get public ip from a network interface attached to an ECS task with boto3如何使用 boto3 从连接到 ECS 任务的网络接口获取公共 IP
【发布时间】:2018-12-18 23:09:48
【问题描述】:

我需要一些帮助。

我正在尝试使用 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强>。 有人可以帮帮我吗?

谢谢!

【问题讨论】:

  • 你确定 eni-r2d2 存在吗? nia.id 可以只返回你给它的东西。它不必进行网络调用,也不必证明它是有效的。
  • @Sam 是的,当然,资源存在,但由于某种原因,响应仍然是空白的。我可以使用另一种方法解决它,如果您有兴趣查看下面的解决方案。感谢您的回复!

标签: python boto3 aws-ecs aws-fargate


【解决方案1】:

我认为您不能仅使用 boto3 来做到这一点(编辑:OP 证明并非如此!),因此除非您有使用它的要求,否则请使用元数据服务。

AWS 文档会告诉您从容器内调用元数据服务并解析公共 IP 的 json 响应。 Documentation here。注意当 ecs-agent 版本

这样的事情应该在 Fargate 的容器中工作:

import requests

try:
    response = requests.get('http://169.254.170.2/v2/metadata').json()  
    for container in response.get('Containers', []):
        if 'Networks' in container:
            for network in container.get('Networks', []):
                if 'IPv4Addresses' in network:
                    for ipv4address in network.get('IPv4Addresses', []):
                        print ipv4address # or do something else
except requests.exceptions.RequestException:
    # parse the smoldering remains of the response object

【讨论】:

    【解决方案2】:

    我可以解决它!代码如下:

    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'
    

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2021-10-15
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2016-12-05
      • 1970-01-01
      • 2020-12-15
      相关资源
      最近更新 更多