debugdockerMinor
How to let build fail when docker image size exceeds certain threshold?
Viewed 0 times
imagehowdockersizefailexceedsletthresholdwhencertain
Problem
docker images returns:REPOSITORY TAG IMAGE ID CREATED SIZE
fcc125757e66 About an hour ago 270 MBAttempts
docker images | awk '{print $6}' returns:SIZE
ago
hour
ago
ago
agoExpected outcome
270 so this could be used in an if statement:if [ VAR > 250 ] then
echo "Image too large"
exit 1
fiSolution
The output of
This just gives an output like this:
If you have multiple images, they will each be on a separate line. I'm going to assume you will only ever have one line, because it vastly simplifies the next steps.
To get rid of the
But, you probably don't want this for your bash script. Most shells don't support floating point comparisons, so inputting 90.6 would just fail. Instead, let's use
Note that I've replaced the
You can then pipe it into a shell script. I tested with this script:
Then run with:
docker images is really intended for humans, and it's not very parse-friendly. Instead, most Docker commands support a --format flag using Go templates. As you can see in the images documentation, you only really care about the .Size value, so you really want this:docker images --format "{{.Size}}"This just gives an output like this:
90.6 MBIf you have multiple images, they will each be on a separate line. I'm going to assume you will only ever have one line, because it vastly simplifies the next steps.
To get rid of the
MB, we can simply use sed:docker images --format "{{.Size}}" | sed "s/MB//g"
# => 90.6But, you probably don't want this for your bash script. Most shells don't support floating point comparisons, so inputting 90.6 would just fail. Instead, let's use
bc to truncate the number first:docker images --format "{{.Size}}" | sed "s/MB/\/1/g" | bc
# => 90Note that I've replaced the
MB with a division by 1, which truncates in bc.You can then pipe it into a shell script. I tested with this script:
VAR=$(cat)
if [ $VAR -gt "250" ]
then
echo "Image too large"
exit 1
fiThen run with:
docker images --format "{{.Size}}" | sed "s/MB/\/1/g" | bc | ./check_size.sh
# Exits with 0 (for my example)Code Snippets
docker images --format "{{.Size}}"docker images --format "{{.Size}}" | sed "s/MB//g"
# => 90.6docker images --format "{{.Size}}" | sed "s/MB/\/1/g" | bc
# => 90VAR=$(cat)
if [ $VAR -gt "250" ]
then
echo "Image too large"
exit 1
fidocker images --format "{{.Size}}" | sed "s/MB/\/1/g" | bc | ./check_size.sh
# Exits with 0 (for my example)Context
StackExchange DevOps Q#900, answer score: 7
Revisions (0)
No revisions yet.