In an AWS lambda, how do I access the image_id or tag of the launched container from within it?

Viewed 28

I have an AWS lambda built using SAM. I want to propagate the id (or, if it's easier, the tag) of a lambda's supporting docker image through to the lambda runtime function.

How do I do this?

Note: I do mean image id and NOT container id - what you'd see if you called docker image ls locally. Getting the container id / hostname is the easy bit :D

I have tried to declare a parameter in the template.yaml and have it picked up as an environment variable that way. I would prefer to define the value at most once within the template.yaml, and preferably have it auto-populated, though I am not aware of best practice there. The aim is to avoid human error. I don't want to pass the value on the command line unless I have to.

If it's too hard to get the image id then as a fallback the DockerTag would be fine. Again, I don't want this in multiple places in the template.yaml. Thanks!

Unanswered similar question: Finding the image ID of a container from within the container

1 Answers

The launched image URI is available in the packaged template file after running sam package, so it's possible to extract the tag from there.

For example, if using YAML:

grep -w ImageUri packaged.yaml | cut -d: -f3

This will find the URI in the packaged template (which looks like ImageUri: 12345.dkr.ecr.us-east-1.amazonaws.com/myrepo:mylambda-123abc-latest) and grabs the tag, which is after the 2nd :.

That said, I don't think it's a great solution. I wish there was a way using the SAM CLI.

Related