How to get Task ID from within ECS container?

code picture code · Feb 16, 2018 · Viewed 10.8k times · Source

Hello I am interested in retrieving the Task ID from within inside a running container which lives inside of a EC2 host machine.

AWS ECS documentation states there is an environment variable ECS_CONTAINER_METADATA_FILE with the location of this data but will only be set/available if ECS_ENABLE_CONTAINER_METADATA variable is set to true upon cluster/EC2 instance creation. I don't see where this can be done in the aws console.

Also, the docs state that this can be done by setting this to true inside the host machine but would require to restart the docker agent.

Is there any other way to do this without having to go inside the EC2 to set this and restart the docker agent?

Answer

Ben picture Ben · Jun 12, 2018

The technique I'd use is to set the environment variable in the container definition.

If you're managing your tasks via Cloudformation, the relevant yaml looks like so:

  Taskdef:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ...
      ContainerDefinitions:
        - Name: some-name
          ...
          Environment:
            - Name: AWS_DEFAULT_REGION
              Value: !Ref AWS::Region
            - Name: ECS_ENABLE_CONTAINER_METADATA
              Value: 'true'

This technique helps you keep everything straightforward and reproducible.

If you need metadata programmatically and don't have access to the metadata file, you can query the agent's metadata endpoint:

curl http://localhost:51678/v1/metadata

Note that if you're getting this information as a running task, you may not be able to connect to the loopback device, but you can connect to the EC2 instance's own IP address.