AWS Fargate - 如何使用 python boto3 获取任务的公共 IP 地址

joh*_*ohn 4 amazon-web-services amazon-ecs boto3 serverless aws-fargate

我正在使用以下 python 脚本创建新的 fargate 任务。

import boto3
import json


def handler():
  client = boto3.client('ecs')
  response = client.run_task(
  cluster='fargate-learning', # name of the cluster
  launchType = 'FARGATE',
  taskDefinition='fargate-learning:1', # replace with your task definition name and revision
  count = 1,
  platformVersion='LATEST',
  networkConfiguration={
        'awsvpcConfiguration': {
            'subnets': [
                'subnet-0a024d8ac87668b64', # replace with your public subnet or a private with NAT
            ],
            'assignPublicIp': 'ENABLED'
        }
    })

  print(response)
  return str(response)


if __name__ == '__main__':
    handler()
Run Code Online (Sandbox Code Playgroud)

这是我从 boto3 得到的回应。

https://jsonblob.com/5faf3ae6-bc31-11ea-8cae-53bd90c38587

尽管脚本正在分配公共 ip 地址,但我无法在响应中看到公共 ip 地址,我可以在网站上看到它。

aws fargate ip 地址

那么,如何使用 boto3 获取此公共 IP 地址?

谢谢

Mar*_*cin 5

这可以分两步完成:

  1. 使用describe_tasks获取与您的 fargateawsvpc接口关联的 ENI id 。ENI,例如价值eni-0c866df3faf8408d0,将被给予attachmentsdetails从调用的结果。

  2. 拥有 eni 后,您就可以使用EC2.NetworkInterface 了。例如:

eni_id = 'eni-0c866df3faf8408d0' # from step 1

eni = boto3.resource('ec2').NetworkInterface(eni_id)

print(eni.association_attribute['PublicIp'])
Run Code Online (Sandbox Code Playgroud)