abstractx1
abstractx1

Reputation: 459

Docker Go template extract image shortname

I'm looking to understand how to extract values using pattern matching, or string splitting techniques etc in the golang template. As an example, I can retrieve the following value from docker inspect:

$ docker inspect --format '{{ .Config.Image }}' hello_world-0f87ch
registry.example.com/hello_world:0.1.0

But what I need is to apply some pattern match to extract the image shortname without the tag like so:

$ docker inspect --format '{{ <some templating logic> }}' hello_world-0f87ch
hello_world

This is an example to highlight, the real case scenario sets the template format in a config file so will not have access to bash at runtime (so I can't simply pipe the result etc).

I'm new to the templating language so can someone please help with the simple check (between / and :) ?

SOLVED

Managed it with thanks to invad0r's answer. Extending what he wrote I ended up with:

'{{$v1 := split .Config.Image ":"}}{{ $v2 := join $v1 "/" }}{{$v3 := split $v2 "/"}}{{$shortName := index $v3 1}}{{$shortName}}'

Upvotes: 0

Views: 4033

Answers (2)

invad0r
invad0r

Reputation: 926

It is possible manipulate template elements see: https://docs.docker.com/config/formatting/

You can split the string and iterate over it. But I haven't found a way to get the last element.

'{{range $v := split .Config.Image "/"}}{{println $v}}{{end}}'

Upvotes: 1

David Maze
David Maze

Reputation: 159393

The core Go text/template language is fairly limited and doesn't include any sort of substring operations.

In the context you're looking at, you can use any other shell tool to do string manipulation on the output of the docker inspect

docker inspect --format '{{ .Config.Image }}' hello_world-0f87ch \
  | sed -e 's@.*/@@' -e 's@:.*@@'

(using sed to trim everything up to and including the last slash, and including and after the first colon)

A more typical workflow would involve having some sort of file checked into source control that knew what images you were trying to run (a docker-compose.yml file, a Kubernetes YAML file, a shell script with docker run commands) and use that as the main way you launch containers. It's a little unusual to have some containers running, and then want to script docker inspect to try to figure out how you launched them.

Upvotes: 0

Related Questions