4

I am creating new fargate task by using the following python script.

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()

And here is the response I am getting from boto3.

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

I can not see the public ip address in response although the script is assigning the public ip address and I can see it on website.

aws fargate ip address

So, how can I get this public ip address by using boto3?

Thanks

john
  • 2,324
  • 3
  • 20
  • 37

2 Answers2

7

This can be done in two steps:

  1. Use describe_tasks to get ENI id associated with your fargate awsvpc interface. The value of eni, e.g. eni-0c866df3faf8408d0, will be given in attachments and details from the result of the call.

  2. Once you have the eni, then you can use EC2.NetworkInterface. For example:

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

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

print(eni.association_attribute['PublicIp'])
Marcin
  • 215,873
  • 14
  • 235
  • 294
3

Tried implementing @Marcin 's answers as a function. Hope this can be helpful

def get_service_ips(cluster, tasks):
    tasks_detail = ecs.describe_tasks(
        cluster=cluster,
        tasks=tasks
    )
    
    # first get the ENIs
    enis = []
    for task in tasks_detail.get("tasks", []):
        for attachment in task.get("attachments", []):
            for detail in attachment.get("details", []):
                if detail.get("name") == "networkInterfaceId":
                    enis.append(detail.get("value"))
   
    # now the ips
    ips = []
    for eni in enis:
        eni_resource = boto3.resource("ec2").NetworkInterface(eni)
        ips.append(eni_resource.association_attribute.get("PublicIp"))

    return ips

as a gist here.

Drew Bollinger
  • 156
  • 1
  • 6