How can I get the TaskId of a Fargate ecs Container

Question:

Similar to this question How to get Task ID from within ECS container? but I want to get the TaskId for my Fargate task. How can you do this? Like others I want this for logging information.

I’m running a Spring App with ELK stack for logging and would like if possible to include the TaskId in the logs if possible.

Edit
I actually never got this to work by the way, here is my code:

But I always get this stack trace:

Answer:

If you’re trying to get the task id in Fargate for ECS you make use of metadata endpoints.

Assuming you’re using version 1.4.0 of Fargate you can get this via a http request to ${ECS_CONTAINER_METADATA_URI_V4}/task.

An example response from this endpoint is below

As you can see you would need to parse the TaskARN to get the TaskID (it is the last part of the ARN if you split by “/”.

Amazon do specify the following in the documentation that should be noted.

For tasks using the Fargate launch type and platform versions prior to 1.4.0, the task metadata version 3 and 2 endpoint are supported. For more information, see Task Metadata Endpoint version 3 or Task Metadata Endpoint version 2.

Leave a Reply